diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/_multiprocess/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/_multiprocess/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..085958182e2246471e6d6f655ff00b6e37e3e99a --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/_multiprocess/__init__.py @@ -0,0 +1,8 @@ +#!/usr/bin/env python +# +# Author: Mike McKerns (mmckerns @caltech and @uqfoundation) +# Copyright (c) 2022-2024 The Uncertainty Quantification Foundation. +# License: 3-clause BSD. The full license text is available at: +# - https://github.com/uqfoundation/multiprocess/blob/master/LICENSE + +from _multiprocessing import * diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo-0.6.0.dist-info/INSTALLER b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo-0.6.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo-0.6.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo-0.6.0.dist-info/METADATA b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo-0.6.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..1a07cf45a2ba1c5bdbb9d56b969064328167e6d2 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo-0.6.0.dist-info/METADATA @@ -0,0 +1,499 @@ +Metadata-Version: 2.4 +Name: ai2-olmo +Version: 0.6.0 +Summary: Open Language Model (OLMo) +Author-email: Allen Institute for Artificial Intelligence +License: Apache License + Version 2.0, January 2004 + https://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 + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +Project-URL: Homepage, https://github.com/allenai/OLMo +Project-URL: Repository, https://github.com/allenai/OLMo +Requires-Python: >=3.10 +Description-Content-Type: text/markdown +License-File: LICENSE +Requires-Dist: numpy<2 +Requires-Dist: torch>=2.1 +Requires-Dist: ai2-olmo-core>=1.8.0 +Requires-Dist: omegaconf +Requires-Dist: rich +Requires-Dist: boto3 +Requires-Dist: google-cloud-storage +Requires-Dist: tokenizers +Requires-Dist: packaging +Requires-Dist: cached_path>=1.6.2 +Requires-Dist: transformers +Requires-Dist: importlib_resources +Provides-Extra: dev +Requires-Dist: ruff; extra == "dev" +Requires-Dist: mypy<1.4,>=1.0; extra == "dev" +Requires-Dist: black<24.0,>=23.1; extra == "dev" +Requires-Dist: isort<5.13,>=5.12; extra == "dev" +Requires-Dist: pytest; extra == "dev" +Requires-Dist: pytest-sphinx; extra == "dev" +Requires-Dist: twine>=1.11.0; extra == "dev" +Requires-Dist: setuptools; extra == "dev" +Requires-Dist: wheel; extra == "dev" +Requires-Dist: build; extra == "dev" +Provides-Extra: train +Requires-Dist: wandb; extra == "train" +Requires-Dist: beaker-gantry; extra == "train" +Requires-Dist: click; extra == "train" +Requires-Dist: torchmetrics; extra == "train" +Requires-Dist: smashed[remote]>=0.21.1; extra == "train" +Requires-Dist: safetensors; extra == "train" +Requires-Dist: datasets; extra == "train" +Requires-Dist: scikit-learn; extra == "train" +Requires-Dist: msgspec>=0.14.0; extra == "train" +Provides-Extra: all +Requires-Dist: ai2-olmo[dev,train]; extra == "all" +Provides-Extra: figures +Requires-Dist: matplotlib; extra == "figures" +Dynamic: license-file + +
+ +
+
+

OLMo: Open Language Model

+
+

+ + GitHub License + + + GitHub release + + + Paper URL + + + Playground + + + Discord + +

+ +# ⚠️ NOTICE ⚠️ This repository is out of date with our more recent releases and is no longer active. For the latest Olmo releases and updates, please visit: https://github.com/allenai/OLMo-core/ + +OLMo is a repository for training and using AI2's state-of-the-art open language models. It is designed by scientists, for scientists. + +## Installation + +First, install [PyTorch](https://pytorch.org) following the instructions specific to your operating system. + +For training and fine-tuning, we recommend installing from source: + +```bash +git clone https://github.com/allenai/OLMo.git +cd OLMo +pip install -e .[all] +``` +You can also install from PyPI with: +```bash +pip install ai2-olmo +``` + +## Pretraining + +OLMo pretraining follows a two-stage training procedure. +In the first stage, we train on large amounts of mostly web-based data: [OLMo-mix-1124](https://huggingface.co/datasets/allenai/olmo-mix-1124) +In the second stage, we train on a smaller amount of high-quality, targeted data: [Dolmino-mix-1124](https://huggingface.co/datasets/allenai/dolmino-mix-1124) + +You can find *all* the checkpoints, at minimum every 1000 training steps in OLMo core and Hugging Face format: + + +| Variant | OLMo Format (Stage 1) | OLMo Format (Stage 2) | Hugging Face Format | +|----------------|-----------------------------------------------------------------------------------------------------|--------|----------------------------------------------------------------------------------| +| **OLMo-2 1B** | [OLMo-2 1B](https://github.com/allenai/OLMo/blob/main/configs/official-0425/OLMo-2-0425-1B.csv) | [OLMo-2 1B](https://github.com/allenai/OLMo/blob/main/configs/official-0425/OLMo-2-0425-1B-stage2.csv) | [Hugging Face for the 1B variant](https://huggingface.co/allenai/OLMo-2-0425-1B) | +| **OLMo-2 7B** | [OLMo-2 7B](https://github.com/allenai/OLMo/blob/main/configs/official-1124/OLMo-2-1124-7B.csv) | [OLMo-2 7B](https://github.com/allenai/OLMo/blob/main/configs/official-1124/OLMo-2-1124-7B-stage2.csv) | [Hugging Face for the 7B variant](https://huggingface.co/allenai/OLMo-2-1124-7B) | +| **OLMo-2 13B** | [OLMo-2 13B](https://github.com/allenai/OLMo/blob/main/configs/official-1124/OLMo-2-1124-13B.csv) | [OLMo-2 13B](https://github.com/allenai/OLMo/blob/main/configs/official-1124/OLMo-2-1124-13B-stage2.csv) | [Hugging Face for the 13B variant](https://huggingface.co/allenai/OLMo-2-1124-13B) | +| **OLMo-2 32B** | [OLMo-2 32B](https://github.com/allenai/OLMo-core/blob/main/src/scripts/official/OLMo2-0325-32B.csv) | [OLMo-2 32B](https://github.com/allenai/OLMo-core/blob/main/src/scripts/official/OLMo-2-0325-32B-stage2.csv) | [Hugging Face for the 32B variant](https://huggingface.co/allenai/OLMo-2-0325-32B) | + +> Note: The 32B variant was trained on our new trainer. To train or fine-tune OLMo-2 32B, visit [OLMo-core](https://github.com/allenai/OLMo-core). + +### Steps to reproduce + +To reproduce any of the training processes described below, run this: + +```bash +torchrun --nproc_per_node=8 scripts/train.py {path_to_train_config} +``` + +For the training config, use any of the configs listed below. + +If you want to override any of the settings in the training config without having to write a new config every time, +you can do this: + +```bash +torchrun --nproc_per_node=8 scripts/train.py {path_to_train_config} \ + --setting1=value \ + --setting2=value \ + --setting3.subsetting1=value +``` + +The training configs below refer to training data that gets streamed in live over HTTP. +To reproduce at large scale, we recommend downloading the files locally and changing the paths to point to your +local file system. + +#### To run on Mac silicon devices: +```bash +python scripts/train.py {path_to_train_config} +``` +Example: +```bash +python scripts/train.py configs/tiny/OLMo-20M.yaml --save_overwrite +``` +> Note: You need to upgrade PyTorch to 2.5.x to run. + +### Stage 1 + +Stage 1 is the biggest stage, where we train on 4T or 5T tokens on largely web-based data. + +| | OLMo2 1B | OLMo2 7B | OLMo2 13B | +|-----------------|-----------------|-------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------| +| Number of tokens| 4 Trillion | 4 Trillion | 5 Trillion | +| Checkpoint |[stage1-step1907359-tokens4001B](https://huggingface.co/allenai/OLMo-2-0425-1B/tree/stage1-step1907359-tokens4001B)| [stage1-step928646-tokens3896B](https://huggingface.co/allenai/OLMo-2-1124-7B/tree/stage1-step928646-tokens3896B) | [stage1-step596057-tokens5001B](https://huggingface.co/allenai/OLMo-2-1124-13B/tree/stage1-step596057-tokens5001B) | +| Training config | [OLMo2-1B-stage1.yaml](configs/official-0425/OLMo2-1B-stage1.yaml) |[OLMo2-7B-stage1.yaml](configs/official-1124/OLMo2-7B-stage1.yaml) | [OLMo2-13B-stage1.yaml](configs/official-1124/OLMo2-13B-stage1.yaml) | | +| WandB | [wandb.ai/OLMo2-1B](https://api.wandb.ai/links/ai2-llm/izdtrtu0)|[wandb.ai/OLMo2-7B](https://wandb.ai/ai2-llm/OLMo-2-1124-7B/reports/OLMo-2-7B-Nov-2024--VmlldzoxMDUzMzE1OA) | [wandb.ai/OLMo2-13B](https://wandb.ai/ai2-llm/OLMo-2-1124-13B/reports/OLMo-2-13B-Nov-2024--VmlldzoxMDUzMjQxNg) | + +You can find the .csv.gz files containing the training data [here](configs/official-1124/provenance.csv). + +### Stage 2 for the 1B + +For the 1B model, we have trained three times with different data order on 50B high quality tokens, used last checkpoint of seed 42 as final checkpoint. + +| | Checkpoint | Training config | WandB | +|------------------------|-------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------|-------------| +| random seed 42069 | [stage2-ingredient1-step23852-tokens51B](https://huggingface.co/allenai/OLMo-2-0425-1B/tree/stage2-ingredient1-step23852-tokens51B) | [OLMo2-1B-stage2-seed42069.yaml](configs/official-0425/OLMo2-1B-stage2-seed42069.yaml) | [wandb.ai/OLMo2-1B](https://api.wandb.ai/links/ai2-llm/izdtrtu0) | +| random seed 666 | [stage2-ingredient2-step23852-tokens51B](https://huggingface.co/allenai/OLMo-2-0425-1B/tree/stage2-ingredient2-step23852-tokens51B) | [OLMo2-1B-stage2-seed666.yaml](configs/official-0425/OLMo2-1B-stage2-seed666.yaml) | [wandb.ai/OLMo2-1B](https://api.wandb.ai/links/ai2-llm/izdtrtu0) | +| random seed 42 (main) | [stage2-ingredient3-step23852-tokens51B](https://huggingface.co/allenai/OLMo-2-0425-1B/tree/stage2-ingredient3-step23852-tokens51B) | [OLMo2-1B-stage2-seed42.yaml](configs/official-0425/OLMo2-1B-stage2-seed42.yaml) | [wandb.ai/OLMo2-1B](https://api.wandb.ai/links/ai2-llm/izdtrtu0) | + + +### Stage 2 for the 7B + +For the 7B model, we train three times with different data order on 50B high quality tokens, and then average ("soup") the models. + +| | Checkpoint | Training config | WandB | +|------------------------|-------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------|-------------| +| random seed 42 | [stage2-ingredient1-step11931-tokens50B](https://huggingface.co/allenai/OLMo-2-1124-7B/tree/stage2-ingredient1-step11931-tokens50B) | [OLMo2-7B-stage2-seed42.yaml](configs/official-1124/OLMo2-7B-stage2-seed42.yaml) | [wandb.ai/OLMo2-7B](https://wandb.ai/ai2-llm/OLMo-2-1124-7B/reports/) | +| random seed 42069 | [stage2-ingredient2-step11931-tokens50B](https://huggingface.co/allenai/OLMo-2-1124-7B/tree/stage2-ingredient2-step11931-tokens50B) | [OLMo2-7B-stage2-seed42069.yaml](configs/official-1124/OLMo2-7B-stage2-seed42069.yaml) | [wandb.ai/OLMo2-7B](https://wandb.ai/ai2-llm/OLMo-2-1124-7B/reports/) | +| random seed 666 | [stage2-ingredient3-step11931-tokens50B](https://huggingface.co/allenai/OLMo-2-1124-7B/tree/stage2-ingredient3-step11931-tokens50B) | [OLMo2-7B-stage2-seed666.yaml](configs/official-1124/OLMo2-7B-stage2-seed666.yaml) | [wandb.ai/OLMo2-7B](https://wandb.ai/ai2-llm/OLMo-2-1124-7B/reports/) | +| **final souped model** | [main](https://huggingface.co/allenai/OLMo-2-1124-7B/tree/main) | no config, we just averaged the weights in Python | | + +The training configs linked here are set up to download the latest checkpoint after stage 1, and start training from there. + +### Stage 2 for the 13B + +For the 13B model, we train three times with different data order on 100B high quality tokens, and one more time +on 300B high quality tokens. Then we average ("soup") the models. + +| | Checkpoint | Training config | WandB | +|------------------------|----------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------|-------------| +| random seed 1110, 100B | [stage2-ingredient1-step11931-tokens100B](https://huggingface.co/allenai/OLMo-2-1124-13B/tree/stage2-ingredient1-step11931-tokens100B) | [OLMo2-13B-stage2-seed1110-100B.yaml](configs/official-1124/OLMo2-13B-stage2-seed1110-100B.yaml) | [wandb.ai/OLMo2-13B](https://wandb.ai/ai2-llm/OLMo-2-1124-13B/reports/OLMo-2-13B-Nov-2024--VmlldzoxMDUzMjQxNg) | +| random seed 2662, 100B | [stage2-ingredient2-step11931-tokens100B](https://huggingface.co/allenai/OLMo-2-1124-13B/tree/stage2-ingredient2-step11931-tokens100B) | [OLMo2-13B-stage2-seed2662-100B.yaml](configs/official-1124/OLMo2-13B-stage2-seed2662-100B.yaml) | [wandb.ai/OLMo2-13B](https://wandb.ai/ai2-llm/OLMo-2-1124-13B/reports/OLMo-2-13B-Nov-2024--VmlldzoxMDUzMjQxNg) | +| random seed 6209, 100B | [stage2-ingredient3-step11931-tokens100B](https://huggingface.co/allenai/OLMo-2-1124-13B/tree/stage2-ingredient3-step11931-tokens100B) | [OLMo2-13B-stage2-seed6209-100B.yaml](configs/official-1124/OLMo2-13B-stage2-seed6209-100B.yaml) | [wandb.ai/OLMo2-13B](https://wandb.ai/ai2-llm/OLMo-2-1124-13B/reports/OLMo-2-13B-Nov-2024--VmlldzoxMDUzMjQxNg) | +| random seed 2662, 300B | [stage2-ingredient4-step11931-tokens300B](https://huggingface.co/allenai/OLMo-2-1124-13B/tree/stage2-ingredient4-step35773-tokens300B) | [OLMo2-13B-stage2-seed2662-300B.yaml](configs/official-1124/OLMo2-13B-stage2-seed2662-300B.yaml) | [wandb.ai/OLMo2-13B](https://wandb.ai/ai2-llm/OLMo-2-1124-13B/reports/OLMo-2-13B-Nov-2024--VmlldzoxMDUzMjQxNg) | +| **final souped model** | [main](https://huggingface.co/allenai/OLMo-2-1124-13B/tree/main) | no config, we just averaged the weights in Python | | + +The training configs linked here are set up to download the latest checkpoints after stage 1, and start training from there. + +> Note: You can find all the information about the 32B in the [OLMo-core](https://github.com/allenai/OLMo-core) repository. + +## Instruction tuned variants + +For instruction tuned variants of these models, go to + * [OLMo2 1B Instruct](https://huggingface.co/allenai/OLMo-2-0425-1B-Instruct) + * [OLMo2 7B Instruct](https://huggingface.co/allenai/OLMo-2-1124-7B-Instruct) + * [OLMo2 13B Instruct](https://huggingface.co/allenai/OLMo-2-1124-13B-Instruct) + * [OLMo2 32B Instruct](https://huggingface.co/allenai/OLMo-2-0325-32B-Instruct) + +## Inference + +You can use our Hugging Face integration to run inference on the OLMo Transformers checkpoints: + +```python +from transformers import AutoModelForCausalLM, AutoTokenizer +olmo = AutoModelForCausalLM.from_pretrained("allenai/OLMo-2-0425-1B") +tokenizer = AutoTokenizer.from_pretrained("allenai/OLMo-2-0425-1B") +message = ["Language modeling is "] +inputs = tokenizer(message, return_tensors='pt', return_token_type_ids=False) +# optional verifying cuda +# inputs = {k: v.to('cuda') for k,v in inputs.items()} +# olmo = olmo.to('cuda') +response = olmo.generate(**inputs, max_new_tokens=100, do_sample=True, top_k=50, top_p=0.95) +print(tokenizer.batch_decode(response, skip_special_tokens=True)[0]) +``` + +Alternatively, with the Hugging Face pipeline abstraction: + +```python +from transformers import pipeline +olmo_pipe = pipeline("text-generation", model="allenai/OLMo-2-0425-1B") +print(olmo_pipe("Language modeling is")) +``` + +### Quantization + +```python +olmo = AutoModelForCausalLM.from_pretrained("allenai/OLMo-2-0425-1B", torch_dtype=torch.float16, load_in_8bit=True) # requires bitsandbytes +``` + +The quantized model is sensitive to input types and CUDA handling. To avoid potential issues, we recommend explicitly converting input IDs to CUDA using: `inputs.input_ids.to('cuda')` + +## Evaluation + +Additional tools for evaluating OLMo models are available at the [OLMo Eval](https://github.com/allenai/OLMo-eval) and [olmes](https://github.com/allenai/olmes) repositories. + +## Modal.com Hosting + +An example script is provided for hosting an OLMo 2 model on Modal.com using the OpenAI API in `./scripts/olmo2_modal_openai.py`. +To run that: + +1. Follow the instructions under Getting Started in [the Modal.com Guide](https://modal.com/docs/guide) to install +the Modal library and command line tools. +2. Follow the instructions under [Secrets](https://modal.com/docs/guide/secrets) in the Modal.com Guide to create a Modal secret named "example-secret-token" +that defines a value for the variable MODAL_TOKEN for your server. +3. Then run +```bash +modal deploy ./scripts/olmo2_modal_openai.py +``` + +You can check your endpoint using curl similar to the following: +```bash +curl -X POST \ + -H "Authorization: Bearer [the secret token from above]" \ + -H "Content-Type: application/json" \ + -d @body.json \ + https://[the web endpoint modal creates above]/v1/chat/completions +``` + +where `body.json` is of the form: +``` +{ + "model": "OLMo-2-1124-13B-Instruct", + "messages": [ + { + "role": "user", + "content": "Who was Alan Turing?" + } + ], + "max_tokens": 100, + "temperature": 0.9, + "stream": true +} +``` + + +## Citing + +```bibtex +@misc{olmo20242olmo2furious, + title={2 OLMo 2 Furious}, + author={Team OLMo and Pete Walsh and Luca Soldaini and Dirk Groeneveld and Kyle Lo and Shane Arora and Akshita Bhagia and Yuling Gu and Shengyi Huang and Matt Jordan and Nathan Lambert and Dustin Schwenk and Oyvind Tafjord and Taira Anderson and David Atkinson and Faeze Brahman and Christopher Clark and Pradeep Dasigi and Nouha Dziri and Michal Guerquin and Hamish Ivison and Pang Wei Koh and Jiacheng Liu and Saumya Malik and William Merrill and Lester James V. Miranda and Jacob Morrison and Tyler Murray and Crystal Nam and Valentina Pyatkin and Aman Rangapur and Michael Schmitz and Sam Skjonsberg and David Wadden and Christopher Wilhelm and Michael Wilson and Luke Zettlemoyer and Ali Farhadi and Noah A. Smith and Hannaneh Hajishirzi}, + year={2024}, + eprint={2501.00656}, + archivePrefix={arXiv}, + primaryClass={cs.CL}, + url={https://arxiv.org/abs/2501.00656}, +} +``` diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo-0.6.0.dist-info/RECORD b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo-0.6.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..797eb5a8efe6e2837b659ff6808738303d1d7610 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo-0.6.0.dist-info/RECORD @@ -0,0 +1,790 @@ +ai2_olmo-0.6.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +ai2_olmo-0.6.0.dist-info/METADATA,sha256=Jd-MgYtyMIcI_2owy0TqDE0FQXAfRAo_JNKl1qz3OSg,32380 +ai2_olmo-0.6.0.dist-info/RECORD,, +ai2_olmo-0.6.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91 +ai2_olmo-0.6.0.dist-info/direct_url.json,sha256=nBAoZADlhg6RHcKwaBzigWDpbV7TgGWaE1AnkcmFxL0,161 +ai2_olmo-0.6.0.dist-info/licenses/LICENSE,sha256=YvuKOpYh3COIF0yqq-nCMXtpS7mh1GyYvPVlW2j1G-M,11359 +ai2_olmo-0.6.0.dist-info/top_level.txt,sha256=aCGcPHL7HW-22cOx3hvo5UwgKe4NHRTgmnHSVtggBwQ,23 +hf_olmo/__init__.py,sha256=LHYwPvSijoOlPKBehe1MM2b-yc9oADmx__wi5OFhLLs,140 +hf_olmo/__pycache__/__init__.cpython-310.pyc,, +hf_olmo/__pycache__/configuration_olmo.cpython-310.pyc,, +hf_olmo/__pycache__/convert_olmo_to_hf.cpython-310.pyc,, +hf_olmo/__pycache__/modeling_olmo.cpython-310.pyc,, +hf_olmo/__pycache__/tokenization_olmo_fast.cpython-310.pyc,, +hf_olmo/configuration_olmo.py,sha256=-v3MFk0BawrgkjPvha4XhwtbyZ-tJUe-RqjUjUCIbY8,2073 +hf_olmo/convert_olmo_to_hf.py,sha256=PstmhWk3UFPI_oSVN702uhaRGlk-s6_ibBzuxPOhd_o,11057 +hf_olmo/modeling_olmo.py,sha256=ulEZ2g8b0Z9xQXCvOlJgXBN53bAPFZKH7B9JWm1D3H8,11006 +hf_olmo/tokenization_olmo_fast.py,sha256=vY1ZT9izLNoutepHikzpdEJWbD7ht8_luWclhWXeodY,645 +olmo/__init__.py,sha256=XHuHnEIFs0Q5aigoEADYkMEirhlvPnuVPuG7tIjEk8I,314 +olmo/__pycache__/__init__.cpython-310.pyc,, +olmo/__pycache__/aliases.cpython-310.pyc,, +olmo/__pycache__/beam_search.cpython-310.pyc,, +olmo/__pycache__/checkpoint.cpython-310.pyc,, +olmo/__pycache__/config.cpython-310.pyc,, +olmo/__pycache__/exceptions.cpython-310.pyc,, +olmo/__pycache__/initialization.cpython-310.pyc,, +olmo/__pycache__/model.cpython-310.pyc,, +olmo/__pycache__/optim.cpython-310.pyc,, +olmo/__pycache__/safetensors_util.cpython-310.pyc,, +olmo/__pycache__/tokenizer.cpython-310.pyc,, +olmo/__pycache__/torch_util.cpython-310.pyc,, +olmo/__pycache__/train.cpython-310.pyc,, +olmo/__pycache__/util.cpython-310.pyc,, +olmo/__pycache__/version.cpython-310.pyc,, +olmo/aliases.py,sha256=x4w3ViALWYVVFgrzu4uu1lnbLAt8SVN30JPraVp6d0Q,109 +olmo/beam_search.py,sha256=inkGUDmxdneo4B6fMyzHLx3Rkk1WgfOuDdckA7JL0dM,46609 +olmo/checkpoint.py,sha256=lomJDfhzKa_4u-0WrMp843iTfRqPXgmvWI7oFCvskl0,88510 +olmo/config.py,sha256=6AaShfDEb0-3-gdE40uOTVNAhHr2Zcj56w6InlL314A,41619 +olmo/data/__init__.py,sha256=pDaIBwcEI2AdNyba9oTDfR4RlnbobJ0LlyvoNuwOBbk,7589 +olmo/data/__pycache__/__init__.cpython-310.pyc,, +olmo/data/__pycache__/collator.cpython-310.pyc,, +olmo/data/__pycache__/custom_datasets.cpython-310.pyc,, +olmo/data/__pycache__/iterable_dataset.cpython-310.pyc,, +olmo/data/__pycache__/memmap_dataset.cpython-310.pyc,, +olmo/data/__pycache__/named_data_mixes.cpython-310.pyc,, +olmo/data/__pycache__/util.cpython-310.pyc,, +olmo/data/collator.py,sha256=c9Yq5Ff5d5DODCP1eSHJRYUHsYNCCu1gP0e4J0Pe5ns,6896 +olmo/data/custom_datasets.py,sha256=HZbvIpTBfFlYkw5vhaOH6nn2m1uDf3WWPaEQVqzwgiM,2494 +olmo/data/iterable_dataset.py,sha256=p4XjNfyqNs9q1ilYqYd3wMQB4dIsxBnLuIZWI295FQM,8582 +olmo/data/memmap_dataset.py,sha256=jijM2I6qqA_8DonRl_rwFf4KZ2rwHJR50M63Cf66i4E,10837 +olmo/data/named_data_mixes.py,sha256=CGyyLsCXdclC2iI5k8IaslP5qAiPZcWBz4ufQZzhCBw,384860 +olmo/data/util.py,sha256=Oyv-L8d_601t4iezJN2DHKm4igYEJFmhg1M5oB3hY2s,5570 +olmo/eval/__init__.py,sha256=yASL8-7QaFSp87lc12C3bz9WnK4BgA0TPhjhuI7iCGo,3923 +olmo/eval/__pycache__/__init__.cpython-310.pyc,, +olmo/eval/__pycache__/downstream.cpython-310.pyc,, +olmo/eval/__pycache__/evaluator.cpython-310.pyc,, +olmo/eval/downstream.py,sha256=GVjQtKPoVI2LdPGJeQHL6-sKTxLf2wQpnIo1zLg0SD8,88879 +olmo/eval/evaluator.py,sha256=kvimeM1XpzpK5e1tBW8Mp2trNrJSTeqQFNkPKQoHNNI,3545 +olmo/exceptions.py,sha256=WZrZIRmtHeDvzvZeGFinIOfw9RUYlrqJqIChsqhV1nk,838 +olmo/initialization.py,sha256=lVU3Qqi0cOwTXj7Y16tc5qgKzmTVSnCbl4Qyx53gaz4,597 +olmo/model.py,sha256=hq--iR1tfwgiOJf5K6CX1KNJd8_fEcssF5MFiN15VTM,78313 +olmo/optim.py,sha256=rgKKrk5BYKuEYHhmW4m4BU7YTVeOHhKUi9JcybWVPNs,47138 +olmo/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +olmo/safetensors_util.py,sha256=9uxbQPJJMqEwZzc6vCkuT7SqC4gSTDImnjgUadWLvzw,2448 +olmo/tokenizer.py,sha256=JC12rJoCjdAm2YySYFf2t3MAhcJs18v691sfzrkpIU4,8034 +olmo/torch_util.py,sha256=tqB2XnnpETntgeDQqXBcWsTS44WMTn6VlL8hRUpws8w,5105 +olmo/train.py,sha256=dbYzAu-odS8_1nwVgLq1HBKDzA06A6SuNH2RgCMbUxY,59922 +olmo/util.py,sha256=SF7cJcGlPU3sN0LXZ3HYtBxUE8_7h6JuB1aq8WUMR3w,34093 +olmo/version.py,sha256=pY-GchL4Y3ZEJam6Cb444PhHVsMIHGkZAywXtaCLyis,407 +olmo_data/__init__.py,sha256=zCyaiU_R6WB1U8RWu74iAZTG2C6vdfMNHvRJtUZutPg,20 +olmo_data/__pycache__/__init__.cpython-310.pyc,, +olmo_data/__pycache__/data.cpython-310.pyc,, +olmo_data/data.py,sha256=anTu5TrZEjP6tt-UGgSMVKpEzbRykkYXUJtc4qFElvY,750 +olmo_data/hf_datasets/ai2_arc/ARC-Challenge/validation/data-00000-of-00001.arrow,sha256=TPWbMhBmticWjYp7TA3etcKbXbaoCDBWhxuqlD1bDJA,98080 +olmo_data/hf_datasets/ai2_arc/ARC-Challenge/validation/dataset_info.json,sha256=iZumP5Udu8LD7cbew3o7nNpnGu-o9jPaMxUrNDDNIVY,1795 +olmo_data/hf_datasets/ai2_arc/ARC-Challenge/validation/state.json,sha256=6Q1XhM-HMZcymuGAKBC_8RjMBKgJSaR_6lLUO9Z8XwE,255 +olmo_data/hf_datasets/ai2_arc/ARC-Easy/validation/data-00000-of-00001.arrow,sha256=RKy-o4FsJcIWEMo5D75WfcPaSMi1uRORIkViY2hyR0s,158824 +olmo_data/hf_datasets/ai2_arc/ARC-Easy/validation/dataset_info.json,sha256=ej_Dxdcputu2j1z-gXm40vKC-XXmtA9u7wytWTEMC0E,1777 +olmo_data/hf_datasets/ai2_arc/ARC-Easy/validation/state.json,sha256=7ti_cOyLLnyQAA32MFtrsbhRcMHNb_FRafLJrF7HnUA,255 +olmo_data/hf_datasets/allenai/basic_arithmetic/none/validation/data-00000-of-00001.arrow,sha256=yqM0-EbGWPOo-Zi-G8h_kf0o1xZkRow8AQ8V_wWcnRA,357496 +olmo_data/hf_datasets/allenai/basic_arithmetic/none/validation/dataset_info.json,sha256=lh6HaB3rCLnh5gugo3-5hig264o1dJSgKxpbX8CDw0M,1318 +olmo_data/hf_datasets/allenai/basic_arithmetic/none/validation/state.json,sha256=8mkvdVYsbNxQ0EbFtq_x_KBpdmrLIdeiFco_itzABjg,255 +olmo_data/hf_datasets/boolq/none/validation/data-00000-of-00001.arrow,sha256=-FgCBXZFLnBrYCv5rSjgnVCebatMl8sBoiAqJHLJr8k,1999832 +olmo_data/hf_datasets/boolq/none/validation/dataset_info.json,sha256=9fkOOIM874JzMu0zy-p90u2glDQQNWdh8Lbqvl0yl6s,1222 +olmo_data/hf_datasets/boolq/none/validation/state.json,sha256=OBBL6PhQcju6tckGNO_WsHalIUQNrYkqWRXusdaAVeQ,255 +olmo_data/hf_datasets/glue/mrpc/validation/data-00000-of-00001.arrow,sha256=6RNrUFkv1bT9mwcs5_xdi4EZhoxgA_Qc-6Uc48QfUYs,106816 +olmo_data/hf_datasets/glue/mrpc/validation/dataset_info.json,sha256=9iJr9w75-gZFJBWnbsU3COqMsSC1XdS167MaCap6rK0,1617 +olmo_data/hf_datasets/glue/mrpc/validation/state.json,sha256=NEcKEJY5my-sJTla-TOSM4OrCyN1tiYYh18Epl8xNag,255 +olmo_data/hf_datasets/glue/rte/validation/data-00000-of-00001.arrow,sha256=fNGHSBCbSkNPyb7ck3Kp44f64m__fiKDgrsVownwJT4,91664 +olmo_data/hf_datasets/glue/rte/validation/dataset_info.json,sha256=gQJibTUoZpOlsEKYbAWylXpmaQPBDP0ikMizRWuSzZI,1612 +olmo_data/hf_datasets/glue/rte/validation/state.json,sha256=9uXN2UeFtlyy1CLsfTBX2kmVEgaQMaDuOuxwtNmjc5I,255 +olmo_data/hf_datasets/glue/sst2/validation/data-00000-of-00001.arrow,sha256=d8XIS9PS33fFm69HUCJIC-0-qPVvoSweq2mmPlNxOE4,107008 +olmo_data/hf_datasets/glue/sst2/validation/dataset_info.json,sha256=reaaBN5hpSB7qbeItazp_SK3Z6b50FDTULdr7gR3CyM,1537 +olmo_data/hf_datasets/glue/sst2/validation/state.json,sha256=4wdbK9t9M0lCpkAHR2zqWT4lt76ayRH__3glclcQSYo,255 +olmo_data/hf_datasets/hails/mmlu_no_train/abstract_algebra/dev/data-00000-of-00001.arrow,sha256=GFHWfK9rZBEWAjQtnViE2fddMuk-_VLpZYbEBNwiB_g,1984 +olmo_data/hf_datasets/hails/mmlu_no_train/abstract_algebra/dev/dataset_info.json,sha256=dNVmMyX3t9NqfAcxj2uhby9di-xHL7u-c4wsjvVrGXQ,1965 +olmo_data/hf_datasets/hails/mmlu_no_train/abstract_algebra/dev/state.json,sha256=8YecJTgLaXtWH33NwCMO2HKZZPo895GNFw6pdu003Co,248 +olmo_data/hf_datasets/hails/mmlu_no_train/abstract_algebra/test/data-00000-of-00001.arrow,sha256=GI1UvovOWzAjH45VntW50PYDHbXQWch0ONo-HzwTXEE,22400 +olmo_data/hf_datasets/hails/mmlu_no_train/abstract_algebra/test/dataset_info.json,sha256=dNVmMyX3t9NqfAcxj2uhby9di-xHL7u-c4wsjvVrGXQ,1965 +olmo_data/hf_datasets/hails/mmlu_no_train/abstract_algebra/test/state.json,sha256=riXPh4NQiYvkfMORq980hw2EuVxqq-8tt287yVb5xZM,249 +olmo_data/hf_datasets/hails/mmlu_no_train/abstract_algebra/validation/data-00000-of-00001.arrow,sha256=sG_EPnA3JLiBFlB0D0jhOIop_XmjbXHvksbRtJxlv00,3296 +olmo_data/hf_datasets/hails/mmlu_no_train/abstract_algebra/validation/dataset_info.json,sha256=dNVmMyX3t9NqfAcxj2uhby9di-xHL7u-c4wsjvVrGXQ,1965 +olmo_data/hf_datasets/hails/mmlu_no_train/abstract_algebra/validation/state.json,sha256=_hKarIdq3gF6ksK2QMU_tvYZWc8mxydapHNd8SIjEzM,255 +olmo_data/hf_datasets/hails/mmlu_no_train/anatomy/dev/data-00000-of-00001.arrow,sha256=biYfUZjzNgrIXDDfSyjoqA_B4gD6leowG0zxyPILbiE,2080 +olmo_data/hf_datasets/hails/mmlu_no_train/anatomy/dev/dataset_info.json,sha256=fHzfhjDXkePMb7d1_HxXCS7XzxG1l9XuZjznT8W36iw,1957 +olmo_data/hf_datasets/hails/mmlu_no_train/anatomy/dev/state.json,sha256=8FzsHgQC1RCDQUEjkZ711v9C99CNS33K13SEEmUkwFE,248 +olmo_data/hf_datasets/hails/mmlu_no_train/anatomy/test/data-00000-of-00001.arrow,sha256=W6NU63KrNIwa8YpfMu_IWt1xE8Wjsk7u82t6yvMCtBY,35664 +olmo_data/hf_datasets/hails/mmlu_no_train/anatomy/test/dataset_info.json,sha256=fHzfhjDXkePMb7d1_HxXCS7XzxG1l9XuZjznT8W36iw,1957 +olmo_data/hf_datasets/hails/mmlu_no_train/anatomy/test/state.json,sha256=yn83DyEC07El6-Sma_BMDBVXkhuYD4ldTm6LDzvqdjw,249 +olmo_data/hf_datasets/hails/mmlu_no_train/anatomy/validation/data-00000-of-00001.arrow,sha256=1OH3OueaiALgRHaJi1strOwwM5Hwrzt4E1w6Ia9V880,4368 +olmo_data/hf_datasets/hails/mmlu_no_train/anatomy/validation/dataset_info.json,sha256=fHzfhjDXkePMb7d1_HxXCS7XzxG1l9XuZjznT8W36iw,1957 +olmo_data/hf_datasets/hails/mmlu_no_train/anatomy/validation/state.json,sha256=CN0E7Gb9mTn9PQX33xjSiuCA2kg052B41i7iOtUUz28,255 +olmo_data/hf_datasets/hails/mmlu_no_train/astronomy/dev/data-00000-of-00001.arrow,sha256=iuiuu6PvJxS08L7ma0HVz2vw1cLLGErJ1dbiEFbdv8o,3192 +olmo_data/hf_datasets/hails/mmlu_no_train/astronomy/dev/dataset_info.json,sha256=NcccfDPprYItb7PSlk_F0wfrv64e48qQ1JpvCkk7ssg,1959 +olmo_data/hf_datasets/hails/mmlu_no_train/astronomy/dev/state.json,sha256=ritTyFwEvQmpe7V9xVHJ_velZIW1-jFpg3zNRQM_N0Y,248 +olmo_data/hf_datasets/hails/mmlu_no_train/astronomy/test/data-00000-of-00001.arrow,sha256=U3kILePIrZUxCbj-NACGy2-3KN37Xtfz29IK07fXIAg,49816 +olmo_data/hf_datasets/hails/mmlu_no_train/astronomy/test/dataset_info.json,sha256=NcccfDPprYItb7PSlk_F0wfrv64e48qQ1JpvCkk7ssg,1959 +olmo_data/hf_datasets/hails/mmlu_no_train/astronomy/test/state.json,sha256=fjnBxdW0geGF-fiFAMQxXQOG_cBJSINT7BVM45ioNUo,249 +olmo_data/hf_datasets/hails/mmlu_no_train/astronomy/validation/data-00000-of-00001.arrow,sha256=Ckw5eFvsCPTdEKt4SD4xmgE7LNOpmh-nQxLEEjL6nrk,6304 +olmo_data/hf_datasets/hails/mmlu_no_train/astronomy/validation/dataset_info.json,sha256=NcccfDPprYItb7PSlk_F0wfrv64e48qQ1JpvCkk7ssg,1959 +olmo_data/hf_datasets/hails/mmlu_no_train/astronomy/validation/state.json,sha256=wUD_-TfkPL1ANDUAIWGcY2l7veII2nBHCKxvVCE--KU,255 +olmo_data/hf_datasets/hails/mmlu_no_train/business_ethics/dev/data-00000-of-00001.arrow,sha256=EELTLOMWicg8yGruITnOsgGd0ttQjJmvP8jKjIxq4ZE,3344 +olmo_data/hf_datasets/hails/mmlu_no_train/business_ethics/dev/dataset_info.json,sha256=l4Jwz_nvMUuIr_J8GpdSiUr6Q8D9ub1dOfhQ8ONNjvY,1965 +olmo_data/hf_datasets/hails/mmlu_no_train/business_ethics/dev/state.json,sha256=dUKwJW4nfcj7dLGPm_G3RflsXYRfPw_9LbHwG1d26E0,248 +olmo_data/hf_datasets/hails/mmlu_no_train/business_ethics/test/data-00000-of-00001.arrow,sha256=3NtygFeaiiFpHAEewGYrD7hQBcJPkZwxr5uXdf0emKA,36224 +olmo_data/hf_datasets/hails/mmlu_no_train/business_ethics/test/dataset_info.json,sha256=l4Jwz_nvMUuIr_J8GpdSiUr6Q8D9ub1dOfhQ8ONNjvY,1965 +olmo_data/hf_datasets/hails/mmlu_no_train/business_ethics/test/state.json,sha256=WxMDzl_B3yWIKmWY17Ujo52ARsbWYWJ5qN2PwxKRLTk,249 +olmo_data/hf_datasets/hails/mmlu_no_train/business_ethics/validation/data-00000-of-00001.arrow,sha256=B-gdFSqM9Emo72wC422_4LgbBCMSrzeB3vkKd6Sm8Go,4312 +olmo_data/hf_datasets/hails/mmlu_no_train/business_ethics/validation/dataset_info.json,sha256=l4Jwz_nvMUuIr_J8GpdSiUr6Q8D9ub1dOfhQ8ONNjvY,1965 +olmo_data/hf_datasets/hails/mmlu_no_train/business_ethics/validation/state.json,sha256=2Whvoh9U6D81DtQE6zAfjCqm4uFThkcNENcYeVilG_A,255 +olmo_data/hf_datasets/hails/mmlu_no_train/clinical_knowledge/dev/data-00000-of-00001.arrow,sha256=ttyQwDdgtVQ8Rk0zOT7GDawo0x5-DIU66ZbCtwLFtO0,2384 +olmo_data/hf_datasets/hails/mmlu_no_train/clinical_knowledge/dev/dataset_info.json,sha256=eEVkx2h8qmM63PNtNB9rXYz6RoK-cnVWqAxgT9jvP2M,1968 +olmo_data/hf_datasets/hails/mmlu_no_train/clinical_knowledge/dev/state.json,sha256=IEaTas-Y7MGQPm6Ol_QsWVTeYIBQwfM7St41P1hhtoU,248 +olmo_data/hf_datasets/hails/mmlu_no_train/clinical_knowledge/test/data-00000-of-00001.arrow,sha256=vsB2yWaBPUIFXSXqFpchnpHineMH3L0B7GtWgZgGkNM,69640 +olmo_data/hf_datasets/hails/mmlu_no_train/clinical_knowledge/test/dataset_info.json,sha256=eEVkx2h8qmM63PNtNB9rXYz6RoK-cnVWqAxgT9jvP2M,1968 +olmo_data/hf_datasets/hails/mmlu_no_train/clinical_knowledge/test/state.json,sha256=HEgEUbSkM7jh1ldWVfnRTuFIcNM0GiC0cLgAQg4y4TM,249 +olmo_data/hf_datasets/hails/mmlu_no_train/clinical_knowledge/validation/data-00000-of-00001.arrow,sha256=D0EzMakm2-3kRskFPBehhYccRWz5mq8GpS0_q4WBums,8360 +olmo_data/hf_datasets/hails/mmlu_no_train/clinical_knowledge/validation/dataset_info.json,sha256=eEVkx2h8qmM63PNtNB9rXYz6RoK-cnVWqAxgT9jvP2M,1968 +olmo_data/hf_datasets/hails/mmlu_no_train/clinical_knowledge/validation/state.json,sha256=vhSAWxQ0WVAi0gpZxAB8VI4hP-xLMCxHGB0s9Ce7wH8,255 +olmo_data/hf_datasets/hails/mmlu_no_train/college_biology/dev/data-00000-of-00001.arrow,sha256=y6DPiCNe_KFf5sB9_IN8i1veGUD5773Qr26qOq4to2U,2688 +olmo_data/hf_datasets/hails/mmlu_no_train/college_biology/dev/dataset_info.json,sha256=9a1vyi7IwBpqLYzOi6D5TXzzY3M7doYVoWh8rlzGXE0,1965 +olmo_data/hf_datasets/hails/mmlu_no_train/college_biology/dev/state.json,sha256=Zo6BPVJvlcPKZ8fQv7TitLoUpV94n43Pt0oPFBWUlB4,248 +olmo_data/hf_datasets/hails/mmlu_no_train/college_biology/test/data-00000-of-00001.arrow,sha256=kftWDt0JYsLgmg1ELGromsV6atK_urCnFxP3JyZ7Kbk,52600 +olmo_data/hf_datasets/hails/mmlu_no_train/college_biology/test/dataset_info.json,sha256=9a1vyi7IwBpqLYzOi6D5TXzzY3M7doYVoWh8rlzGXE0,1965 +olmo_data/hf_datasets/hails/mmlu_no_train/college_biology/test/state.json,sha256=14EdN4YTubTAbDqNuPG6l3m9Xs1PxKJsPSDM-x-Jiwc,249 +olmo_data/hf_datasets/hails/mmlu_no_train/college_biology/validation/data-00000-of-00001.arrow,sha256=UFaTeB-Xc2Mj3KAzEYJyWxxXFPi9DPCL8vxpbAuOgvM,6192 +olmo_data/hf_datasets/hails/mmlu_no_train/college_biology/validation/dataset_info.json,sha256=9a1vyi7IwBpqLYzOi6D5TXzzY3M7doYVoWh8rlzGXE0,1965 +olmo_data/hf_datasets/hails/mmlu_no_train/college_biology/validation/state.json,sha256=zEFm5h6FFUDzw7wXnh2WzNCMvva0PZe5M_ZkzHYsxPM,255 +olmo_data/hf_datasets/hails/mmlu_no_train/college_chemistry/dev/data-00000-of-00001.arrow,sha256=XMhExGTaJzCrj7wEMLC3Q6Z-SP_67GdghKGkFaP2xXM,2488 +olmo_data/hf_datasets/hails/mmlu_no_train/college_chemistry/dev/dataset_info.json,sha256=roKxaPz8_llrRMnPwqQT5NBHjb3ysdrd4gX2qqtN_9Q,1966 +olmo_data/hf_datasets/hails/mmlu_no_train/college_chemistry/dev/state.json,sha256=Qr3wHpC5G91MrCjGIVKjO_LvWK_xAJgmAceHqnd_kog,248 +olmo_data/hf_datasets/hails/mmlu_no_train/college_chemistry/test/data-00000-of-00001.arrow,sha256=6ev3V28XKrAygkkrQHTM7bG1cUnqYor7GJW8_VzL0tE,27880 +olmo_data/hf_datasets/hails/mmlu_no_train/college_chemistry/test/dataset_info.json,sha256=roKxaPz8_llrRMnPwqQT5NBHjb3ysdrd4gX2qqtN_9Q,1966 +olmo_data/hf_datasets/hails/mmlu_no_train/college_chemistry/test/state.json,sha256=xLsDBcPjmKks95OThOxWFEJHPfSGFNLrTNNiEWuVT-w,249 +olmo_data/hf_datasets/hails/mmlu_no_train/college_chemistry/validation/data-00000-of-00001.arrow,sha256=_eXrBXNuGHbcJ_rjxQdwMhYIgCz-SnvknbO023eFwTU,3568 +olmo_data/hf_datasets/hails/mmlu_no_train/college_chemistry/validation/dataset_info.json,sha256=roKxaPz8_llrRMnPwqQT5NBHjb3ysdrd4gX2qqtN_9Q,1966 +olmo_data/hf_datasets/hails/mmlu_no_train/college_chemistry/validation/state.json,sha256=dvvYYeAPCvkZZ7kCs6Uh5mReXCdqN5bbTC4_-TWHCsw,255 +olmo_data/hf_datasets/hails/mmlu_no_train/college_computer_science/dev/data-00000-of-00001.arrow,sha256=PPXw_GDT2QbZK-CZ0vWmL8HYDar4K-EU-9GrkDWng1Q,3960 +olmo_data/hf_datasets/hails/mmlu_no_train/college_computer_science/dev/dataset_info.json,sha256=uh6mCRYbX-8podnIGR1kmAv-ialWLU1JrLHEWvl4W08,1974 +olmo_data/hf_datasets/hails/mmlu_no_train/college_computer_science/dev/state.json,sha256=dI1DLENiK1PsAsrFDMqaPlxVntdBn9wldPUWpf4Tokc,248 +olmo_data/hf_datasets/hails/mmlu_no_train/college_computer_science/test/data-00000-of-00001.arrow,sha256=NmA6gc4OfbwWzmEDvrlUR7MnMpKR7QkzMHjYYHrnGCk,46504 +olmo_data/hf_datasets/hails/mmlu_no_train/college_computer_science/test/dataset_info.json,sha256=uh6mCRYbX-8podnIGR1kmAv-ialWLU1JrLHEWvl4W08,1974 +olmo_data/hf_datasets/hails/mmlu_no_train/college_computer_science/test/state.json,sha256=CLCBK1cLhNaSKCWgAau4ZczizdKPmwsZgHq2zerpp1s,249 +olmo_data/hf_datasets/hails/mmlu_no_train/college_computer_science/validation/data-00000-of-00001.arrow,sha256=byMZvSzzZPrMSqozW7TbPNZbZECGyFqbdJTuPEEbI_8,6024 +olmo_data/hf_datasets/hails/mmlu_no_train/college_computer_science/validation/dataset_info.json,sha256=uh6mCRYbX-8podnIGR1kmAv-ialWLU1JrLHEWvl4W08,1974 +olmo_data/hf_datasets/hails/mmlu_no_train/college_computer_science/validation/state.json,sha256=HLHpAwONkkDWexw6Jq31mwdbxvNfV2FU_gnqGwmavbs,255 +olmo_data/hf_datasets/hails/mmlu_no_train/college_mathematics/dev/data-00000-of-00001.arrow,sha256=AnRLzcuAjNo99HUPuIBbpvLc_sNCL4uXTt2s0WqAwys,2664 +olmo_data/hf_datasets/hails/mmlu_no_train/college_mathematics/dev/dataset_info.json,sha256=IhBACIx9oW99wBP545wYEsfO-jmyG2xWQ28sIpJ4r9c,1969 +olmo_data/hf_datasets/hails/mmlu_no_train/college_mathematics/dev/state.json,sha256=UZBusoaSu1Cxe25IEDGbu3vRP-QdXvkQ6H0Knby_m80,248 +olmo_data/hf_datasets/hails/mmlu_no_train/college_mathematics/test/data-00000-of-00001.arrow,sha256=YP6jdcZNC3E7Ci4oZTO_QDzogvTFuxi-FyaDwdgTdAM,28080 +olmo_data/hf_datasets/hails/mmlu_no_train/college_mathematics/test/dataset_info.json,sha256=IhBACIx9oW99wBP545wYEsfO-jmyG2xWQ28sIpJ4r9c,1969 +olmo_data/hf_datasets/hails/mmlu_no_train/college_mathematics/test/state.json,sha256=tvE4YEUu7jV8pvbNriBKdPz_vIB6lW0EPxfNI4jLe_0,249 +olmo_data/hf_datasets/hails/mmlu_no_train/college_mathematics/validation/data-00000-of-00001.arrow,sha256=49cUWH_4YTa_P08olgTmUMzEyWf3OR7t_BaV3oX4sUs,3984 +olmo_data/hf_datasets/hails/mmlu_no_train/college_mathematics/validation/dataset_info.json,sha256=IhBACIx9oW99wBP545wYEsfO-jmyG2xWQ28sIpJ4r9c,1969 +olmo_data/hf_datasets/hails/mmlu_no_train/college_mathematics/validation/state.json,sha256=UqOgG5wT8f0GzVh7Zbqa5nsJI-ATIyBVb2_L8Gk-sB4,255 +olmo_data/hf_datasets/hails/mmlu_no_train/college_medicine/dev/data-00000-of-00001.arrow,sha256=gOKtjOGyQrBREfmMc8yn5cOPCac0MKXaetWCKxQPQfo,2824 +olmo_data/hf_datasets/hails/mmlu_no_train/college_medicine/dev/dataset_info.json,sha256=2um5PIiOECdJWRIK1dF4WIUp5m3Bp7qBJhC1YG_Bc2c,1966 +olmo_data/hf_datasets/hails/mmlu_no_train/college_medicine/dev/state.json,sha256=hw_WI8w4t6q8uMxM9ilx10HHt3ElkjPyYGS6gWPTTjM,248 +olmo_data/hf_datasets/hails/mmlu_no_train/college_medicine/test/data-00000-of-00001.arrow,sha256=gEuBqzhP2Fp6sHDL7-2ReIRF9_s4f8rrGd5ZKoIr3Gg,86912 +olmo_data/hf_datasets/hails/mmlu_no_train/college_medicine/test/dataset_info.json,sha256=2um5PIiOECdJWRIK1dF4WIUp5m3Bp7qBJhC1YG_Bc2c,1966 +olmo_data/hf_datasets/hails/mmlu_no_train/college_medicine/test/state.json,sha256=UVsXY8ybcqT4Q1A6VQgvs4qbqaCEMADE35I587WYww8,249 +olmo_data/hf_datasets/hails/mmlu_no_train/college_medicine/validation/data-00000-of-00001.arrow,sha256=paSq2jKvmLhXLtbhLCc5neaaPx4KYZa2-eKb1SYW_0U,9416 +olmo_data/hf_datasets/hails/mmlu_no_train/college_medicine/validation/dataset_info.json,sha256=2um5PIiOECdJWRIK1dF4WIUp5m3Bp7qBJhC1YG_Bc2c,1966 +olmo_data/hf_datasets/hails/mmlu_no_train/college_medicine/validation/state.json,sha256=xut-nB9N8O5MlwCxD1CNGlgfKoYnnQuQvE_0aCcVyVQ,255 +olmo_data/hf_datasets/hails/mmlu_no_train/college_physics/dev/data-00000-of-00001.arrow,sha256=tiyCsd6SjLdeUT62KMIh7Umt4RywPVbgoezoMXWqmNQ,2568 +olmo_data/hf_datasets/hails/mmlu_no_train/college_physics/dev/dataset_info.json,sha256=9r2nrNCnsjRwVHzIexlHRFGOF5MBwMYO8oeFE4TattU,1965 +olmo_data/hf_datasets/hails/mmlu_no_train/college_physics/dev/state.json,sha256=cmdY0z54ZphsJVus44i2IcDePl0gxgvJgdYOyl3l-As,248 +olmo_data/hf_datasets/hails/mmlu_no_train/college_physics/test/data-00000-of-00001.arrow,sha256=xo41Rcrev-kNHj654TKuksAni-XErrDk2nchfTUTE1s,33192 +olmo_data/hf_datasets/hails/mmlu_no_train/college_physics/test/dataset_info.json,sha256=9r2nrNCnsjRwVHzIexlHRFGOF5MBwMYO8oeFE4TattU,1965 +olmo_data/hf_datasets/hails/mmlu_no_train/college_physics/test/state.json,sha256=CW6Br7cOTNI1MwmXfj2HeatggUCdP5Rb7q0zk1LQ_1w,249 +olmo_data/hf_datasets/hails/mmlu_no_train/college_physics/validation/data-00000-of-00001.arrow,sha256=2ZuWVNLJB7c8NXT7XtgOYbzni3DRWF_NN9PrdaWN00k,4760 +olmo_data/hf_datasets/hails/mmlu_no_train/college_physics/validation/dataset_info.json,sha256=9r2nrNCnsjRwVHzIexlHRFGOF5MBwMYO8oeFE4TattU,1965 +olmo_data/hf_datasets/hails/mmlu_no_train/college_physics/validation/state.json,sha256=hN_Lw8Qvsfs9fY1tTkIbIsuJpXGyDBS4Rw13XGwjg7E,255 +olmo_data/hf_datasets/hails/mmlu_no_train/computer_security/dev/data-00000-of-00001.arrow,sha256=qhjvHfUlEd0RJzTY2R3Lup1-leGu7KCOrmEUoEYNIwI,2264 +olmo_data/hf_datasets/hails/mmlu_no_train/computer_security/dev/dataset_info.json,sha256=6YP9VRTJQf_cFtU69McMY4vedPweo4Dkiqb8297IWuU,1967 +olmo_data/hf_datasets/hails/mmlu_no_train/computer_security/dev/state.json,sha256=omz2HWem1mewOCuFQkoJVC0t62lXx9Z9cpXEaPZzfdc,248 +olmo_data/hf_datasets/hails/mmlu_no_train/computer_security/test/data-00000-of-00001.arrow,sha256=3R01uY7aIiqQ0nh2x_Sn_IxBRKGPD3fhYhiobvdpRkE,30296 +olmo_data/hf_datasets/hails/mmlu_no_train/computer_security/test/dataset_info.json,sha256=6YP9VRTJQf_cFtU69McMY4vedPweo4Dkiqb8297IWuU,1967 +olmo_data/hf_datasets/hails/mmlu_no_train/computer_security/test/state.json,sha256=sNJn-jTaq0GVT5OPskHbuDrE8mvtxmARWDF7DJVc_4I,249 +olmo_data/hf_datasets/hails/mmlu_no_train/computer_security/validation/data-00000-of-00001.arrow,sha256=8nVd-WorM4pOb21Q6KwuKFpyOOk2W5Xc5wC9Tyg-7P4,5840 +olmo_data/hf_datasets/hails/mmlu_no_train/computer_security/validation/dataset_info.json,sha256=6YP9VRTJQf_cFtU69McMY4vedPweo4Dkiqb8297IWuU,1967 +olmo_data/hf_datasets/hails/mmlu_no_train/computer_security/validation/state.json,sha256=dLwKWfUy3r-aTg-NlWlL-MHpAP8sK4Mo-gajfrxpbNg,255 +olmo_data/hf_datasets/hails/mmlu_no_train/conceptual_physics/dev/data-00000-of-00001.arrow,sha256=CIavXhq3GZ8rG7BikBzJP1lPQv2MyVUR0RFyN8C9-QI,2112 +olmo_data/hf_datasets/hails/mmlu_no_train/conceptual_physics/dev/dataset_info.json,sha256=HdYfO-BB1yFnqVtAsyrplER6i5lso9duTx7JNKVz4Hw,1968 +olmo_data/hf_datasets/hails/mmlu_no_train/conceptual_physics/dev/state.json,sha256=rNFopSvuFpIOJ8gPpzBsd0EREnkJjJH6W1IbqYT8NuQ,248 +olmo_data/hf_datasets/hails/mmlu_no_train/conceptual_physics/test/data-00000-of-00001.arrow,sha256=RfGq3M_H8tyUkYLY53_JKTBHfLYvgwHnVOX_Y1tfbHA,46936 +olmo_data/hf_datasets/hails/mmlu_no_train/conceptual_physics/test/dataset_info.json,sha256=HdYfO-BB1yFnqVtAsyrplER6i5lso9duTx7JNKVz4Hw,1968 +olmo_data/hf_datasets/hails/mmlu_no_train/conceptual_physics/test/state.json,sha256=T2y9z9UuaeboEnSwlFNvceYGVzKe0CPcoe_JgXF3kxs,249 +olmo_data/hf_datasets/hails/mmlu_no_train/conceptual_physics/validation/data-00000-of-00001.arrow,sha256=Hz5TaGTKmL3vA4eg1xLZp3zmPClXWwM_ygQa_Fs9jdA,6120 +olmo_data/hf_datasets/hails/mmlu_no_train/conceptual_physics/validation/dataset_info.json,sha256=HdYfO-BB1yFnqVtAsyrplER6i5lso9duTx7JNKVz4Hw,1968 +olmo_data/hf_datasets/hails/mmlu_no_train/conceptual_physics/validation/state.json,sha256=7KOOrXFGbTpuh1hZ_1ZWnK0MEjuIMCnP2Z1S_oWUIu8,255 +olmo_data/hf_datasets/hails/mmlu_no_train/econometrics/dev/data-00000-of-00001.arrow,sha256=bIHHwqP-IK3G5UvSf8AxWWVEnRKGfyzxj4r1iLGgtjE,2784 +olmo_data/hf_datasets/hails/mmlu_no_train/econometrics/dev/dataset_info.json,sha256=LugdvafRbncAf6faKOhn7ndCD6P8I569QslO6il0kcQ,1962 +olmo_data/hf_datasets/hails/mmlu_no_train/econometrics/dev/state.json,sha256=4hGmUk4Ar0oFDrHIuBZe9qHjI2a5uchOHfJ9cg-diCA,248 +olmo_data/hf_datasets/hails/mmlu_no_train/econometrics/test/data-00000-of-00001.arrow,sha256=XR4vE102VG3CKabEIy6Uwf2r1sTaHJam_R-zv-XnJIc,49440 +olmo_data/hf_datasets/hails/mmlu_no_train/econometrics/test/dataset_info.json,sha256=LugdvafRbncAf6faKOhn7ndCD6P8I569QslO6il0kcQ,1962 +olmo_data/hf_datasets/hails/mmlu_no_train/econometrics/test/state.json,sha256=Qf7v_nk8mbe4OKUyleRUe60bRO5XtVlr7CSuRTgXFUI,249 +olmo_data/hf_datasets/hails/mmlu_no_train/econometrics/validation/data-00000-of-00001.arrow,sha256=88jLGy8XZhvtHHKFKNkPrUxnK1s21H40Z2fAj-TvjWY,6224 +olmo_data/hf_datasets/hails/mmlu_no_train/econometrics/validation/dataset_info.json,sha256=LugdvafRbncAf6faKOhn7ndCD6P8I569QslO6il0kcQ,1962 +olmo_data/hf_datasets/hails/mmlu_no_train/econometrics/validation/state.json,sha256=toSsw4OSLpUdk6gjv2Mz2BjRGIGF1jaYwqlqn8jDUBc,255 +olmo_data/hf_datasets/hails/mmlu_no_train/electrical_engineering/dev/data-00000-of-00001.arrow,sha256=39lTFhfHIGxfiuplSSRAoTJdRwYZcR3aZJfBdPKExFM,2160 +olmo_data/hf_datasets/hails/mmlu_no_train/electrical_engineering/dev/dataset_info.json,sha256=E0mbLb9og-CICHkPUAkeRePmMBLoDhipyjCgpU3xias,1972 +olmo_data/hf_datasets/hails/mmlu_no_train/electrical_engineering/dev/state.json,sha256=w8MeFfWG7uJpDuQ4uYe0Fu-z3ZYKssn6v2XQRbqqfUw,248 +olmo_data/hf_datasets/hails/mmlu_no_train/electrical_engineering/test/data-00000-of-00001.arrow,sha256=2yOSB6l5b8e5hlbjQWTHf5NxO6S_qb4bJPIOFAjkXkY,29968 +olmo_data/hf_datasets/hails/mmlu_no_train/electrical_engineering/test/dataset_info.json,sha256=E0mbLb9og-CICHkPUAkeRePmMBLoDhipyjCgpU3xias,1972 +olmo_data/hf_datasets/hails/mmlu_no_train/electrical_engineering/test/state.json,sha256=dX5z4C24M9gVOAS0PuqZoR6HJ8RHC9X7MD6VHBKUaeY,249 +olmo_data/hf_datasets/hails/mmlu_no_train/electrical_engineering/validation/data-00000-of-00001.arrow,sha256=CcP7BG-varvVPGUQds1XKaGxHxVm5yWsviVS0H7C3ig,4384 +olmo_data/hf_datasets/hails/mmlu_no_train/electrical_engineering/validation/dataset_info.json,sha256=E0mbLb9og-CICHkPUAkeRePmMBLoDhipyjCgpU3xias,1972 +olmo_data/hf_datasets/hails/mmlu_no_train/electrical_engineering/validation/state.json,sha256=oALXBSX_icXkFi1_sJ2N3-Bt1CTkqz1SVMUFr7hD4n4,255 +olmo_data/hf_datasets/hails/mmlu_no_train/elementary_mathematics/dev/data-00000-of-00001.arrow,sha256=3UUruvFXp7BOq_w2XITDLIK3BI2IOkFCAoLxVPus1i8,2632 +olmo_data/hf_datasets/hails/mmlu_no_train/elementary_mathematics/dev/dataset_info.json,sha256=ksE_DQEhQrxWe0-MP6VoTX_7Q7WawTLY_S_mL9bgx4Y,1973 +olmo_data/hf_datasets/hails/mmlu_no_train/elementary_mathematics/dev/state.json,sha256=ZCZ68-0I5ifAHFXnBqOJTBjIdmR63XZckC8G_K5_4Bo,248 +olmo_data/hf_datasets/hails/mmlu_no_train/elementary_mathematics/test/data-00000-of-00001.arrow,sha256=4PlJpX0aWofOsJBeqBL3GuFQ0OAURyMOUiUklA52CMM,81008 +olmo_data/hf_datasets/hails/mmlu_no_train/elementary_mathematics/test/dataset_info.json,sha256=ksE_DQEhQrxWe0-MP6VoTX_7Q7WawTLY_S_mL9bgx4Y,1973 +olmo_data/hf_datasets/hails/mmlu_no_train/elementary_mathematics/test/state.json,sha256=k5i176YcFtXLlUZjG6H_qxFYGWp0p6WfCwWqLNGxcbY,249 +olmo_data/hf_datasets/hails/mmlu_no_train/elementary_mathematics/validation/data-00000-of-00001.arrow,sha256=BRLJXAaSIdZf_s_cJmxunQ2ENTj2WW_5vjG5QjHLj7U,11112 +olmo_data/hf_datasets/hails/mmlu_no_train/elementary_mathematics/validation/dataset_info.json,sha256=ksE_DQEhQrxWe0-MP6VoTX_7Q7WawTLY_S_mL9bgx4Y,1973 +olmo_data/hf_datasets/hails/mmlu_no_train/elementary_mathematics/validation/state.json,sha256=Ma7u4AJXPFt1VFNMwwUGwERGOTZxg3zNtk7FtgYnXsU,255 +olmo_data/hf_datasets/hails/mmlu_no_train/formal_logic/dev/data-00000-of-00001.arrow,sha256=LZC1wB0pkStEeKGXC79LdKskTgE086TwwOgIZi7n_bk,2896 +olmo_data/hf_datasets/hails/mmlu_no_train/formal_logic/dev/dataset_info.json,sha256=kJ-eCD4MYeJmBBeU6CUogQkKGZB05UyYHw2dkksQLcg,1962 +olmo_data/hf_datasets/hails/mmlu_no_train/formal_logic/dev/state.json,sha256=u5W4G_6uUvSGhwfdvHBoyEbKxk2GS56Sign8Sd7d0Tk,248 +olmo_data/hf_datasets/hails/mmlu_no_train/formal_logic/test/data-00000-of-00001.arrow,sha256=LmBuI_cAwBXSb1n68PJLL5OZlTyz041zLWqeOy_st3k,52864 +olmo_data/hf_datasets/hails/mmlu_no_train/formal_logic/test/dataset_info.json,sha256=kJ-eCD4MYeJmBBeU6CUogQkKGZB05UyYHw2dkksQLcg,1962 +olmo_data/hf_datasets/hails/mmlu_no_train/formal_logic/test/state.json,sha256=dqpvaouVbe0yFilPiyZ-00Vo-uiKLDcJt7K7pFKJ6-c,249 +olmo_data/hf_datasets/hails/mmlu_no_train/formal_logic/validation/data-00000-of-00001.arrow,sha256=exyJddlywJwVxyLv_LbXn_urMDHn4liQjGftZF6NNqQ,7536 +olmo_data/hf_datasets/hails/mmlu_no_train/formal_logic/validation/dataset_info.json,sha256=kJ-eCD4MYeJmBBeU6CUogQkKGZB05UyYHw2dkksQLcg,1962 +olmo_data/hf_datasets/hails/mmlu_no_train/formal_logic/validation/state.json,sha256=BNmYUHOHqEBsRDDntmN1eGLWOGDYYc1-mO6olJWoHCE,255 +olmo_data/hf_datasets/hails/mmlu_no_train/global_facts/dev/data-00000-of-00001.arrow,sha256=7c-ImrZzL8cRxF2Sni3teYZPpkukB9TwlrqF7lPTcZM,2368 +olmo_data/hf_datasets/hails/mmlu_no_train/global_facts/dev/dataset_info.json,sha256=A3MwQWdgMYeOPh1OwoHVuztiKzjmby42GhvQSqP5P58,1962 +olmo_data/hf_datasets/hails/mmlu_no_train/global_facts/dev/state.json,sha256=79zspy64JokpkV4aff1GjeOhvPaUWvpdCkzRVNSPfow,248 +olmo_data/hf_datasets/hails/mmlu_no_train/global_facts/test/data-00000-of-00001.arrow,sha256=jjNAuOiY3e70q6wc1C6R1kE4EDppFHbhTZC8eVY3GjY,21072 +olmo_data/hf_datasets/hails/mmlu_no_train/global_facts/test/dataset_info.json,sha256=A3MwQWdgMYeOPh1OwoHVuztiKzjmby42GhvQSqP5P58,1962 +olmo_data/hf_datasets/hails/mmlu_no_train/global_facts/test/state.json,sha256=OjfYTt1hxBZyv4pj2g1p1cMMzxYoqaLtqCvC7jjQtBI,249 +olmo_data/hf_datasets/hails/mmlu_no_train/global_facts/validation/data-00000-of-00001.arrow,sha256=V7g-aoVqii-2pr_nHDxaxbXuLx5uej_Ce8yIQToHNyg,3096 +olmo_data/hf_datasets/hails/mmlu_no_train/global_facts/validation/dataset_info.json,sha256=A3MwQWdgMYeOPh1OwoHVuztiKzjmby42GhvQSqP5P58,1962 +olmo_data/hf_datasets/hails/mmlu_no_train/global_facts/validation/state.json,sha256=kKcldp4y04pmKZX5b30YlM9m3Cyk47pvbII7p9NrysQ,255 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_biology/dev/data-00000-of-00001.arrow,sha256=-5XIeBjJoVI4aH-baRcGYXrd1nJbDl_xrozL2TnsfPA,2840 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_biology/dev/dataset_info.json,sha256=KudWmc9Yzcb33ktqXruoTB48TRqEP8xBvfVqmFwxLfM,1972 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_biology/dev/state.json,sha256=T5UnySrlidfOXWubakQvRQHiXWL_zedVcU1IRYr8D7M,248 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_biology/test/data-00000-of-00001.arrow,sha256=EZabcE-nf3SWMl7puCtGGwcUEYSt9fz0PtFXPQKFKDw,117936 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_biology/test/dataset_info.json,sha256=KudWmc9Yzcb33ktqXruoTB48TRqEP8xBvfVqmFwxLfM,1972 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_biology/test/state.json,sha256=PSYZv22JgnKChTrkkE0KUNUCCtcrAaBlaBNSZlVmpgk,249 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_biology/validation/data-00000-of-00001.arrow,sha256=8axozy8gHANOz-8eEbt4WAuzRdyMJSt7iHjbAe4zDtU,12824 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_biology/validation/dataset_info.json,sha256=KudWmc9Yzcb33ktqXruoTB48TRqEP8xBvfVqmFwxLfM,1972 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_biology/validation/state.json,sha256=JWOj50jBo8lAmZGTsjsjazUt7fEQoXnw62TwbXtR46c,255 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_chemistry/dev/data-00000-of-00001.arrow,sha256=bPxMsxwknGNf_xF9nZ2hDVsE3OtSowh1Lg9gA_4Db58,2408 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_chemistry/dev/dataset_info.json,sha256=17VdBIOBlLHzv5eN3bar1KHAqxesCrbKVOAMD2SJPws,1971 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_chemistry/dev/state.json,sha256=tU3EZxXwmascQo_HLe-IripGphVDU-LiURNEMnlCYaE,248 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_chemistry/test/data-00000-of-00001.arrow,sha256=f1rW3zpV7JTH-42-_dlKTvABxboXBUfNzAX_AXM4oRQ,64592 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_chemistry/test/dataset_info.json,sha256=17VdBIOBlLHzv5eN3bar1KHAqxesCrbKVOAMD2SJPws,1971 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_chemistry/test/state.json,sha256=Pnxa0QdPS00K-8UYYsrw6c852No5t8YE1RxbL-SZKWg,249 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_chemistry/validation/data-00000-of-00001.arrow,sha256=sw3uZgDF2IUovE0CIxxz8nGOyeibTrXkckxJG5_lnx8,8712 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_chemistry/validation/dataset_info.json,sha256=17VdBIOBlLHzv5eN3bar1KHAqxesCrbKVOAMD2SJPws,1971 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_chemistry/validation/state.json,sha256=ndl268gkBrdxjhO03UD7heof8hmCMU92WtQh05FctoQ,255 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_computer_science/dev/data-00000-of-00001.arrow,sha256=7sj5zBQp8p8FsBYPs-vvOF2k_DjK72Sc0QdE8cy3ZtU,4136 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_computer_science/dev/dataset_info.json,sha256=CrfYSOikOlaSNPMqKGRor5s-SjAfFzxcEJn3Yl2jYU4,1977 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_computer_science/dev/state.json,sha256=gG7pDCf6om3qPBigZT04ntWexesr5zZ1jn0okY1VD3g,248 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_computer_science/test/data-00000-of-00001.arrow,sha256=6Su-NCJj7lRymJPJHEmjD6rHFZWAhIhcnBVTRiZs6i0,48744 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_computer_science/test/dataset_info.json,sha256=CrfYSOikOlaSNPMqKGRor5s-SjAfFzxcEJn3Yl2jYU4,1977 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_computer_science/test/state.json,sha256=v-onTUXkULGzI-EAEFpStaTk_0gZzTy3okxBMZqm2YU,249 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_computer_science/validation/data-00000-of-00001.arrow,sha256=Yhd5S_NsLXJKoaclkigOmO01URWjdFF4HYLIGgfbcNs,4688 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_computer_science/validation/dataset_info.json,sha256=CrfYSOikOlaSNPMqKGRor5s-SjAfFzxcEJn3Yl2jYU4,1977 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_computer_science/validation/state.json,sha256=uH8jL99wO3fBHOMt-eDshoVythWUgAoDuHB6SzLNyiI,255 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_european_history/dev/data-00000-of-00001.arrow,sha256=BO0oVRApOLBZ8CptT1s9Ba9EsfHHTHR_3Lk4M2-MDD0,12784 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_european_history/dev/dataset_info.json,sha256=htmRPDAuSGGjf6EcWyTLcMmVXTPNNWjwfLkBvXD9OcQ,1982 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_european_history/dev/state.json,sha256=BwZYfWa6Vtb6FAbJca8a2vZfIjv2ptjB5gkQ5eyWyCU,248 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_european_history/test/data-00000-of-00001.arrow,sha256=IxQ61Cy93ImwlRPbuIHiO405dPcW_E5rkiQ2niY5N1g,276640 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_european_history/test/dataset_info.json,sha256=htmRPDAuSGGjf6EcWyTLcMmVXTPNNWjwfLkBvXD9OcQ,1982 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_european_history/test/state.json,sha256=FtW-mmiWljSehXHIHewDxEWdCXgO3oaxvc77JBx8Imo,249 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_european_history/validation/data-00000-of-00001.arrow,sha256=CE1aL6WPoEDyG9Qm0teQjU1vohq_Mwf2zgbViS_C9Pg,31280 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_european_history/validation/dataset_info.json,sha256=htmRPDAuSGGjf6EcWyTLcMmVXTPNNWjwfLkBvXD9OcQ,1982 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_european_history/validation/state.json,sha256=0nbOYxB7U-t-O0RGyXXc8wVBVY4lMuZdzvFd_n7q4y0,255 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_geography/dev/data-00000-of-00001.arrow,sha256=JykwPyEAlYirL3T4MPsFqooY7DNT9iSqlIyamfXRPPQ,2584 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_geography/dev/dataset_info.json,sha256=qlBhS8-rE_fEfoCeojFo_Ck4wF9H3DNtIa2P-bFaj3Y,1971 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_geography/dev/state.json,sha256=WgnunW6dy1Er0t6N5aH52eHMGACWNOPbxp7zLPZ61uw,248 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_geography/test/data-00000-of-00001.arrow,sha256=DloBS405xTMVEyBx9jouVTksi9xGl13u0JUFJyW2G2Q,48048 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_geography/test/dataset_info.json,sha256=qlBhS8-rE_fEfoCeojFo_Ck4wF9H3DNtIa2P-bFaj3Y,1971 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_geography/test/state.json,sha256=uHsmFD5we7u02Jt3POCXZSxsU7gf3bHCyOC8yNk1zp4,249 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_geography/validation/data-00000-of-00001.arrow,sha256=g73WW-ZNqzyrCWy_eOkDRIr1G3aYoYp04O5vPWx66vA,5952 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_geography/validation/dataset_info.json,sha256=qlBhS8-rE_fEfoCeojFo_Ck4wF9H3DNtIa2P-bFaj3Y,1971 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_geography/validation/state.json,sha256=zcV6ipESE_Sh8yC32foTv5cHAmczIk_Lqplf5DlIt4E,255 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_government_and_politics/dev/data-00000-of-00001.arrow,sha256=CmHy598mS1mTbc2YLr3Gew6pIzsYrp-n-inz-82ZSRI,3032 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_government_and_politics/dev/dataset_info.json,sha256=ZZNmMsK0lVlT9EJLcGSV5Ke8QzZhYwY9vNzk2laLU5s,1985 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_government_and_politics/dev/state.json,sha256=Q1PZk0y3TjEyI5Nby5xhuciBEaiwneK3jsaescMbG3M,248 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_government_and_politics/test/data-00000-of-00001.arrow,sha256=5uAbTrgvnqoNfA91AYtS0YLkAJ1lQtbAhGgijWtysAE,74656 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_government_and_politics/test/dataset_info.json,sha256=ZZNmMsK0lVlT9EJLcGSV5Ke8QzZhYwY9vNzk2laLU5s,1985 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_government_and_politics/test/state.json,sha256=C-3Vq6SuiWa_ypz0o4rt_mxRlHhB6k8_gn7FKJv3brM,249 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_government_and_politics/validation/data-00000-of-00001.arrow,sha256=bIl9GsVtjqIHxt930hzj2ZMQGw_UmkMIaYk4V4avB54,8936 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_government_and_politics/validation/dataset_info.json,sha256=ZZNmMsK0lVlT9EJLcGSV5Ke8QzZhYwY9vNzk2laLU5s,1985 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_government_and_politics/validation/state.json,sha256=stsPr8tiRV0VdCwdlxMFzoFVkJrsNSD1JWMXzB835Nk,255 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_macroeconomics/dev/data-00000-of-00001.arrow,sha256=iLBD--0oxlM7U72KTw9ia4uHP8KaQfbI91Pdon74CdA,2544 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_macroeconomics/dev/dataset_info.json,sha256=p_hl6Gx1_OHFzz358oiHVlLzLuqSd4gYx7-432i3-WQ,1979 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_macroeconomics/dev/state.json,sha256=rt3A0m8QMBZgZhAFpO4DGlCS5EFmtRIohu7XfJjP0Co,248 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_macroeconomics/test/data-00000-of-00001.arrow,sha256=FoMeLgITWoa26wMDpYCvjtF4RNuaTwFY5tmh5v9Jrvc,130456 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_macroeconomics/test/dataset_info.json,sha256=p_hl6Gx1_OHFzz358oiHVlLzLuqSd4gYx7-432i3-WQ,1979 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_macroeconomics/test/state.json,sha256=HS0sEydAoctUtdrdWLwe9Yw6L4z7YRPFPFAygtAI8Cg,249 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_macroeconomics/validation/data-00000-of-00001.arrow,sha256=6OX0lbh1VqdWqod-3nJQUzdDT0C-kdWGQqYuc_Uhyt8,15368 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_macroeconomics/validation/dataset_info.json,sha256=p_hl6Gx1_OHFzz358oiHVlLzLuqSd4gYx7-432i3-WQ,1979 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_macroeconomics/validation/state.json,sha256=F8G2ZnztaLV2unWa7Q4ZkajrS2vFggygC9BpmjdJAP8,255 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_mathematics/dev/data-00000-of-00001.arrow,sha256=F6Iz6aTea7_shwwB972raY_DKI2ykZQOWnde3-oKqaE,2496 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_mathematics/dev/dataset_info.json,sha256=wpyaVYAHO_t4EC4pOD7_I9nxVMujsturlUTDZvStoks,1973 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_mathematics/dev/state.json,sha256=2_v4avQw6r1bY8ol5BRePPRrGiM0DfhXGGH7C8OX8Q0,248 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_mathematics/test/data-00000-of-00001.arrow,sha256=HM4LAVFsMn18QuIyulNEk7S1cw5JaRKw-evVQXE1Pe4,63216 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_mathematics/test/dataset_info.json,sha256=wpyaVYAHO_t4EC4pOD7_I9nxVMujsturlUTDZvStoks,1973 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_mathematics/test/state.json,sha256=YNkmEU9SNKowggfGIDJIYo_ObyzbJRfeOsJa4j87_7I,249 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_mathematics/validation/data-00000-of-00001.arrow,sha256=gh_-IWIdEzDPCFxRyZlx4XAn7txVAfgYPJRaZlCaR7g,7608 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_mathematics/validation/dataset_info.json,sha256=wpyaVYAHO_t4EC4pOD7_I9nxVMujsturlUTDZvStoks,1973 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_mathematics/validation/state.json,sha256=AqtEkNsY3BI7Li5-uNMyD_uS7tLNMfpKp--vZU8EnOQ,255 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_microeconomics/dev/data-00000-of-00001.arrow,sha256=HWcWNcQldP7XtyFvYvWb40g_TNCfEGRYtouYknVV2c4,2504 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_microeconomics/dev/dataset_info.json,sha256=24SxbJ8NiJE_R7zpYDhrb8khjxiUVCEn-UKaLRAb1B0,1976 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_microeconomics/dev/state.json,sha256=4VRC5AxFCPsjSdYbe2W2-d6cg1lDxTulUr2VNXcoG1Q,248 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_microeconomics/test/data-00000-of-00001.arrow,sha256=q4n0CGLyONBskp8ESQ2bdhzuA2-w1R6ncVo0dmZxDpA,83912 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_microeconomics/test/dataset_info.json,sha256=24SxbJ8NiJE_R7zpYDhrb8khjxiUVCEn-UKaLRAb1B0,1976 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_microeconomics/test/state.json,sha256=T3ltWYZs1RQdkrkhgvQjjz7bFnuyn2cilrLGwkKlJXU,249 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_microeconomics/validation/data-00000-of-00001.arrow,sha256=YSP3CUYBdg-z3jBAbOeP36keqFtERn_I-kRSJeGq--c,9408 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_microeconomics/validation/dataset_info.json,sha256=24SxbJ8NiJE_R7zpYDhrb8khjxiUVCEn-UKaLRAb1B0,1976 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_microeconomics/validation/state.json,sha256=s5_caIReiDKTagQCDBCsBE_0d8fRUoZDZi_03akW5Fc,255 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_physics/dev/data-00000-of-00001.arrow,sha256=cZUNn0iJvBJafVDS5N2gP9RVxyDdacYf2xNDHzKXgrY,2656 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_physics/dev/dataset_info.json,sha256=GHR7Iyh5K004bo8hwCNIuSU76Nrfz3eVlrThWmR38T4,1969 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_physics/dev/state.json,sha256=7ACkmvrf9cDg5ipyYM1JQ4no-0fwQICa9WypLMclDqI,248 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_physics/test/data-00000-of-00001.arrow,sha256=rQmBamh1N1yQYKp3vlloJTxCpGiUriP-QqmAH51DtSk,64064 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_physics/test/dataset_info.json,sha256=GHR7Iyh5K004bo8hwCNIuSU76Nrfz3eVlrThWmR38T4,1969 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_physics/test/state.json,sha256=SNFayfc_nCpr56gh4AyOSgZ7CCaOAEqdgSnGdYTY3M8,249 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_physics/validation/data-00000-of-00001.arrow,sha256=yrva4jlV3N-7By6ogLeJFbkYG9KItYcWA6MSSi3qUkc,8224 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_physics/validation/dataset_info.json,sha256=GHR7Iyh5K004bo8hwCNIuSU76Nrfz3eVlrThWmR38T4,1969 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_physics/validation/state.json,sha256=3g9ZTOsW3RiAfjZRyHKnUe5ptNmjqAzv1lgMSH8o3vo,255 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_psychology/dev/data-00000-of-00001.arrow,sha256=Gkuv4qvZKLOlqePje8krWZ1m9VtzaxIDM2ogrWfJc8w,3096 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_psychology/dev/dataset_info.json,sha256=iVOPiGIIEBqkqB8ozIEzr7_c4ZgAMIPBfg3bTQJjNUY,1975 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_psychology/dev/state.json,sha256=7LuJ9CyllCmV6QKtvfORvWEZCL9iVid9rt1f81-sHls,248 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_psychology/test/data-00000-of-00001.arrow,sha256=vAUICJRb_BxwBe7q_Ruvzi8EjcZ3ZIgHfO9wgTR8Ixo,174640 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_psychology/test/dataset_info.json,sha256=iVOPiGIIEBqkqB8ozIEzr7_c4ZgAMIPBfg3bTQJjNUY,1975 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_psychology/test/state.json,sha256=lNAoCjpAEw6DYXlVBzVR1R2kebuwU8KsKuyYb4YHtcI,249 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_psychology/validation/data-00000-of-00001.arrow,sha256=m_3LFsmnx5wJiaGnhVgu0N3s1umDI7h8XxBSYCL5uaA,19896 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_psychology/validation/dataset_info.json,sha256=iVOPiGIIEBqkqB8ozIEzr7_c4ZgAMIPBfg3bTQJjNUY,1975 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_psychology/validation/state.json,sha256=mV4LHOVWu7XrtjoAo1SBpnpapCw_ajjfA6vbe4zv99o,255 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_statistics/dev/data-00000-of-00001.arrow,sha256=OWtUJnk41wjh-BxaKuBw4yhZ6FBe6p1fo5t54023JqQ,3712 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_statistics/dev/dataset_info.json,sha256=gKM1Fltijt2xZPsNUjJ7pwbnPYJXMhXfhHNBHEy2qMs,1975 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_statistics/dev/state.json,sha256=AqNa0KbpY4bA1Osa1AbmrxNQsuxflTn162NkAIR7tLo,248 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_statistics/test/data-00000-of-00001.arrow,sha256=OojWsgjIPKM3snO0PNEPA9BqNNjq9wYYC9T2fTYuwi4,117384 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_statistics/test/dataset_info.json,sha256=gKM1Fltijt2xZPsNUjJ7pwbnPYJXMhXfhHNBHEy2qMs,1975 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_statistics/test/state.json,sha256=C9PWCT2-j8Nyf3Tp_2Gor-a7QQ80_-ncoDpNm3vP4rA,249 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_statistics/validation/data-00000-of-00001.arrow,sha256=_V_K022AlSEKAbmABeN4lYRG3pKc4MH1eMJ4ur6N1jk,11656 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_statistics/validation/dataset_info.json,sha256=gKM1Fltijt2xZPsNUjJ7pwbnPYJXMhXfhHNBHEy2qMs,1975 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_statistics/validation/state.json,sha256=8S-iOAPK5LP-piRyWseEYzktV3WQvVNJ_5xP5ZWgaiU,255 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_us_history/dev/data-00000-of-00001.arrow,sha256=BnxXvw5zV2bsWOibsigZiVHDpbc-Gw3GhN5Mdp14eAE,10048 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_us_history/dev/dataset_info.json,sha256=PXyxQ-ef2eLGrbakD6s-CfgVCi7Xy6sFerpMBhQlE7c,1975 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_us_history/dev/state.json,sha256=7lZ1bqKOfC3IkZzlNNhgOgU8tHlBvc0Ky-FcjrgHrxI,248 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_us_history/test/data-00000-of-00001.arrow,sha256=60Ys-T7yM6fkZcU3vR-ZoEBa2UPwhRRhQJ_LvnRfyvI,303104 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_us_history/test/dataset_info.json,sha256=PXyxQ-ef2eLGrbakD6s-CfgVCi7Xy6sFerpMBhQlE7c,1975 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_us_history/test/state.json,sha256=MIFvtLI6SNoXsof-OO2Zg7fIMj902idlSROWPPlSmGA,249 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_us_history/validation/data-00000-of-00001.arrow,sha256=94aQAsOiNcZOwhKv3WlFEb9LdWNK5d1tdyxdYMC9MVA,33352 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_us_history/validation/dataset_info.json,sha256=PXyxQ-ef2eLGrbakD6s-CfgVCi7Xy6sFerpMBhQlE7c,1975 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_us_history/validation/state.json,sha256=Y0Yw1wiTnecZ9UMK5HtJ99ASbOT4Bnvo-lhqe8esvzI,255 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_world_history/dev/data-00000-of-00001.arrow,sha256=byGUqwChWk59W5Vid1IdcAhLlqwgpXIBZoZfTqmjpCk,6080 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_world_history/dev/dataset_info.json,sha256=EF7z5KGnW2QMNgKLBnm-NadDR6w0RiwZmB2EJISxmAk,1978 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_world_history/dev/state.json,sha256=-vSxbJoCVSCakg55vlA9-IahDQUs3vv7mp0_ldfH1WI,248 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_world_history/test/data-00000-of-00001.arrow,sha256=3hOBMuNO3IMVWdkni9k6mcIuzjU_h_YwOJScMnxkFak,386544 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_world_history/test/dataset_info.json,sha256=EF7z5KGnW2QMNgKLBnm-NadDR6w0RiwZmB2EJISxmAk,1978 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_world_history/test/state.json,sha256=3G5VMxwbPG9SwVqs9m3_K3tmrjKqWovrv0VjHIfMJSs,249 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_world_history/validation/data-00000-of-00001.arrow,sha256=XzmBiEXg7BujljUWhmFJO0FiJkawxgWpin50lvlP7H8,47328 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_world_history/validation/dataset_info.json,sha256=EF7z5KGnW2QMNgKLBnm-NadDR6w0RiwZmB2EJISxmAk,1978 +olmo_data/hf_datasets/hails/mmlu_no_train/high_school_world_history/validation/state.json,sha256=C6SOK0mAwbp3tvOAl0kzU3CVNRTlhJMPvtKtJj5TodM,255 +olmo_data/hf_datasets/hails/mmlu_no_train/human_aging/dev/data-00000-of-00001.arrow,sha256=F0P2yritGrB13Vsn5IJEazgwECtQQgjdoyjrmCYZ_kI,2136 +olmo_data/hf_datasets/hails/mmlu_no_train/human_aging/dev/dataset_info.json,sha256=GmoWUnw515FI7XTCrg_3eNolXhqPe8-pMXPfPtBcieU,1961 +olmo_data/hf_datasets/hails/mmlu_no_train/human_aging/dev/state.json,sha256=Fy5DVLpGW7Ny3VVwtIlORcJEzc9ttpaTdrcCe9CjY90,248 +olmo_data/hf_datasets/hails/mmlu_no_train/human_aging/test/data-00000-of-00001.arrow,sha256=iBZHAv9ipgJrjPHihgB-lH4Q0oZRgYMKLbZE_1sXOCs,50504 +olmo_data/hf_datasets/hails/mmlu_no_train/human_aging/test/dataset_info.json,sha256=GmoWUnw515FI7XTCrg_3eNolXhqPe8-pMXPfPtBcieU,1961 +olmo_data/hf_datasets/hails/mmlu_no_train/human_aging/test/state.json,sha256=NaCxVtEr6fxVoNLzraGvcWm6qroL9tTS0LzgCX92cYk,249 +olmo_data/hf_datasets/hails/mmlu_no_train/human_aging/validation/data-00000-of-00001.arrow,sha256=L6BgVM3m8VkYi4_Pc-61AORpcll5bGM0XWS_yI1lkPk,6112 +olmo_data/hf_datasets/hails/mmlu_no_train/human_aging/validation/dataset_info.json,sha256=GmoWUnw515FI7XTCrg_3eNolXhqPe8-pMXPfPtBcieU,1961 +olmo_data/hf_datasets/hails/mmlu_no_train/human_aging/validation/state.json,sha256=i5U_nmrHABG-idu3M7NDLvIfTp_7ZFoTSVEC2WRdJkY,255 +olmo_data/hf_datasets/hails/mmlu_no_train/human_sexuality/dev/data-00000-of-00001.arrow,sha256=CiGwtqBZbSW-nSocrBohkmLTFQv2vHbpJPDyCv7QXu4,2232 +olmo_data/hf_datasets/hails/mmlu_no_train/human_sexuality/dev/dataset_info.json,sha256=w7oxHOyFAtkZrs4Iljzq-Ff2qUc8V56YENOXfrv5rH8,1965 +olmo_data/hf_datasets/hails/mmlu_no_train/human_sexuality/dev/state.json,sha256=QI0KjM7g9OcJkd0h3hPYRQz0iue2DVPMehlEW3Mjx-c,248 +olmo_data/hf_datasets/hails/mmlu_no_train/human_sexuality/test/data-00000-of-00001.arrow,sha256=Unc8vPNXmEq3SKk47cCa2hCZNOOWR7PGwhWOyTosO6s,35656 +olmo_data/hf_datasets/hails/mmlu_no_train/human_sexuality/test/dataset_info.json,sha256=w7oxHOyFAtkZrs4Iljzq-Ff2qUc8V56YENOXfrv5rH8,1965 +olmo_data/hf_datasets/hails/mmlu_no_train/human_sexuality/test/state.json,sha256=KKHDOWyFZG948xSVu7bZNwByCr71F8M__BDIn20SbQ8,249 +olmo_data/hf_datasets/hails/mmlu_no_train/human_sexuality/validation/data-00000-of-00001.arrow,sha256=hiIBF92FRj9qcDI3B7fl7o16gT7RhLb-ZTZGBlOz5zU,3720 +olmo_data/hf_datasets/hails/mmlu_no_train/human_sexuality/validation/dataset_info.json,sha256=w7oxHOyFAtkZrs4Iljzq-Ff2qUc8V56YENOXfrv5rH8,1965 +olmo_data/hf_datasets/hails/mmlu_no_train/human_sexuality/validation/state.json,sha256=5SVD_houTJBCwFi1EajtBELSNeRejLegBEC0GZavUQw,255 +olmo_data/hf_datasets/hails/mmlu_no_train/international_law/dev/data-00000-of-00001.arrow,sha256=7OQpz8z0dpz1w-wWJMF2AdAIZRU_P-CPmDmKafWuc8Y,3584 +olmo_data/hf_datasets/hails/mmlu_no_train/international_law/dev/dataset_info.json,sha256=eLZkOg7EQ24Thg7VwP-21MAc9IKOcSyaoS3s7RKYT6A,1967 +olmo_data/hf_datasets/hails/mmlu_no_train/international_law/dev/state.json,sha256=yXt4MelA0PxIp_Cu3RsFObeCuKf3saituhyH0VuHD2Y,248 +olmo_data/hf_datasets/hails/mmlu_no_train/international_law/test/data-00000-of-00001.arrow,sha256=EUFtXmG84mKUIxxqlAvCS6w_KopYXhOfJ3HfgWyUw24,57136 +olmo_data/hf_datasets/hails/mmlu_no_train/international_law/test/dataset_info.json,sha256=eLZkOg7EQ24Thg7VwP-21MAc9IKOcSyaoS3s7RKYT6A,1967 +olmo_data/hf_datasets/hails/mmlu_no_train/international_law/test/state.json,sha256=0foXHuk87DxTCeYOJZp7-9XKU_Xq0A1kVWEaBbQX7iU,249 +olmo_data/hf_datasets/hails/mmlu_no_train/international_law/validation/data-00000-of-00001.arrow,sha256=ZPK2FQhbUzLw3BDzSm2LzarqZ_Pw2UPpHkXlL9gp64s,7808 +olmo_data/hf_datasets/hails/mmlu_no_train/international_law/validation/dataset_info.json,sha256=eLZkOg7EQ24Thg7VwP-21MAc9IKOcSyaoS3s7RKYT6A,1967 +olmo_data/hf_datasets/hails/mmlu_no_train/international_law/validation/state.json,sha256=1bxsaFq9GwkTnsa5hM8-sJ3YAYosRrPm-pWfeaaQteI,255 +olmo_data/hf_datasets/hails/mmlu_no_train/jurisprudence/dev/data-00000-of-00001.arrow,sha256=l5T5QS1JddCmn5VAmgQCPgRaKer4SAfGi1bpzB0GFQU,2456 +olmo_data/hf_datasets/hails/mmlu_no_train/jurisprudence/dev/dataset_info.json,sha256=_z29qCCmCEuVVJdgTj5nAiLdBaDU_PkIBDqeg7wYMKA,1963 +olmo_data/hf_datasets/hails/mmlu_no_train/jurisprudence/dev/state.json,sha256=wk4OzjQ2FqZeBmWaCZVGhuffk5gNstjeSbhK3Unz41g,248 +olmo_data/hf_datasets/hails/mmlu_no_train/jurisprudence/test/data-00000-of-00001.arrow,sha256=bxex8k7YGA6qSZTsoNndSdT7mtURyZH3zZjX5hO8K1c,36896 +olmo_data/hf_datasets/hails/mmlu_no_train/jurisprudence/test/dataset_info.json,sha256=_z29qCCmCEuVVJdgTj5nAiLdBaDU_PkIBDqeg7wYMKA,1963 +olmo_data/hf_datasets/hails/mmlu_no_train/jurisprudence/test/state.json,sha256=15izJ7VagR19pkSsmL35oGPbOyEZggNY9syHuUzXJWM,249 +olmo_data/hf_datasets/hails/mmlu_no_train/jurisprudence/validation/data-00000-of-00001.arrow,sha256=a2hwm3galwtBkyp-TcNcwbwEw5E1I4ipst8KT93oVIo,4976 +olmo_data/hf_datasets/hails/mmlu_no_train/jurisprudence/validation/dataset_info.json,sha256=_z29qCCmCEuVVJdgTj5nAiLdBaDU_PkIBDqeg7wYMKA,1963 +olmo_data/hf_datasets/hails/mmlu_no_train/jurisprudence/validation/state.json,sha256=yoHakoPvCnY6Gs4nYgAPn15Mn6wSHpeHHxOTnBLZ88A,255 +olmo_data/hf_datasets/hails/mmlu_no_train/logical_fallacies/dev/data-00000-of-00001.arrow,sha256=SRp4mC1CpJFx0Pm6j1azvZ-WTecpA4Gkb1Uy7VA_e2c,2736 +olmo_data/hf_datasets/hails/mmlu_no_train/logical_fallacies/dev/dataset_info.json,sha256=3qh_M0lhTv_tsXkzdBPM9Q_VVkeVOzTgFUXgqy8uBuY,1967 +olmo_data/hf_datasets/hails/mmlu_no_train/logical_fallacies/dev/state.json,sha256=nC-4tiFzKHgZHDxLIq7XWNfVgBir1_7kJ6nRVEEdpmc,248 +olmo_data/hf_datasets/hails/mmlu_no_train/logical_fallacies/test/data-00000-of-00001.arrow,sha256=EbYVgkbnhk2HIzJY_nGctutO7Wd8_FTsHxCAz_fC8yw,54600 +olmo_data/hf_datasets/hails/mmlu_no_train/logical_fallacies/test/dataset_info.json,sha256=3qh_M0lhTv_tsXkzdBPM9Q_VVkeVOzTgFUXgqy8uBuY,1967 +olmo_data/hf_datasets/hails/mmlu_no_train/logical_fallacies/test/state.json,sha256=Co1VoHPRxDbcGkguyV_CbbKZNP6GE1khEi3sqXLpD9Y,249 +olmo_data/hf_datasets/hails/mmlu_no_train/logical_fallacies/validation/data-00000-of-00001.arrow,sha256=571b67DduMhF4ZolXfJy-39m9GbSQJxs-Js073vxRzs,6552 +olmo_data/hf_datasets/hails/mmlu_no_train/logical_fallacies/validation/dataset_info.json,sha256=3qh_M0lhTv_tsXkzdBPM9Q_VVkeVOzTgFUXgqy8uBuY,1967 +olmo_data/hf_datasets/hails/mmlu_no_train/logical_fallacies/validation/state.json,sha256=MM_UlJkekkPLvXt6w_Q0pno-6uximeSWJplceZlyCGs,255 +olmo_data/hf_datasets/hails/mmlu_no_train/machine_learning/dev/data-00000-of-00001.arrow,sha256=4ifg6r9tVRToS8jIYYY0zP82xtZ3yk5AA5MF4hEp2jE,3472 +olmo_data/hf_datasets/hails/mmlu_no_train/machine_learning/dev/dataset_info.json,sha256=a1hq9PlgdWqzzzKUr44Wk6fzoNk2lHvOA8sW2L5E9oI,1966 +olmo_data/hf_datasets/hails/mmlu_no_train/machine_learning/dev/state.json,sha256=WJzE-3OzmnjfaNqKdV4nh7ayKMMOum5ni1-KcxoQnTQ,248 +olmo_data/hf_datasets/hails/mmlu_no_train/machine_learning/test/data-00000-of-00001.arrow,sha256=8L-pUAW6RFbORAN3Z-hU-UJF1021i76mEC9KXW5MZAY,37192 +olmo_data/hf_datasets/hails/mmlu_no_train/machine_learning/test/dataset_info.json,sha256=a1hq9PlgdWqzzzKUr44Wk6fzoNk2lHvOA8sW2L5E9oI,1966 +olmo_data/hf_datasets/hails/mmlu_no_train/machine_learning/test/state.json,sha256=w-lK1OX89WabMzF6XIM0lLsJwwO8PcCw-St1YWTDgO0,249 +olmo_data/hf_datasets/hails/mmlu_no_train/machine_learning/validation/data-00000-of-00001.arrow,sha256=-XoH10VLmSQG13nIcSyMmi2-OSx0a1BBd4dfthJFs84,4512 +olmo_data/hf_datasets/hails/mmlu_no_train/machine_learning/validation/dataset_info.json,sha256=a1hq9PlgdWqzzzKUr44Wk6fzoNk2lHvOA8sW2L5E9oI,1966 +olmo_data/hf_datasets/hails/mmlu_no_train/machine_learning/validation/state.json,sha256=9CKdesMFTrv3frwjrFep9LRN8a05ll89KfeVM9fcwjE,255 +olmo_data/hf_datasets/hails/mmlu_no_train/management/dev/data-00000-of-00001.arrow,sha256=WPdJxZL_Glldb9w2rZKmvA-5qeZkE8F6NCQF7Dx-x7s,2024 +olmo_data/hf_datasets/hails/mmlu_no_train/management/dev/dataset_info.json,sha256=T1Y0nXPbO7sD5WYJVyV0uPdZzW0Z2rVXHXQeKZjF1IU,1959 +olmo_data/hf_datasets/hails/mmlu_no_train/management/dev/state.json,sha256=bnOcN2T9U7c87xX8e067__gGcH9ES-WpkDdDwRNqT9w,248 +olmo_data/hf_datasets/hails/mmlu_no_train/management/test/data-00000-of-00001.arrow,sha256=_2D3_bCnDhIpv3Pfh512MxYy48xh47izqZOIWd6y0jg,22496 +olmo_data/hf_datasets/hails/mmlu_no_train/management/test/dataset_info.json,sha256=T1Y0nXPbO7sD5WYJVyV0uPdZzW0Z2rVXHXQeKZjF1IU,1959 +olmo_data/hf_datasets/hails/mmlu_no_train/management/test/state.json,sha256=mUthDnKSXIfRp1LcoLpz12HTbbsAveeznAn6OcFoEb8,249 +olmo_data/hf_datasets/hails/mmlu_no_train/management/validation/data-00000-of-00001.arrow,sha256=YjCX6844k2NOucPm0uvzoBC8xTRZqIuJ13C2rviKnUc,3032 +olmo_data/hf_datasets/hails/mmlu_no_train/management/validation/dataset_info.json,sha256=T1Y0nXPbO7sD5WYJVyV0uPdZzW0Z2rVXHXQeKZjF1IU,1959 +olmo_data/hf_datasets/hails/mmlu_no_train/management/validation/state.json,sha256=VX4zR3A1LgPUvUWFiqptaSx2g3T7R1Jiwu39wdVsZGQ,255 +olmo_data/hf_datasets/hails/mmlu_no_train/marketing/dev/data-00000-of-00001.arrow,sha256=xoZA9l_FJxvHFV6NbR7Plwnalp8PgS26NoyzhgN_k30,2608 +olmo_data/hf_datasets/hails/mmlu_no_train/marketing/dev/dataset_info.json,sha256=pEA7rTSpLW0yNG4ZPDh8jPqyzAqV9pd1ahS0Yy32WmE,1959 +olmo_data/hf_datasets/hails/mmlu_no_train/marketing/dev/state.json,sha256=ieeOpAv4HUxfFXiQa9boG2C3b3GxCCxm3PS2lf2XWt8,248 +olmo_data/hf_datasets/hails/mmlu_no_train/marketing/test/data-00000-of-00001.arrow,sha256=gkS8xOjDLty8lEORlfzm86UUSLFXHEH9jDpPovvQ2qw,67136 +olmo_data/hf_datasets/hails/mmlu_no_train/marketing/test/dataset_info.json,sha256=pEA7rTSpLW0yNG4ZPDh8jPqyzAqV9pd1ahS0Yy32WmE,1959 +olmo_data/hf_datasets/hails/mmlu_no_train/marketing/test/state.json,sha256=teMxsaKjdlJm9fSXvmxrjfRKhPLGoiSLHhLSbOJx4fY,249 +olmo_data/hf_datasets/hails/mmlu_no_train/marketing/validation/data-00000-of-00001.arrow,sha256=k_nIQAdOVLhJibjSQcRmo_UKDYKk-UJk-5UWG6X_Mqw,8776 +olmo_data/hf_datasets/hails/mmlu_no_train/marketing/validation/dataset_info.json,sha256=pEA7rTSpLW0yNG4ZPDh8jPqyzAqV9pd1ahS0Yy32WmE,1959 +olmo_data/hf_datasets/hails/mmlu_no_train/marketing/validation/state.json,sha256=-IE23OZ0WMx3-TWuoQ49jarEFiC1vGm05UPVqaJ-sTc,255 +olmo_data/hf_datasets/hails/mmlu_no_train/medical_genetics/dev/data-00000-of-00001.arrow,sha256=wmJmEoEyIGZqc9Sn39mgF-QyhHtbvqac-mYvC7G1hps,2240 +olmo_data/hf_datasets/hails/mmlu_no_train/medical_genetics/dev/dataset_info.json,sha256=_u9xD10FNZfSIpL-R3XeNOzFTJa9976iQVEkaWrd9Q8,1966 +olmo_data/hf_datasets/hails/mmlu_no_train/medical_genetics/dev/state.json,sha256=U8Z6ilPaw8gOLwzWJ481_WxRBNPL185yXFpZ27NC15c,248 +olmo_data/hf_datasets/hails/mmlu_no_train/medical_genetics/test/data-00000-of-00001.arrow,sha256=EdjBf4BPNrxdW4M-TRoLBudfFSZRkVKKQEGF7J64OIQ,23928 +olmo_data/hf_datasets/hails/mmlu_no_train/medical_genetics/test/dataset_info.json,sha256=_u9xD10FNZfSIpL-R3XeNOzFTJa9976iQVEkaWrd9Q8,1966 +olmo_data/hf_datasets/hails/mmlu_no_train/medical_genetics/test/state.json,sha256=WzWKo5DcTauoKrWyJ8SrgCpOoW4AFizgpnAaGgzKklM,249 +olmo_data/hf_datasets/hails/mmlu_no_train/medical_genetics/validation/data-00000-of-00001.arrow,sha256=5P1EoLPyeSqZ0SBqpA6YD7FQ9oSldz9CWl-fHds-68Y,4280 +olmo_data/hf_datasets/hails/mmlu_no_train/medical_genetics/validation/dataset_info.json,sha256=_u9xD10FNZfSIpL-R3XeNOzFTJa9976iQVEkaWrd9Q8,1966 +olmo_data/hf_datasets/hails/mmlu_no_train/medical_genetics/validation/state.json,sha256=UyC15oUnULv8KpwzK7nSFsFHIgZLbqvTLCD0mRhhs0s,255 +olmo_data/hf_datasets/hails/mmlu_no_train/miscellaneous/dev/data-00000-of-00001.arrow,sha256=EZQRiMIaNeiyE5qLpz8ZfHS5x3u7ok9YwNENkfc5X08,1848 +olmo_data/hf_datasets/hails/mmlu_no_train/miscellaneous/dev/dataset_info.json,sha256=gWKFZuLP9vFk2DOSYqSSRR4potB41tDugF2Xm1f1V58,1965 +olmo_data/hf_datasets/hails/mmlu_no_train/miscellaneous/dev/state.json,sha256=rOuDLi8ote1VBpBH9rRsFgGZJcMzYXNS5agndTgx-dc,248 +olmo_data/hf_datasets/hails/mmlu_no_train/miscellaneous/test/data-00000-of-00001.arrow,sha256=Eukc17AFYjHDX64Xmx6cgnHEmomkgNxIjRtNc5ePewc,162072 +olmo_data/hf_datasets/hails/mmlu_no_train/miscellaneous/test/dataset_info.json,sha256=gWKFZuLP9vFk2DOSYqSSRR4potB41tDugF2Xm1f1V58,1965 +olmo_data/hf_datasets/hails/mmlu_no_train/miscellaneous/test/state.json,sha256=gb6FhhxJSWwas83B_Km_NuIivHm6dgcKHKoJ5zk3K6E,249 +olmo_data/hf_datasets/hails/mmlu_no_train/miscellaneous/validation/data-00000-of-00001.arrow,sha256=IPPVrKN2J95Rw7svAWJFHIwSPRRLrRQlAaICfhfHdlE,16864 +olmo_data/hf_datasets/hails/mmlu_no_train/miscellaneous/validation/dataset_info.json,sha256=gWKFZuLP9vFk2DOSYqSSRR4potB41tDugF2Xm1f1V58,1965 +olmo_data/hf_datasets/hails/mmlu_no_train/miscellaneous/validation/state.json,sha256=wW4tB0Kv2-LNqTfgCK-3ZuFSoIKGN6CBoTdruKnO_-E,255 +olmo_data/hf_datasets/hails/mmlu_no_train/moral_disputes/dev/data-00000-of-00001.arrow,sha256=fINXt19ZTRw2Z3kNpdlgKvLtCNTbUlVM1GvLRjL8k6A,2904 +olmo_data/hf_datasets/hails/mmlu_no_train/moral_disputes/dev/dataset_info.json,sha256=V5IdcQoEW4djxudNyMNix-W-7AoSqd51KhBKpkHYC18,1967 +olmo_data/hf_datasets/hails/mmlu_no_train/moral_disputes/dev/state.json,sha256=lVGdW6VWc8aNUO0R83DSJVftOEKONdym0-eHvZ6CWNs,248 +olmo_data/hf_datasets/hails/mmlu_no_train/moral_disputes/test/data-00000-of-00001.arrow,sha256=euc3L2ke6tFdaLS8xCwGXpzwTW5Bzr8RGOlbIBTHbZk,115120 +olmo_data/hf_datasets/hails/mmlu_no_train/moral_disputes/test/dataset_info.json,sha256=V5IdcQoEW4djxudNyMNix-W-7AoSqd51KhBKpkHYC18,1967 +olmo_data/hf_datasets/hails/mmlu_no_train/moral_disputes/test/state.json,sha256=BxpZlndqj79e5IA_qYEI-_KUb0M82wSkr6z3Ol4fgYE,249 +olmo_data/hf_datasets/hails/mmlu_no_train/moral_disputes/validation/data-00000-of-00001.arrow,sha256=u18A0VFOgEACW5FHgeo_DZqg77GXL_tg0Wmx2vOkaiA,14176 +olmo_data/hf_datasets/hails/mmlu_no_train/moral_disputes/validation/dataset_info.json,sha256=V5IdcQoEW4djxudNyMNix-W-7AoSqd51KhBKpkHYC18,1967 +olmo_data/hf_datasets/hails/mmlu_no_train/moral_disputes/validation/state.json,sha256=oE4APfQtFucGPQ_LJUriCLb_c_JfvZs1il-K0Fq1uoM,255 +olmo_data/hf_datasets/hails/mmlu_no_train/moral_scenarios/dev/data-00000-of-00001.arrow,sha256=2ZWmZgfKu-GymW9IVNOHodCv08_lS9Rjb8M8vSQvGFA,3208 +olmo_data/hf_datasets/hails/mmlu_no_train/moral_scenarios/dev/dataset_info.json,sha256=XvYutnTMU0a5LNc0BTIVqhAH6tb3PBPWcp3O2fTq61Y,1969 +olmo_data/hf_datasets/hails/mmlu_no_train/moral_scenarios/dev/state.json,sha256=FoY97fXG2mOaS3vHdHlSpSTVtO9tXBPzFPz7lf53LSQ,248 +olmo_data/hf_datasets/hails/mmlu_no_train/moral_scenarios/test/data-00000-of-00001.arrow,sha256=Q8M66ou2wKYDJ3VOGDN9pN2RKiRzj6FsxgBlXM_AjeQ,392088 +olmo_data/hf_datasets/hails/mmlu_no_train/moral_scenarios/test/dataset_info.json,sha256=XvYutnTMU0a5LNc0BTIVqhAH6tb3PBPWcp3O2fTq61Y,1969 +olmo_data/hf_datasets/hails/mmlu_no_train/moral_scenarios/test/state.json,sha256=VaZ2D_H2EdOEM5V0JC4z66JX9BBbKJZOo4vLkdnUjf4,249 +olmo_data/hf_datasets/hails/mmlu_no_train/moral_scenarios/validation/data-00000-of-00001.arrow,sha256=aPvaVQmaScMB5RZi0lLAelIm2R84MXq0O5zEPRIw2Fw,45304 +olmo_data/hf_datasets/hails/mmlu_no_train/moral_scenarios/validation/dataset_info.json,sha256=XvYutnTMU0a5LNc0BTIVqhAH6tb3PBPWcp3O2fTq61Y,1969 +olmo_data/hf_datasets/hails/mmlu_no_train/moral_scenarios/validation/state.json,sha256=1ImurzjOdrQRfsjpMrN4s5pCXr2-p-nryZSyeG4hxY0,255 +olmo_data/hf_datasets/hails/mmlu_no_train/nutrition/dev/data-00000-of-00001.arrow,sha256=EoavriSn6I0yMRt3g5zuCMT5qE44MaZV7dDEJpk4Tlo,3208 +olmo_data/hf_datasets/hails/mmlu_no_train/nutrition/dev/dataset_info.json,sha256=WhwaANfMoZb5fWG6PavBcr2k0T2Fn6ir-aY_V3r19ok,1960 +olmo_data/hf_datasets/hails/mmlu_no_train/nutrition/dev/state.json,sha256=VH8Ige23VXEsThhaKzVUvBo6f33LLG09JNNOyDFzyC8,248 +olmo_data/hf_datasets/hails/mmlu_no_train/nutrition/test/data-00000-of-00001.arrow,sha256=uckpng6HR46fVWL9T1jU7BuTJnccb0pVfVjbFX6WDKA,97456 +olmo_data/hf_datasets/hails/mmlu_no_train/nutrition/test/dataset_info.json,sha256=WhwaANfMoZb5fWG6PavBcr2k0T2Fn6ir-aY_V3r19ok,1960 +olmo_data/hf_datasets/hails/mmlu_no_train/nutrition/test/state.json,sha256=txErDkXLUzYn7_ppFtq0YVuRDg3j0AFwvcfy0L9k8Eo,249 +olmo_data/hf_datasets/hails/mmlu_no_train/nutrition/validation/data-00000-of-00001.arrow,sha256=bBrKl8L57OmkjQD4U2c16pvSUd8RR2sV6D449qpH3BQ,9928 +olmo_data/hf_datasets/hails/mmlu_no_train/nutrition/validation/dataset_info.json,sha256=WhwaANfMoZb5fWG6PavBcr2k0T2Fn6ir-aY_V3r19ok,1960 +olmo_data/hf_datasets/hails/mmlu_no_train/nutrition/validation/state.json,sha256=eRIj1Iojy5DLmJdAoUfS5KHSn3nse3mPiBwgv2qDf7k,255 +olmo_data/hf_datasets/hails/mmlu_no_train/philosophy/dev/data-00000-of-00001.arrow,sha256=tyUABmOfWwtDyjIjjqHCPgo2X27-c9lSVFcnVVnZc6c,2120 +olmo_data/hf_datasets/hails/mmlu_no_train/philosophy/dev/dataset_info.json,sha256=9sRdsHpVwBO2kNjoyh1BTFyvcl2BQ-tOh_Je_M7ZWqY,1960 +olmo_data/hf_datasets/hails/mmlu_no_train/philosophy/dev/state.json,sha256=mCg4YRwRy1-dUkha5Iwh8VaEWq0SIZs7FS6qqIqE3DI,248 +olmo_data/hf_datasets/hails/mmlu_no_train/philosophy/test/data-00000-of-00001.arrow,sha256=JsBJ5XmH4he95_Mg1hd3Xh97iGHqdIOcUqdXI0rF0gI,85480 +olmo_data/hf_datasets/hails/mmlu_no_train/philosophy/test/dataset_info.json,sha256=9sRdsHpVwBO2kNjoyh1BTFyvcl2BQ-tOh_Je_M7ZWqY,1960 +olmo_data/hf_datasets/hails/mmlu_no_train/philosophy/test/state.json,sha256=vKlAwEeEGhQQH5FVGbFUpxh8xr1sM0FLEYZHglYnY-g,249 +olmo_data/hf_datasets/hails/mmlu_no_train/philosophy/validation/data-00000-of-00001.arrow,sha256=3V_jiBadnWEheKxhSQ1iJTJpdWoqRBSmMy63umTIM74,10736 +olmo_data/hf_datasets/hails/mmlu_no_train/philosophy/validation/dataset_info.json,sha256=9sRdsHpVwBO2kNjoyh1BTFyvcl2BQ-tOh_Je_M7ZWqY,1960 +olmo_data/hf_datasets/hails/mmlu_no_train/philosophy/validation/state.json,sha256=RH0_2G14djdKT3lBCzQ8v8B_wrl7VlSaJvyxx_lXuQU,255 +olmo_data/hf_datasets/hails/mmlu_no_train/prehistory/dev/data-00000-of-00001.arrow,sha256=J-Yh6LTqEFshP0EwOZVkfD9JTIRAnkRX268_RfVJD_U,3008 +olmo_data/hf_datasets/hails/mmlu_no_train/prehistory/dev/dataset_info.json,sha256=G8PkRcPd1-yIHvTAwjjXmeKV_wH31e2z2lS6JcRx1rQ,1962 +olmo_data/hf_datasets/hails/mmlu_no_train/prehistory/dev/state.json,sha256=kBxLZaOtpUIom9rM-WDgL4FRiFIT8Q7YPfTtMA5Cf8U,248 +olmo_data/hf_datasets/hails/mmlu_no_train/prehistory/test/data-00000-of-00001.arrow,sha256=zEUh6E7-xP-1o0m5VICdUzABnbpgjE5UkhYJavi7KGA,95192 +olmo_data/hf_datasets/hails/mmlu_no_train/prehistory/test/dataset_info.json,sha256=G8PkRcPd1-yIHvTAwjjXmeKV_wH31e2z2lS6JcRx1rQ,1962 +olmo_data/hf_datasets/hails/mmlu_no_train/prehistory/test/state.json,sha256=jf4Pi59JFn0gR8yXoQC-3pdPVXu5K50ygy-af4Ety10,249 +olmo_data/hf_datasets/hails/mmlu_no_train/prehistory/validation/data-00000-of-00001.arrow,sha256=1i7AgB_tWDJ9Pc5YfFmrmP0YjTPI2sYmAVJauo_c0Io,11832 +olmo_data/hf_datasets/hails/mmlu_no_train/prehistory/validation/dataset_info.json,sha256=G8PkRcPd1-yIHvTAwjjXmeKV_wH31e2z2lS6JcRx1rQ,1962 +olmo_data/hf_datasets/hails/mmlu_no_train/prehistory/validation/state.json,sha256=1h_0mTwPEwhGhhZBUuPK6ModbltLaaaLtOIiEYE_f5Q,255 +olmo_data/hf_datasets/hails/mmlu_no_train/professional_accounting/dev/data-00000-of-00001.arrow,sha256=NaV404-BbM1tFZ0T5CJfA4e8IBxnV1FaCxSMb8Uhb0U,3344 +olmo_data/hf_datasets/hails/mmlu_no_train/professional_accounting/dev/dataset_info.json,sha256=id7lBEk1ZdtVXyqcG2PyCHYFsFr-JU2iZsWqHd7NjrQ,1976 +olmo_data/hf_datasets/hails/mmlu_no_train/professional_accounting/dev/state.json,sha256=9qPD9nIUsg37fAo-OCafwNTYzOUWx4AldawBMvMylwk,248 +olmo_data/hf_datasets/hails/mmlu_no_train/professional_accounting/test/data-00000-of-00001.arrow,sha256=B3whHcd4cBJjEyohqF7ouD3BdvI3TJeRgN4kThIgAgk,133232 +olmo_data/hf_datasets/hails/mmlu_no_train/professional_accounting/test/dataset_info.json,sha256=id7lBEk1ZdtVXyqcG2PyCHYFsFr-JU2iZsWqHd7NjrQ,1976 +olmo_data/hf_datasets/hails/mmlu_no_train/professional_accounting/test/state.json,sha256=Y_GHNpTyO-aG6pWng1v9hK2nVuGAstyzlnkT17uujpo,249 +olmo_data/hf_datasets/hails/mmlu_no_train/professional_accounting/validation/data-00000-of-00001.arrow,sha256=BPl3nDOBGGpA6PohOsF02loUQ2-ogK3z8icsKtktrZ4,16272 +olmo_data/hf_datasets/hails/mmlu_no_train/professional_accounting/validation/dataset_info.json,sha256=id7lBEk1ZdtVXyqcG2PyCHYFsFr-JU2iZsWqHd7NjrQ,1976 +olmo_data/hf_datasets/hails/mmlu_no_train/professional_accounting/validation/state.json,sha256=3G-Vztrmzpk97hzLyN6H4a2gedgjua5uh044ZkEeutc,255 +olmo_data/hf_datasets/hails/mmlu_no_train/professional_law/dev/data-00000-of-00001.arrow,sha256=H6TVveqXw3S0I3-35_F4Eoi_e-gtaUf65ZDorEZMMRM,7768 +olmo_data/hf_datasets/hails/mmlu_no_train/professional_law/dev/dataset_info.json,sha256=r9qDygpxYOAIRGccyQx6GYnxGFOpFO8I2E12HqhGU-w,1974 +olmo_data/hf_datasets/hails/mmlu_no_train/professional_law/dev/state.json,sha256=pL0dM1fE3cnvnsHYS6c9PKeVRhg3wPhKIt8cULkvtUw,248 +olmo_data/hf_datasets/hails/mmlu_no_train/professional_law/test/data-00000-of-00001.arrow,sha256=yNRncZeQcCCvRtqtGkbRhW1-vZUYr6kVrRVOe9w1O4M,1923936 +olmo_data/hf_datasets/hails/mmlu_no_train/professional_law/test/dataset_info.json,sha256=r9qDygpxYOAIRGccyQx6GYnxGFOpFO8I2E12HqhGU-w,1974 +olmo_data/hf_datasets/hails/mmlu_no_train/professional_law/test/state.json,sha256=zwSyPO9IZJkSB4j6Rga5ko6C8gQgzGPMVEP4W2omVxM,249 +olmo_data/hf_datasets/hails/mmlu_no_train/professional_law/validation/data-00000-of-00001.arrow,sha256=G7LOHUHevSNO9ekipqQnIlAYKOqgmvuWKAJm--XWuTM,207984 +olmo_data/hf_datasets/hails/mmlu_no_train/professional_law/validation/dataset_info.json,sha256=r9qDygpxYOAIRGccyQx6GYnxGFOpFO8I2E12HqhGU-w,1974 +olmo_data/hf_datasets/hails/mmlu_no_train/professional_law/validation/state.json,sha256=AITC52TJjDKCngUYSakyevj7JHF4DBXAzwAIGZAISbA,255 +olmo_data/hf_datasets/hails/mmlu_no_train/professional_medicine/dev/data-00000-of-00001.arrow,sha256=CTKP0OQgqawhRjS5XTMm3uZzH6t5_YhL6jNyaj89A5s,4992 +olmo_data/hf_datasets/hails/mmlu_no_train/professional_medicine/dev/dataset_info.json,sha256=aECUqhQoT6Sof4ZQNMyU7ZUL3G5U6Q_zoy9-oZyKdsA,1974 +olmo_data/hf_datasets/hails/mmlu_no_train/professional_medicine/dev/state.json,sha256=z-IkZvRZ2GwG-Kbc3Xt9mxJg1f2G0DUU6nJCNukm5_4,248 +olmo_data/hf_datasets/hails/mmlu_no_train/professional_medicine/test/data-00000-of-00001.arrow,sha256=r1FOwAhyqU8gXeh7mYX9ikxUDzGhVIs59NGQbfb5j2M,225432 +olmo_data/hf_datasets/hails/mmlu_no_train/professional_medicine/test/dataset_info.json,sha256=aECUqhQoT6Sof4ZQNMyU7ZUL3G5U6Q_zoy9-oZyKdsA,1974 +olmo_data/hf_datasets/hails/mmlu_no_train/professional_medicine/test/state.json,sha256=liSRQRjA_xhpwFSZ19oiBmJTFS4cAiJTA6IzGxtvfJI,249 +olmo_data/hf_datasets/hails/mmlu_no_train/professional_medicine/validation/data-00000-of-00001.arrow,sha256=0tjhf7q7birHMEckksw9EeeZ-b7h2DkiJhn20pi6DqI,25680 +olmo_data/hf_datasets/hails/mmlu_no_train/professional_medicine/validation/dataset_info.json,sha256=aECUqhQoT6Sof4ZQNMyU7ZUL3G5U6Q_zoy9-oZyKdsA,1974 +olmo_data/hf_datasets/hails/mmlu_no_train/professional_medicine/validation/state.json,sha256=57zTI93JnoPDGaCnhaYoPs8wsexxuXHZXPoOlvK_go4,255 +olmo_data/hf_datasets/hails/mmlu_no_train/professional_psychology/dev/data-00000-of-00001.arrow,sha256=qpe3iYJ7AjsjjDX4E-OkXTtUhquV1seUAtltwtHGz5w,3464 +olmo_data/hf_datasets/hails/mmlu_no_train/professional_psychology/dev/dataset_info.json,sha256=-zhW4sEHb_ts6V6MEMJjvynEjD2iFzmyyVnU8GmCJOE,1976 +olmo_data/hf_datasets/hails/mmlu_no_train/professional_psychology/dev/state.json,sha256=kHkss88Oyo3FFX0bjwOLU185-ArZWlOwv29TcLCtHKw,248 +olmo_data/hf_datasets/hails/mmlu_no_train/professional_psychology/test/data-00000-of-00001.arrow,sha256=H8erUkl3kT2x9IE-httbZ80GSsGRZo12P-uRAM1wtQo,243488 +olmo_data/hf_datasets/hails/mmlu_no_train/professional_psychology/test/dataset_info.json,sha256=-zhW4sEHb_ts6V6MEMJjvynEjD2iFzmyyVnU8GmCJOE,1976 +olmo_data/hf_datasets/hails/mmlu_no_train/professional_psychology/test/state.json,sha256=ULbG7waeo5RDxIyg3Cg6i9Uw5ETNrUPO9nQ9sizi_kU,249 +olmo_data/hf_datasets/hails/mmlu_no_train/professional_psychology/validation/data-00000-of-00001.arrow,sha256=Xt6UJrNXjCRQ3TOCcv59mwF2VgLThBkqY1PZ4jIhCL8,32024 +olmo_data/hf_datasets/hails/mmlu_no_train/professional_psychology/validation/dataset_info.json,sha256=-zhW4sEHb_ts6V6MEMJjvynEjD2iFzmyyVnU8GmCJOE,1976 +olmo_data/hf_datasets/hails/mmlu_no_train/professional_psychology/validation/state.json,sha256=MDyQTQI4MfsPCU-xoIwCaiYmDxaeNECiBQErdBLIjfs,255 +olmo_data/hf_datasets/hails/mmlu_no_train/public_relations/dev/data-00000-of-00001.arrow,sha256=E-odcrujIVrAHF4wS6mzea1A7NOUY8E5rg2LtutK72k,2656 +olmo_data/hf_datasets/hails/mmlu_no_train/public_relations/dev/dataset_info.json,sha256=2o0kjk7kMuCbZNPWkfG0yWKXU1JDO15qI6J-0jwIOJE,1966 +olmo_data/hf_datasets/hails/mmlu_no_train/public_relations/dev/state.json,sha256=vr0ZAor2Y6nlaqxu4NL07TvIBKMyqCp87AveQCCPJjI,248 +olmo_data/hf_datasets/hails/mmlu_no_train/public_relations/test/data-00000-of-00001.arrow,sha256=W_mvZOb5qg2QWo9zuGFieCXSKqIRgYKWpaT7Bz4_oUM,32032 +olmo_data/hf_datasets/hails/mmlu_no_train/public_relations/test/dataset_info.json,sha256=2o0kjk7kMuCbZNPWkfG0yWKXU1JDO15qI6J-0jwIOJE,1966 +olmo_data/hf_datasets/hails/mmlu_no_train/public_relations/test/state.json,sha256=R7SWHNU-LW6mYUw-F5cJOKJDjP6Mgy_MVYAjKhzawkA,249 +olmo_data/hf_datasets/hails/mmlu_no_train/public_relations/validation/data-00000-of-00001.arrow,sha256=f_aSzP8ViucSS3PN6h9UT6iwQ8b8W2jlY2ylXv2ZUdw,5880 +olmo_data/hf_datasets/hails/mmlu_no_train/public_relations/validation/dataset_info.json,sha256=2o0kjk7kMuCbZNPWkfG0yWKXU1JDO15qI6J-0jwIOJE,1966 +olmo_data/hf_datasets/hails/mmlu_no_train/public_relations/validation/state.json,sha256=vcMVjAt6jmHBnt1m8HUS851lVp5Z0Ax73naxXz8SmAA,255 +olmo_data/hf_datasets/hails/mmlu_no_train/security_studies/dev/data-00000-of-00001.arrow,sha256=taO7R2iw-X1N8J17XviAllDpI0grEYT7PN11MNU2q8U,6488 +olmo_data/hf_datasets/hails/mmlu_no_train/security_studies/dev/dataset_info.json,sha256=G_iwB12wyfdKpuQvDtYa6MhzFgqVpnfocQboG-scqW0,1969 +olmo_data/hf_datasets/hails/mmlu_no_train/security_studies/dev/state.json,sha256=j4KHLi0BdH31DeqLa4PUFvnBz06Sa6CORPiyuzFJSFc,248 +olmo_data/hf_datasets/hails/mmlu_no_train/security_studies/test/data-00000-of-00001.arrow,sha256=3iuCzBajixXtTMUXB7NhPmblrZI0JVBNV-HFTqLxSdA,210800 +olmo_data/hf_datasets/hails/mmlu_no_train/security_studies/test/dataset_info.json,sha256=G_iwB12wyfdKpuQvDtYa6MhzFgqVpnfocQboG-scqW0,1969 +olmo_data/hf_datasets/hails/mmlu_no_train/security_studies/test/state.json,sha256=1Awp4WEhU4wf06f4-ayMttzr2eq1aMRj4anlIshiNg8,249 +olmo_data/hf_datasets/hails/mmlu_no_train/security_studies/validation/data-00000-of-00001.arrow,sha256=k2awA8a5euQLZG1Z7I78fKqrNmIhCgrpcSD7OKxZTVY,24232 +olmo_data/hf_datasets/hails/mmlu_no_train/security_studies/validation/dataset_info.json,sha256=G_iwB12wyfdKpuQvDtYa6MhzFgqVpnfocQboG-scqW0,1969 +olmo_data/hf_datasets/hails/mmlu_no_train/security_studies/validation/state.json,sha256=CWqxN9cJ5uY0bT8bELq-dh93Fz74o3wi4fs8EKu03sc,255 +olmo_data/hf_datasets/hails/mmlu_no_train/sociology/dev/data-00000-of-00001.arrow,sha256=X0jwJzmT3IqnebTFeb21cE1kPdFwfGNBKM_PDUe8H_0,2736 +olmo_data/hf_datasets/hails/mmlu_no_train/sociology/dev/dataset_info.json,sha256=SMSGv3_AjFSFOsqzdLFxC68Oiw_KU9nz1-6UHmlPGx0,1959 +olmo_data/hf_datasets/hails/mmlu_no_train/sociology/dev/state.json,sha256=qK8uQBBuopNeU84FRYNRMjp0FRmH9NjKRnwUmRkn7RQ,248 +olmo_data/hf_datasets/hails/mmlu_no_train/sociology/test/data-00000-of-00001.arrow,sha256=1DSYlAv7qpXb1bUiWq6vuP-NA91TyZ8F9GmXSpwhv9A,69920 +olmo_data/hf_datasets/hails/mmlu_no_train/sociology/test/dataset_info.json,sha256=SMSGv3_AjFSFOsqzdLFxC68Oiw_KU9nz1-6UHmlPGx0,1959 +olmo_data/hf_datasets/hails/mmlu_no_train/sociology/test/state.json,sha256=pPMypPpha6DQF8Dlx5bFqGYryrW0n4js7Y_IMl7835U,249 +olmo_data/hf_datasets/hails/mmlu_no_train/sociology/validation/data-00000-of-00001.arrow,sha256=EEqb22ion6KOy2xdEV3LtN6VIFQ7RsBLY4DD9kiE4qw,8536 +olmo_data/hf_datasets/hails/mmlu_no_train/sociology/validation/dataset_info.json,sha256=SMSGv3_AjFSFOsqzdLFxC68Oiw_KU9nz1-6UHmlPGx0,1959 +olmo_data/hf_datasets/hails/mmlu_no_train/sociology/validation/state.json,sha256=vcTE3_IOWM5WtUvSjlVB5yr-I2mWom-6J_Vqmwd9-So,255 +olmo_data/hf_datasets/hails/mmlu_no_train/us_foreign_policy/dev/data-00000-of-00001.arrow,sha256=fzDmR8Qk9YOi-h7NqDAHvSK4lxGVazpsggabZkek4Fs,2776 +olmo_data/hf_datasets/hails/mmlu_no_train/us_foreign_policy/dev/dataset_info.json,sha256=GX7zqlAXUhPaC7Wgp8v4yA-6PWVcVwQkjWJuVKH67Xw,1967 +olmo_data/hf_datasets/hails/mmlu_no_train/us_foreign_policy/dev/state.json,sha256=46k9cKEXOLVpFE7ukEJLF9IX5NNtMJy1gV9PWqpkeSY,248 +olmo_data/hf_datasets/hails/mmlu_no_train/us_foreign_policy/test/data-00000-of-00001.arrow,sha256=AVHXbWTU_O076S4MkIgU3zq54dVJMmRVYA6y5vqKfu4,31616 +olmo_data/hf_datasets/hails/mmlu_no_train/us_foreign_policy/test/dataset_info.json,sha256=GX7zqlAXUhPaC7Wgp8v4yA-6PWVcVwQkjWJuVKH67Xw,1967 +olmo_data/hf_datasets/hails/mmlu_no_train/us_foreign_policy/test/state.json,sha256=_OCGgvtVXiIyofrgNBb5173uFmRA-GICsU_-kEWqzTE,249 +olmo_data/hf_datasets/hails/mmlu_no_train/us_foreign_policy/validation/data-00000-of-00001.arrow,sha256=dY0XvwvYQ3IIZ3wjFnqc5vvmiCKblzucvNVk20wWAIA,4560 +olmo_data/hf_datasets/hails/mmlu_no_train/us_foreign_policy/validation/dataset_info.json,sha256=GX7zqlAXUhPaC7Wgp8v4yA-6PWVcVwQkjWJuVKH67Xw,1967 +olmo_data/hf_datasets/hails/mmlu_no_train/us_foreign_policy/validation/state.json,sha256=MQjwNU25-BVQNFiU0xje0lNFJXCjhIAomDdqHwEZp8k,255 +olmo_data/hf_datasets/hails/mmlu_no_train/virology/dev/data-00000-of-00001.arrow,sha256=tnbBuh4dXgpIOPh02KyJaugoD3pLKfHETgnDuWdA4LQ,2208 +olmo_data/hf_datasets/hails/mmlu_no_train/virology/dev/dataset_info.json,sha256=9Db3WthVzv2gpWFY2uaAAyTdAYS-EoqmlUdJ_eVk7xI,1958 +olmo_data/hf_datasets/hails/mmlu_no_train/virology/dev/state.json,sha256=AxGz6H4-H2iIips-hsFMvSMJS7e_pyJvUFP8UQqZNaw,248 +olmo_data/hf_datasets/hails/mmlu_no_train/virology/test/data-00000-of-00001.arrow,sha256=1l6FsO4AbUcUEE8CkO_P4IB5dnte1BJgZ748HUEY6iU,41816 +olmo_data/hf_datasets/hails/mmlu_no_train/virology/test/dataset_info.json,sha256=9Db3WthVzv2gpWFY2uaAAyTdAYS-EoqmlUdJ_eVk7xI,1958 +olmo_data/hf_datasets/hails/mmlu_no_train/virology/test/state.json,sha256=xJzMJIYwTeuHj3CHkAP0OMB3ZbjRpHAU1Sc9hq3h9S8,249 +olmo_data/hf_datasets/hails/mmlu_no_train/virology/validation/data-00000-of-00001.arrow,sha256=5QWdNYf7V15634B6469rYw3VjMz2VNILenHwD0Fgq2w,6744 +olmo_data/hf_datasets/hails/mmlu_no_train/virology/validation/dataset_info.json,sha256=9Db3WthVzv2gpWFY2uaAAyTdAYS-EoqmlUdJ_eVk7xI,1958 +olmo_data/hf_datasets/hails/mmlu_no_train/virology/validation/state.json,sha256=u2GlTIBXzbLU4yvOQFMuCiCNqBA9kZzZnfBhwHZXiIY,255 +olmo_data/hf_datasets/hails/mmlu_no_train/world_religions/dev/data-00000-of-00001.arrow,sha256=gcmjywgyfOOZLyWuDhle7GMcFdQNvt6ADJdcgA4N86A,1824 +olmo_data/hf_datasets/hails/mmlu_no_train/world_religions/dev/dataset_info.json,sha256=OotV2Byh-_JlyAUMVMT1CmHzp5P2atZcZjO66AarWv8,1964 +olmo_data/hf_datasets/hails/mmlu_no_train/world_religions/dev/state.json,sha256=tbj-AEAPXIovFLb7en3S1d6ZJR4xMQ1A1i9N76zezII,248 +olmo_data/hf_datasets/hails/mmlu_no_train/world_religions/test/data-00000-of-00001.arrow,sha256=zgBcBGZEuXjgtRTmYg0958vkJlwpo-aLXLLg734oVCM,29584 +olmo_data/hf_datasets/hails/mmlu_no_train/world_religions/test/dataset_info.json,sha256=OotV2Byh-_JlyAUMVMT1CmHzp5P2atZcZjO66AarWv8,1964 +olmo_data/hf_datasets/hails/mmlu_no_train/world_religions/test/state.json,sha256=eX1hqtphtdJIg_m40D0X8la-Kw3cy3aUdMiDB3rbdlA,249 +olmo_data/hf_datasets/hails/mmlu_no_train/world_religions/validation/data-00000-of-00001.arrow,sha256=nBkG7tM0Tef48uOMVks4-NohHGZb6G-6z-babU2dxXo,4184 +olmo_data/hf_datasets/hails/mmlu_no_train/world_religions/validation/dataset_info.json,sha256=OotV2Byh-_JlyAUMVMT1CmHzp5P2atZcZjO66AarWv8,1964 +olmo_data/hf_datasets/hails/mmlu_no_train/world_religions/validation/state.json,sha256=fM5CDsTML5LSPjJ0qZ3CSwzoCq4FdZoIFzPDjUKZYHg,255 +olmo_data/hf_datasets/hellaswag/none/validation/data-00000-of-00001.arrow,sha256=XSGozz-VKA8pFhKO1IDGtRihGqyxix6iAO79jAuSwWs,11186432 +olmo_data/hf_datasets/hellaswag/none/validation/dataset_info.json,sha256=8303EcfZdPJe9mdKmd32BsxdrTy4BBs65jGvGVZGiv4,2560 +olmo_data/hf_datasets/hellaswag/none/validation/state.json,sha256=GVRRNWTQPs7IQdDnZt3zMjNFWVIMfGTlWee7BLCyjIM,255 +olmo_data/hf_datasets/nq_open/none/validation/data-00000-of-00001.arrow,sha256=ouYG1t1Hj1HsLlfRpJL7WlOTlTO1YTZYdrMMRurhjdE,315488 +olmo_data/hf_datasets/nq_open/none/validation/dataset_info.json,sha256=PiR2rW1B_dXxJxWBZZ5ro-82AdaQ57N3hzvvj8trbRE,1225 +olmo_data/hf_datasets/nq_open/none/validation/state.json,sha256=TDk_aY0tgQp5CssPvzpbDek1e0HAqH-HzpJ-3qfFu_s,255 +olmo_data/hf_datasets/openbookqa/main/validation/data-00000-of-00001.arrow,sha256=BxVbASyUIGBfxWd6WJumc_OqkSLF6ECPXD8PMguIaQ8,96872 +olmo_data/hf_datasets/openbookqa/main/validation/dataset_info.json,sha256=MbPRLqIUSLwM8DdhesJLKKlWLbhCWDFj7zfDyDyHZKE,1783 +olmo_data/hf_datasets/openbookqa/main/validation/state.json,sha256=Ct77C1cq-4QRQButkkWRtrN4v44NUo5c86Hojxm1h_s,255 +olmo_data/hf_datasets/piqa/plain_text/validation/data-00000-of-00001.arrow,sha256=bhRzHHgBatxqVzjWYREfXLTGvORhxFRWHrZr5KvDkiI,465608 +olmo_data/hf_datasets/piqa/plain_text/validation/dataset_info.json,sha256=VGH-vU9FxVjQCetdlr7aElWd7aVIfnDltskzQDYzPCM,3003 +olmo_data/hf_datasets/piqa/plain_text/validation/state.json,sha256=99SO9Jg-xZ79QZVZgdBzkCDCiexK-NfVf-C6R26TOwA,255 +olmo_data/hf_datasets/sciq/none/validation/data-00000-of-00001.arrow,sha256=ZWzfFvQGFzYGg7A5uMKitItHm-BtHfXIsCOvu2SNqb0,555448 +olmo_data/hf_datasets/sciq/none/validation/dataset_info.json,sha256=8zcNI4W4vM5TD_QoxMCNGo7AwJnX1VT0dxdnB0Cz72A,1740 +olmo_data/hf_datasets/sciq/none/validation/state.json,sha256=qaNE8FgeQyneStp1V8x-sPNhwKdLGcxK_BbhbQbOKU0,255 +olmo_data/hf_datasets/social_i_qa/none/validation/data-00000-of-00001.arrow,sha256=gHun0yhCfqL_BNjLUgzPstjvJpqp5i0n7Xm9bBNFyDg,374632 +olmo_data/hf_datasets/social_i_qa/none/validation/dataset_info.json,sha256=D158PcVmJ0tcA5kC7whGup9xqg5NbzyROqclnu3_I9M,2273 +olmo_data/hf_datasets/social_i_qa/none/validation/state.json,sha256=PWmlVm9LqSjhmk7n1DmSRIhLEXU1AZ_07CUbbtQ2DLM,255 +olmo_data/hf_datasets/super_glue/cb/validation/data-00000-of-00001.arrow,sha256=q6aBlhJLU6w8u4xkmCSsNNTASYtSQUSeVOaU5Mk5HpA,22792 +olmo_data/hf_datasets/super_glue/cb/validation/dataset_info.json,sha256=403MDyXIEtLzsitDASdFvcuhRPX6FhNcHxrmkPrY17Q,3155 +olmo_data/hf_datasets/super_glue/cb/validation/state.json,sha256=WnF7Rali0JEcUW_7W_xPz0Hooq0uK80Bsd3jtFXhU0w,255 +olmo_data/hf_datasets/super_glue/copa/validation/data-00000-of-00001.arrow,sha256=DtoKKu3_gApcp4d0h9SnVdmO_pDBmUTdvloTn_tH09k,13744 +olmo_data/hf_datasets/super_glue/copa/validation/dataset_info.json,sha256=nbG45L1bWeWQfWCwoE5YOsyHkHZwI9YoD1I9Yg-ZNWM,3204 +olmo_data/hf_datasets/super_glue/copa/validation/state.json,sha256=GLAIPcaYJY59ddCUZlRkLjLglgU3X4zvRfHYuwTXkVg,255 +olmo_data/hf_datasets/tau/commonsense_qa/none/validation/data-00000-of-00001.arrow,sha256=HbKBagushv9vZ7yzm1Ojz3avf7qm12lgi7vB4dDJrtY,276128 +olmo_data/hf_datasets/tau/commonsense_qa/none/validation/dataset_info.json,sha256=NY4ZaQrNcCHOML_M06scfw7M8OTqOCKHMb8swTPv9Jc,1911 +olmo_data/hf_datasets/tau/commonsense_qa/none/validation/state.json,sha256=FRsf5xkCrJQiMEtk1mVOque94EumqwqrmjFlAvg7VZI,255 +olmo_data/hf_datasets/trivia_qa/rc.wikipedia.nocontext/validation/data-00000-of-00001.arrow,sha256=ImKXf-9HQUuQPXLBtOdpMl1O9RlIEQLCrnciYhY65S0,6386776 +olmo_data/hf_datasets/trivia_qa/rc.wikipedia.nocontext/validation/dataset_info.json,sha256=C3Q_UXXbN9ZWd7nnxnPyx8zXr6ZwziEgZJwJH0CzRbo,3453 +olmo_data/hf_datasets/trivia_qa/rc.wikipedia.nocontext/validation/state.json,sha256=YwlKa157fnm--6SWqjasJ2LX9idM43UyQ3_8HccLHEA,255 +olmo_data/hf_datasets/winogrande/winogrande_xl/validation/data-00000-of-00001.arrow,sha256=mSr4QEsgKtpDViKO0uuyfxBJUSbv33hnjO0z6U6CuDA,165504 +olmo_data/hf_datasets/winogrande/winogrande_xl/validation/dataset_info.json,sha256=9SVyfaJ1f1GIcWh-Dvot65lXCDFj2gksKsKKvDLIcvk,1945 +olmo_data/hf_datasets/winogrande/winogrande_xl/validation/state.json,sha256=hgbS05TZT20V73h1xfeo-KPgFQvrCBsMqTsdrGW7VtQ,255 +olmo_data/oe_eval_tasks/arc_challenge/mc_5shot/config.json,sha256=CFqENkMRgy9t27hdcm2bO8bjMOXOEGx8u0MpVnk1Ubw,633 +olmo_data/oe_eval_tasks/arc_challenge/mc_5shot/requests.jsonl.gz,sha256=mKol4c0UjaiOt8KNhxqbqWePIQzEWG6Shy6nBFSHzUw,68534 +olmo_data/oe_eval_tasks/arc_challenge/rc_0shot/config.json,sha256=cqJ9g3A5dtx7LOPs2GVzg8EBPvE2sWt7YXfeDUBG2TM,544 +olmo_data/oe_eval_tasks/arc_challenge/rc_0shot/requests.jsonl.gz,sha256=7k_6WdtDmV8Qbehoy431WIYpKvYSOyP6o0noD5rPtPo,110665 +olmo_data/oe_eval_tasks/arc_challenge/rc_5shot/config.json,sha256=wxtcq3TNQWIOzCacdNNnGys4nuZ1pB0EfGiIN1-UwU4,662 +olmo_data/oe_eval_tasks/arc_challenge/rc_5shot/requests.jsonl.gz,sha256=4em2bj_6nv3dPPev1CJG0MwnGiayWees4tJlnqamO10,118564 +olmo_data/oe_eval_tasks/arc_challenge/test_mc_5shot/config.json,sha256=LlZtkS9uZKQXJTbY1As5wD__A_bTAPAchLEHP1X-0Hg,689 +olmo_data/oe_eval_tasks/arc_challenge/test_mc_5shot/requests.jsonl.gz,sha256=YBXSoElH3SRyWcMFK3H8jJBMlRYNdGUFo5rN-8oKpUQ,265953 +olmo_data/oe_eval_tasks/arc_challenge/test_rc_5shot/config.json,sha256=6iQmegJlN9A7BjshGGvk1BwODa983BCVf2OqQ2nSn7s,718 +olmo_data/oe_eval_tasks/arc_challenge/test_rc_5shot/requests.jsonl.gz,sha256=mOAB3_5fyPo7bhW7ypax16VeWnl8Ev8QwY7VdNVL-lc,460134 +olmo_data/oe_eval_tasks/arc_challenge/train_mc_5shot/config.json,sha256=iOWmzqxSQX2PPz3QPz3IGT9EFGUZ3OQNnrkhpKmpN6U,690 +olmo_data/oe_eval_tasks/arc_challenge/train_mc_5shot/requests.jsonl.gz,sha256=i71x6-_rpgij2GgZeFpnF9vlodY8OY_E9ezwfua39Ng,249155 +olmo_data/oe_eval_tasks/arc_challenge/train_rc_5shot/config.json,sha256=kc5YRKkxI6KOIPjXbZt5I-TbP3yFckuvp3JjyZ5ZO1A,719 +olmo_data/oe_eval_tasks/arc_challenge/train_rc_5shot/requests.jsonl.gz,sha256=XklGaq10EMGtxLVkWiFNS9lN5F2cc5mi3YXqsQmMRBU,430852 +olmo_data/oe_eval_tasks/arc_challenge/val_mc_5shot/config.json,sha256=EI3n3IeRLiC0tIsikG79v27-gKjWj0P07utuYNjA8V4,694 +olmo_data/oe_eval_tasks/arc_challenge/val_mc_5shot/requests.jsonl.gz,sha256=Ldx-5PHOXi90roftFLa6QNeVgUCPF7dVWP_Alg28O-c,68475 +olmo_data/oe_eval_tasks/arc_challenge/val_rc_5shot/config.json,sha256=8umJ42KV3nLRjQfpp4oe4NUC8jPr-EKJaUo8xeaZP-8,723 +olmo_data/oe_eval_tasks/arc_challenge/val_rc_5shot/requests.jsonl.gz,sha256=_KzkmTzZ_1zZN0FKABooM42mmq1DBF8oKtut1jOp-Qc,118667 +olmo_data/oe_eval_tasks/arc_easy/mc_5shot/config.json,sha256=Kyc6GPawbMqTILOo4-5C6ECOK-GVqj5MM4vwQmZHd7s,667 +olmo_data/oe_eval_tasks/arc_easy/mc_5shot/requests.jsonl.gz,sha256=oEDvvlMsLbLnEnxpeLjuHbOmKdVm4Qg1hQv-WxFuEl0,114395 +olmo_data/oe_eval_tasks/arc_easy/rc_0shot/config.json,sha256=_mW3tWISjqaNUuTsko39TDFQlR5-IzVCHUr3p-1-qTs,538 +olmo_data/oe_eval_tasks/arc_easy/rc_0shot/requests.jsonl.gz,sha256=HhqthR8k4KVHhA-TLYE8M4DK-nfFySppl6IVECSoVzw,189219 +olmo_data/oe_eval_tasks/arc_easy/rc_5shot/config.json,sha256=dLn0m98FRxwx1tV_ZiR7tfQ8Az2Uv68lQ0qSx1KLKIM,710 +olmo_data/oe_eval_tasks/arc_easy/rc_5shot/requests.jsonl.gz,sha256=8UOpkur-oXFacWkLlNpgN6CdqopaEshKbP1S_yt5Hhc,202443 +olmo_data/oe_eval_tasks/arc_easy/test_mc_5shot/config.json,sha256=9kMexwWWX-cGzM3MT-leFwXQfBiQJM7hRLFRQzGzC-0,708 +olmo_data/oe_eval_tasks/arc_easy/test_mc_5shot/requests.jsonl.gz,sha256=wxK6xQf8HugmUX-6Uw-4hnKqcLssf4lXOGwkjm3ya7E,473937 +olmo_data/oe_eval_tasks/arc_easy/test_rc_5shot/config.json,sha256=rYOQg4ceouMuJWiWo5ouV0XRYJjLhP6mmquyKwGVJo4,756 +olmo_data/oe_eval_tasks/arc_easy/test_rc_5shot/requests.jsonl.gz,sha256=yWSIHSuyro2WEsge1sWuzEAqox5Jivh_Yb3lA8yCJNw,838922 +olmo_data/oe_eval_tasks/arc_easy/train_mc_5shot/config.json,sha256=Q2szCk8F-r6SVkZ2t_RDFIgrb5bljKUbm7-OuFOargU,709 +olmo_data/oe_eval_tasks/arc_easy/train_mc_5shot/requests.jsonl.gz,sha256=qyyPnftqmxRZBxbIaR1weAnUqyRENsKUaj4AG2jzR-U,447636 +olmo_data/oe_eval_tasks/arc_easy/train_rc_5shot/config.json,sha256=F3dd82w2n5R5NLjAGRZmSauMEArBqFtyH6wJ_2Dcj3Q,757 +olmo_data/oe_eval_tasks/arc_easy/train_rc_5shot/requests.jsonl.gz,sha256=V8PkeCQyeMcWSy8uvvrddvgaWulc6m0-c247OJIgH5U,792763 +olmo_data/oe_eval_tasks/arc_easy/val_mc_5shot/config.json,sha256=CEgPNm226vxmMim5TgBzCewUdw6qqOITF3ndhiyHv-c,713 +olmo_data/oe_eval_tasks/arc_easy/val_mc_5shot/requests.jsonl.gz,sha256=LZ7XuWwDo6zJTqhgpZgHNj6yi-xOXb-TQxl9yxB9gVg,114271 +olmo_data/oe_eval_tasks/arc_easy/val_rc_5shot/config.json,sha256=LeNP534voujfcp9ph8SKHfnfYPjfSu8ik3HWiXt3TFM,761 +olmo_data/oe_eval_tasks/arc_easy/val_rc_5shot/requests.jsonl.gz,sha256=28UmHQnAB2DIlfYbqhuhJ4AjAVLDAHWWoEmaHlI-UKU,202290 +olmo_data/oe_eval_tasks/boolq/mc_5shot/config.json,sha256=87GTyDGser1tWfSWmktZ1X17jKXU1EZzHOJLMSbVspA,632 +olmo_data/oe_eval_tasks/boolq/mc_5shot/requests.jsonl.gz,sha256=uZ9ZkbFkiUn4XcCzypgPscTFTrVDexVC1L-e6zBiEMg,393249 +olmo_data/oe_eval_tasks/boolq/rc_0shot/config.json,sha256=d1GKQMIX1cUgnZHlUe9kgAZsgkMc1N2GnMlyhccO9pE,509 +olmo_data/oe_eval_tasks/boolq/rc_0shot/requests.jsonl.gz,sha256=CYS27HFoIqomrWcj5Jii8gy-BRCtj-oxZhVi2ZEnVLk,1096744 +olmo_data/oe_eval_tasks/boolq/rc_5shot/config.json,sha256=iAD8DDqUcX7crb3ocz_uyGADXbBJAs-QB419j-bRF50,626 +olmo_data/oe_eval_tasks/boolq/rc_5shot/requests.jsonl.gz,sha256=8s8_NHsF_LS-WOt3DgOQKuzP8N5LFZHOYRzYZquqxy8,397146 +olmo_data/oe_eval_tasks/boolq/train_mc_5shot/config.json,sha256=OI3aoNIbUKs5w2X0kFRZcwzc_0MmOjpSYuk5KnDyIRo,673 +olmo_data/oe_eval_tasks/boolq/train_mc_5shot/requests.jsonl.gz,sha256=XL1EoKV4-jyHKqmS2bblcH2rSGrnmhVBGiTrCoOyb0I,3709857 +olmo_data/oe_eval_tasks/boolq/train_rc_5shot/config.json,sha256=hwQ-Cwq7K_iwDhnztXkDff0p4TrBwSA2J-ExWvuoj9A,667 +olmo_data/oe_eval_tasks/boolq/train_rc_5shot/requests.jsonl.gz,sha256=mZ-F9m9mZjrx0BiSECaCYygJ4QpGtN70tgCAh9xwXWA,3734933 +olmo_data/oe_eval_tasks/boolq/val_mc_5shot/config.json,sha256=06ZAVLO1Bd7w-uoD24reO4h5gEzbyGvxjfiUkIODOag,678 +olmo_data/oe_eval_tasks/boolq/val_mc_5shot/requests.jsonl.gz,sha256=Uo8vJC827Ky4J27uR5ujgF6WyS8O9SCcATtjnZcPMYE,1274284 +olmo_data/oe_eval_tasks/boolq/val_rc_5shot/config.json,sha256=eR9oyZMCIckUVP9FoQiTLvkk4gYX4sVrvJO3IMZtpWk,672 +olmo_data/oe_eval_tasks/boolq/val_rc_5shot/requests.jsonl.gz,sha256=1e0uURX0nSTDfsF_t7Sm7GvFjGXOFUEL7StANC8I-8k,1282935 +olmo_data/oe_eval_tasks/copa/rc_0shot/config.json,sha256=dkNiFgoOz56d8IPeQkJTQlR6rJbO2Iogdp1wHKp5ztw,531 +olmo_data/oe_eval_tasks/copa/rc_0shot/requests.jsonl.gz,sha256=4XnXOK5tIEN-XBUQmQ9TAffnp1TfgwJFYpKZo9-6CFE,18841 +olmo_data/oe_eval_tasks/copycolors/10way/config.json,sha256=LcKu28kWu9TphtNk5BJXo44z1deqUZ0boK_lt-F0Ils,1064 +olmo_data/oe_eval_tasks/copycolors/10way/requests.jsonl.gz,sha256=SW9yN6kXnM5Dp5vti7DB9EDaIOM_v01Y2kng4Fb6hog,16922 +olmo_data/oe_eval_tasks/copycolors/xl_10way/config.json,sha256=zElN4wQjKjYlFO2hw-FGmhqi8sfXNgipbjToPjAD62o,1075 +olmo_data/oe_eval_tasks/copycolors/xl_10way/requests.jsonl.gz,sha256=O0eLjaTaqxwQsQNauzqfTAUQqT6JGy9EDTPGJUICeKw,148731 +olmo_data/oe_eval_tasks/csqa/mc_5shot/config.json,sha256=eQZuPWzARbEdcX1Rwqrg2Bu6X9pjMm4dwkBxye84wsg,595 +olmo_data/oe_eval_tasks/csqa/mc_5shot/requests.jsonl.gz,sha256=JLTht4aPQUsKRMpMdRC-at4mEHiGDVAlW1XJzfHs4Bk,223765 +olmo_data/oe_eval_tasks/csqa/rc_0shot/config.json,sha256=6Ot0pSZaS7C9imHjCTJb9Z2zCi7MNoeHTb2x3bRV0jU,514 +olmo_data/oe_eval_tasks/csqa/rc_0shot/requests.jsonl.gz,sha256=iDIdfnW51OafGFOHMje5dmpMgHFTQduw4okFvpUCUI4,383331 +olmo_data/oe_eval_tasks/csqa/rc_5shot/config.json,sha256=q__C82RMl820wUqB6mBO9v29hVsfJizUhR3oXH2EU0A,624 +olmo_data/oe_eval_tasks/csqa/rc_5shot/requests.jsonl.gz,sha256=3t5HYgR4Ljg1kf95IpVfDOmU2y4H4I50AN9mdXEDaGc,405977 +olmo_data/oe_eval_tasks/csqa/train_mc_5shot/config.json,sha256=7tWmCtq1W9Vr-v8pKfghswjASP4qo0To77yBGXzfVcY,651 +olmo_data/oe_eval_tasks/csqa/train_mc_5shot/requests.jsonl.gz,sha256=z8Wqd5jfUVNpxCjm378ZHXf1Aq7riB6QvRZmwKit87M,1806374 +olmo_data/oe_eval_tasks/csqa/train_rc_5shot/config.json,sha256=7O1YtPeMFVNavteM1MDuK90qh-VuSkmZrDM0FD5MGrs,680 +olmo_data/oe_eval_tasks/csqa/train_rc_5shot/requests.jsonl.gz,sha256=GgOoNPHFd8KZvPun2kL-ty3l73YDGXwyYYq2dVZ94xM,3283241 +olmo_data/oe_eval_tasks/csqa/val_mc_5shot/config.json,sha256=2HC25HJP_9HkP6Q8rckieQehct0U6h5yx4oRxi3yw5Y,656 +olmo_data/oe_eval_tasks/csqa/val_mc_5shot/requests.jsonl.gz,sha256=Yp3imWdQnnDq5sbjSVmhVbX4mAGT-7lrHPfn-EzSmhU,225104 +olmo_data/oe_eval_tasks/csqa/val_rc_5shot/config.json,sha256=dDOgeHoYRttEjWa1GxsiFfPq7O4elNJAs7ppCHkGjHM,685 +olmo_data/oe_eval_tasks/csqa/val_rc_5shot/requests.jsonl.gz,sha256=kPbc937b5gJ1Ax3t-wMQ5HK-2fK0zUOTxNxRWBDRuj8,408334 +olmo_data/oe_eval_tasks/gsm8k/gold_bpb_5shot/config.json,sha256=lsvfA84diCAUUB4n_jjCAOy0JkJqA2DNXI9vmHmW0Cs,838 +olmo_data/oe_eval_tasks/gsm8k/gold_bpb_5shot/requests.jsonl.gz,sha256=3-lMQnIGFYQiWQNrwsdT94yqLpDNrZzMydo7c-ZtcBI,434682 +olmo_data/oe_eval_tasks/hellaswag/mc_5shot/config.json,sha256=HWqNAgD630Uiyp9iSSq7llvgIseaw2BV6zMIJdiS1LA,621 +olmo_data/oe_eval_tasks/hellaswag/mc_5shot/requests.jsonl.gz,sha256=WCOAxvlldjXrOfEom6CC5HBGZqKSGlwPi7dN7wXNCL4,550547 +olmo_data/oe_eval_tasks/hellaswag/rc_0shot/config.json,sha256=ewFxgEPrKDNtRWbXNrnIZakQT1U4AE5099dp-3IaTZU,526 +olmo_data/oe_eval_tasks/hellaswag/rc_0shot/requests.jsonl.gz,sha256=vwqwi_-FKW6kjZ__Hd0S6cFKGhETZ-avDwjAg7w_UC8,8213204 +olmo_data/oe_eval_tasks/hellaswag/rc_5shot/config.json,sha256=0N2lWWKEh46xNB_KVP1OOJj2PvP-k8lnB5FOsxtSBeI,650 +olmo_data/oe_eval_tasks/hellaswag/rc_5shot/requests.jsonl.gz,sha256=VtVrRx4fvLm477eWcqw4IEG0agtpQlok0jQ53i30vvA,922524 +olmo_data/oe_eval_tasks/hellaswag/train_mc_5shot/config.json,sha256=KFr8Swjt2qamkvm3YhbypWgTPyGS6mUUhKg2EDzdKAA,663 +olmo_data/oe_eval_tasks/hellaswag/train_mc_5shot/requests.jsonl.gz,sha256=nkwyOF9BQmfus9RM05c47fJGFuL-U3WxTp_--JL2eek,20530884 +olmo_data/oe_eval_tasks/hellaswag/train_rc_5shot/config.json,sha256=diMZYyKkY0ZW1X3YwceF7pFW1PqfX2V5bsZb1RGsp-s,692 +olmo_data/oe_eval_tasks/hellaswag/train_rc_5shot/requests.jsonl.gz,sha256=io0_hCi_aDE4YILb9dKpTUy8WzA6YV1y3XJhDcpb_PQ,33702436 +olmo_data/oe_eval_tasks/hellaswag/val_mc_5shot/config.json,sha256=DaDjfSSvXBE0Nk77wWCaSEvqjdo7ThmTxGzE7MzxHjg,668 +olmo_data/oe_eval_tasks/hellaswag/val_mc_5shot/requests.jsonl.gz,sha256=XNpBEoMjg397dEuapS9r3UxOOPQAxmVUrYM92YBxzDs,5298017 +olmo_data/oe_eval_tasks/hellaswag/val_rc_5shot/config.json,sha256=5QzTjpfq260Gn-uudEcnwtNQhu5cgXDppDb4xwVKaXg,697 +olmo_data/oe_eval_tasks/hellaswag/val_rc_5shot/requests.jsonl.gz,sha256=eqT2QbCuP_dnNHVI-QLSl7GANmSJ97vc6cW6CNaxpOk,8715020 +olmo_data/oe_eval_tasks/openbookqa/mc_5shot/config.json,sha256=RfZ4pfvROPvMIMmVhlr_3xWGLz5mVOqsdWCHTdu1eIY,612 +olmo_data/oe_eval_tasks/openbookqa/mc_5shot/requests.jsonl.gz,sha256=oQ4gkIyQ5ZkZa-ceBvETqlrRs8GJCgsn6djAV6ubFgU,75731 +olmo_data/oe_eval_tasks/openbookqa/rc_0shot/config.json,sha256=bOBTOqksTpGGJYJ2419HJxd__pbOpetokEJBzN6yRKw,547 +olmo_data/oe_eval_tasks/openbookqa/rc_0shot/requests.jsonl.gz,sha256=PuZsSlZxQCZ8VhBxPe1L-xUFoP4nueCadCElpF0PH6Y,129666 +olmo_data/oe_eval_tasks/openbookqa/rc_5shot/config.json,sha256=ZSVH4h5BMtW1pnHFXW5KvUV5hrNnXThv_JFO9F0pN_A,659 +olmo_data/oe_eval_tasks/openbookqa/rc_5shot/requests.jsonl.gz,sha256=94Ymg3l-kdKmCt7b_DUDhTudHKPDiVUnIWyKuMWIJqM,136128 +olmo_data/oe_eval_tasks/openbookqa/test_mc_5shot/config.json,sha256=M2f8L-l77V7mivb5gyRo2OPQMuzA3OoB0pJ9aGPp-RE,667 +olmo_data/oe_eval_tasks/openbookqa/test_mc_5shot/requests.jsonl.gz,sha256=aN3OzIMf65S3H_M5DVHYCogdnuMV_ZlFLA5ppPrh3EA,73642 +olmo_data/oe_eval_tasks/openbookqa/test_rc_5shot/config.json,sha256=MW8I3SRRLfpFu_Qd0oCpSKB19IjBSjRjfCF3nEIUiEU,714 +olmo_data/oe_eval_tasks/openbookqa/test_rc_5shot/requests.jsonl.gz,sha256=QVnckfFUkzoHePtVIJl8wsUxT6fwFMUn86VuSlhEvRU,133010 +olmo_data/oe_eval_tasks/openbookqa/train_mc_5shot/config.json,sha256=ufQ7l4gWctquMFl-M7oIZQqfxdjIDxZwT-eFRyNiyGk,669 +olmo_data/oe_eval_tasks/openbookqa/train_mc_5shot/requests.jsonl.gz,sha256=5kryqqsnYGCMuKD3nu-DN0xdGPAnvhfNtPMM6ymLGyY,696932 +olmo_data/oe_eval_tasks/openbookqa/train_rc_5shot/config.json,sha256=5weBwXF6r3W8DJ-9u4Q21ZR6tUpeBTQmrZU9xtVihGQ,716 +olmo_data/oe_eval_tasks/openbookqa/train_rc_5shot/requests.jsonl.gz,sha256=zqdt3oT1ptFID-SJR6zVOCb45OstW6uMGAcd1q9FlQU,1263062 +olmo_data/oe_eval_tasks/openbookqa/val_mc_5shot/config.json,sha256=1q6nH0O_yfgWvHMNv9aQNHt-b2yThlXSBH6GboQYj-s,673 +olmo_data/oe_eval_tasks/openbookqa/val_mc_5shot/requests.jsonl.gz,sha256=Oi5j1fl0Lr6aq9j_m4LaxvL0s6TvbOxbYp3ccUAhZ28,75683 +olmo_data/oe_eval_tasks/openbookqa/val_rc_5shot/config.json,sha256=WdLRZBm5Z0GboCzIJIl2S5Vr3EFTKw8bdjuku5uMZZI,720 +olmo_data/oe_eval_tasks/openbookqa/val_rc_5shot/requests.jsonl.gz,sha256=jQ4Fjc9Lge6BFSv8Yhcp8j_77_jqVqVEZJs5a85wMJw,136460 +olmo_data/oe_eval_tasks/piqa/mc_5shot/config.json,sha256=4Ijh7m36TpOak7hrk7yzE3uuEWpS-Irr_V902REAtnQ,593 +olmo_data/oe_eval_tasks/piqa/mc_5shot/requests.jsonl.gz,sha256=0D4aUwIxTwvcST5V1MjxZbfSa3SQe1akHmM_yYs_4lY,161890 +olmo_data/oe_eval_tasks/piqa/rc_0shot/config.json,sha256=IqEyMBPG3zCM5vRpg2hT-xr3QmpSfNWmW-lvHEhqAn0,507 +olmo_data/oe_eval_tasks/piqa/rc_0shot/requests.jsonl.gz,sha256=jIeNgby5URbONexjTmVLegAK5JJOBXyw8CBaadzihxQ,510517 +olmo_data/oe_eval_tasks/piqa/rc_5shot/config.json,sha256=mU7fcwsiEeEcZIV_FYQ0LFdTXS5gJSOEK96BiNRVrhg,622 +olmo_data/oe_eval_tasks/piqa/rc_5shot/requests.jsonl.gz,sha256=REGt8DLLa6xZTY7zFsHRaePyL3zPq6pyjIUjeXx-mqs,294074 +olmo_data/oe_eval_tasks/piqa/train_mc_5shot/config.json,sha256=_IQers9u363MC-knrU0NzsU4Wg42i2QD2irW2BFdeK0,635 +olmo_data/oe_eval_tasks/piqa/train_mc_5shot/requests.jsonl.gz,sha256=4FTnpzdstjqozftJZDWdRgADEll7H69UaPVkOIZ6zGA,2528246 +olmo_data/oe_eval_tasks/piqa/train_rc_5shot/config.json,sha256=sVpbwpR_VC_XJCKAcZI1fGBtfEEktO1mp8-pnaLfyNo,664 +olmo_data/oe_eval_tasks/piqa/train_rc_5shot/requests.jsonl.gz,sha256=rWmp1hpHxYhucfkWFggjuADiU4yxfEnYYuMBZ5oADgA,4624806 +olmo_data/oe_eval_tasks/piqa/val_mc_5shot/config.json,sha256=5VTIDOgBisXT_aXGirCeeY6AJxggR0V0y0w2DSHYDJc,639 +olmo_data/oe_eval_tasks/piqa/val_mc_5shot/requests.jsonl.gz,sha256=g4pKwXIOS095bc9nO_QvFLZf62RTYzKR8f-naIy-zMc,289245 +olmo_data/oe_eval_tasks/piqa/val_rc_5shot/config.json,sha256=jjEApPiEgko-N2_vrHW_qG9V9my6CGJ2eCSR13X5oIc,668 +olmo_data/oe_eval_tasks/piqa/val_rc_5shot/requests.jsonl.gz,sha256=vQFe_zcqmo7BklH-ZpBV-Rml7C5JAXf2ACvHd_O_ts4,528757 +olmo_data/oe_eval_tasks/sciq/rc_0shot/config.json,sha256=IbjkC4mLmV306367REX5HrxHL1vvGlTqlsJqD2s6aBU,526 +olmo_data/oe_eval_tasks/sciq/rc_0shot/requests.jsonl.gz,sha256=zA0_Cg8kGfW3VT98mktZ1ard0o4xWlJm0k_R7ux7Brs,711941 +olmo_data/oe_eval_tasks/socialiqa/mc_5shot/config.json,sha256=RD8wo4wV6IiRwRdcN6jazoz5TLU0lxGzcL2oO5lrqKc,627 +olmo_data/oe_eval_tasks/socialiqa/mc_5shot/requests.jsonl.gz,sha256=hVzSXBiePoLsIGSw80VTb2gbezPF9WFINLq4IlM_arI,175627 +olmo_data/oe_eval_tasks/socialiqa/rc_0shot/config.json,sha256=OI2eGlrB2dEpDdsRTAX4CXaM_8WtbJWSyzXp4P6aTxA,529 +olmo_data/oe_eval_tasks/socialiqa/rc_0shot/requests.jsonl.gz,sha256=vt0VTBV0Y3t6i1s-CeEOh42ZhVSm9hOvgo6PQ6drlXY,582369 +olmo_data/oe_eval_tasks/socialiqa/rc_5shot/config.json,sha256=qAVLfukX5RAQhIjL-tJWC07u7PRbgoWGykdHTi16_aE,656 +olmo_data/oe_eval_tasks/socialiqa/rc_5shot/requests.jsonl.gz,sha256=QcBmb18slLzrR7Ch_1GWRVs7B-PCv1KmAOEQaPgKO84,318902 +olmo_data/oe_eval_tasks/socialiqa/train_mc_5shot/config.json,sha256=Ci8a7YppaplI7D3mpr-zAsV-KZDisplFaaOfWF8TRok,669 +olmo_data/oe_eval_tasks/socialiqa/train_mc_5shot/requests.jsonl.gz,sha256=WCFYnDl7aNxzZCMAeRa6667_ZXxIIy4A_zp_jalelS8,5758466 +olmo_data/oe_eval_tasks/socialiqa/train_rc_5shot/config.json,sha256=Yj2DUpyMpzPFeUVvFa-1HmuLXY_xYhZY2FFsGkCjCUc,698 +olmo_data/oe_eval_tasks/socialiqa/train_rc_5shot/requests.jsonl.gz,sha256=RWVLhmRAn7nZnKCpevI9QgV5VqDtrm0GpTyMiYDs3Vc,10493303 +olmo_data/oe_eval_tasks/socialiqa/val_mc_5shot/config.json,sha256=G_qKgjkad1K5VMxTA7IG6OFra-Yk_wvjuBIUhm75apE,673 +olmo_data/oe_eval_tasks/socialiqa/val_mc_5shot/requests.jsonl.gz,sha256=5Cg14CQILNBmkP4sC2ZDLozbW5PnjKSGkOzcgyGiFVs,339213 +olmo_data/oe_eval_tasks/socialiqa/val_rc_5shot/config.json,sha256=boygFc6tbDZT6tAH0ha-nCpkSrVdq67iWXTeZ4j0H6k,702 +olmo_data/oe_eval_tasks/socialiqa/val_rc_5shot/requests.jsonl.gz,sha256=rFvYri5Cki3703UX_a-noiXyVSf4dLcC8uoaDH4lcnA,617709 +olmo_data/oe_eval_tasks/winogrande/mc_5shot/config.json,sha256=q9cUsjPl0RtXC3EKCYmp4PUFLQT1APM3iYJ2ypMGSqg,625 +olmo_data/oe_eval_tasks/winogrande/mc_5shot/requests.jsonl.gz,sha256=VJFO0g_LZLX7wtDJO9lfi3bgD2CIqsY2SoLlSCk_1yw,137204 +olmo_data/oe_eval_tasks/winogrande/rc_0shot/config.json,sha256=Q-L4r0GNkSAHcV0ELfD4TfvV3_-QQL-aw-Zdr1xG9pQ,504 +olmo_data/oe_eval_tasks/winogrande/rc_0shot/requests.jsonl.gz,sha256=tsUwiN218eRT918vIDXrqQos0VvSrVc8e8rIyN1buEY,102498 +olmo_data/oe_eval_tasks/winogrande/rc_5shot/config.json,sha256=tluGyhzjZTY-cqyGRS46OQvSbUns9xzns-E50cAjkxs,616 +olmo_data/oe_eval_tasks/winogrande/rc_5shot/requests.jsonl.gz,sha256=djjr6I7ibK9b9Zqutm_lzzwt-yupf1W5MDItVOfJi6Q,115364 +olmo_data/oe_eval_tasks/winogrande/train_mc_5shot/config.json,sha256=JAL8jBc6GvJ2vZfVriGKQTb9Zf6oCnKDyiyp91bGGXg,682 +olmo_data/oe_eval_tasks/winogrande/train_mc_5shot/requests.jsonl.gz,sha256=6FTzFzX5Kc8ho1ZTifQkBlI9Fy-j0vDVWUsK1VDCr8Y,3644078 +olmo_data/oe_eval_tasks/winogrande/train_rc_5shot/config.json,sha256=Aqffo_HoANPX304xa64TRObtzs-EkcqoJFNSri6mC3E,673 +olmo_data/oe_eval_tasks/winogrande/train_rc_5shot/requests.jsonl.gz,sha256=6jq_4wWz7IkpqcAoPCI7Bl6GGqTfQIUiCy7kW4YkltM,2970627 +olmo_data/oe_eval_tasks/winogrande/val_mc_5shot/config.json,sha256=2L_4fgE58k_VqCdq22tAiW_m9vI-21RA30ge4Xqs7_Y,686 +olmo_data/oe_eval_tasks/winogrande/val_mc_5shot/requests.jsonl.gz,sha256=jDFf1gIBcyFGIcwCInFUXD35Qlep5UHEWVHDgDVjTs8,137080 +olmo_data/oe_eval_tasks/winogrande/val_rc_5shot/config.json,sha256=ySjEVqTOj5GwC78Y1E4AaKhSoJCD47pfyZLRyDsSwa8,677 +olmo_data/oe_eval_tasks/winogrande/val_rc_5shot/requests.jsonl.gz,sha256=knTzcqigWCfdYLN1Pl0TfCm0Fi1lRASWAo_SC6KtXsc,115262 +olmo_data/tokenizers/allenai_dolma2.json,sha256=PKmWzKiv6lizTpXDU-hZMzWSZCpeUdaV16bbuvaS3-k,2733190 +olmo_data/tokenizers/allenai_eleuther-ai-gpt-neox-20b-pii-special.json,sha256=yjXYcnpTO7Zjm_R4Gucrn9oA5paadiYM-ZZER5q_EXc,2114319 +olmo_data/tokenizers/allenai_gpt-neox-olmo-dolma-v1_5.json,sha256=mtM7Szmp-Dlzw_jEKgGUjdW4d6KKyaU1aVbE_07QtxQ,2115113 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo-0.6.0.dist-info/WHEEL b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo-0.6.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..14a883f292bc96b20c2b76a3081991f2676523a9 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo-0.6.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (82.0.1) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo-0.6.0.dist-info/direct_url.json b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo-0.6.0.dist-info/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..e152b93e7060f0a902b1f9289417c5ce58ea8b96 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo-0.6.0.dist-info/direct_url.json @@ -0,0 +1 @@ +{"url": "https://github.com/allenai/OLMo.git", "vcs_info": {"commit_id": "090253dac6688f2532509daa7aa2eb5fae50e956", "requested_revision": "main", "vcs": "git"}} \ No newline at end of file diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo-0.6.0.dist-info/top_level.txt b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo-0.6.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..1218f536984623cd82c36f81b9b7daf82035bef3 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo-0.6.0.dist-info/top_level.txt @@ -0,0 +1,3 @@ +hf_olmo +olmo +olmo_data diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo_core-2.4.0.dist-info/INSTALLER b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo_core-2.4.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo_core-2.4.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo_core-2.4.0.dist-info/METADATA b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo_core-2.4.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..e246d5c4e819bd5ce57e85c01676b32234033e0f --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo_core-2.4.0.dist-info/METADATA @@ -0,0 +1,450 @@ +Metadata-Version: 2.4 +Name: ai2-olmo-core +Version: 2.4.0 +Summary: Core training module for the Open Language Model (OLMo) +Author-email: Allen Institute for Artificial Intelligence +License: Apache License + Version 2.0, January 2004 + https://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 + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +Project-URL: Homepage, https://github.com/allenai/OLMo-core +Project-URL: Documentation, https://olmo-core.readthedocs.io/en/latest/ +Project-URL: Changelog, https://github.com/allenai/OLMo-core/blob/main/CHANGELOG.md +Requires-Python: >=3.10 +Description-Content-Type: text/markdown +License-File: LICENSE +Requires-Dist: numpy +Requires-Dist: torch>=2.6.0 +Requires-Dist: cached-path>=1.7.2 +Requires-Dist: requests +Requires-Dist: packaging +Requires-Dist: rich +Requires-Dist: omegaconf +Requires-Dist: safetensors +Requires-Dist: importlib_resources +Requires-Dist: bettermap +Provides-Extra: dev +Requires-Dist: black<24.0,>=23.1; extra == "dev" +Requires-Dist: boto3; extra == "dev" +Requires-Dist: build; extra == "dev" +Requires-Dist: furo==2024.8.6; extra == "dev" +Requires-Dist: google-cloud-storage; extra == "dev" +Requires-Dist: isort<5.14,>=5.12; extra == "dev" +Requires-Dist: mypy<1.4,>=1.0; extra == "dev" +Requires-Dist: myst-parser<3.0,>=1.0; extra == "dev" +Requires-Dist: pytest; extra == "dev" +Requires-Dist: pytest-memray; extra == "dev" +Requires-Dist: pytest-sphinx; extra == "dev" +Requires-Dist: pytest-xdist; extra == "dev" +Requires-Dist: ruff; extra == "dev" +Requires-Dist: setuptools; extra == "dev" +Requires-Dist: Sphinx<=8.1.3,>=6.0; extra == "dev" +Requires-Dist: sphinx-autobuild; extra == "dev" +Requires-Dist: sphinx-autodoc-typehints==1.23.3; extra == "dev" +Requires-Dist: sphinx-copybutton; extra == "dev" +Requires-Dist: sphinx-inline-tabs; extra == "dev" +Requires-Dist: twine>=1.11.0; extra == "dev" +Requires-Dist: wheel; extra == "dev" +Provides-Extra: beaker +Requires-Dist: beaker-py<2.0,>=1.37.0; extra == "beaker" +Requires-Dist: GitPython<4.0,>=3.0; extra == "beaker" +Requires-Dist: google-cloud-compute; extra == "beaker" +Provides-Extra: comet +Requires-Dist: comet_ml; extra == "comet" +Provides-Extra: eval +Requires-Dist: ai2-olmo-eval==0.8.5; extra == "eval" +Provides-Extra: torchao +Requires-Dist: torchao; extra == "torchao" +Provides-Extra: transformers +Requires-Dist: transformers; extra == "transformers" +Provides-Extra: wandb +Requires-Dist: wandb; extra == "wandb" +Provides-Extra: all +Requires-Dist: ai2-olmo-core[beaker,comet,dev,eval,torchao,transformers,wandb]; extra == "all" +Dynamic: license-file + +
+ + OLMo Logo +
+

OLMo-core

+

Building blocks for OLMo modeling and training

+
+

+ + Docs + + + Examples + + + Pypi + + + GitHub License + + + Paper URL + + + Playground + + + Discord + +

+ +## Installation + +First install [PyTorch](https://pytorch.org) according to the instructions specific to your operating system and hardware. + +For development, we recommend installing from source: + +```bash +git clone https://github.com/allenai/OLMo-core.git +cd OLMo-core +pip install -e .[all] +``` +Or you can install from PyPI with: + +```bash +pip install ai2-olmo-core +``` + +There are a number of optional dependencies that must be installed to use certain functionality as well, including: + +- [flash-attn](https://github.com/Dao-AILab/flash-attention), [ring-flash-attn](https://github.com/zhuzilin/ring-flash-attention), and [TransformerEngine](https://github.com/NVIDIA/TransformerEngine) for the corresponding attention backends. +- [Liger-Kernel](https://github.com/linkedin/Liger-Kernel) for a low-memory "fused-linear" loss implementation. +- [torchao](https://github.com/pytorch/ao) for float8 training. +- [grouped_gemm](https://github.com/tgale96/grouped_gemm) for dropless mixture-of-experts (MoE) models. You may need to compile from source until [PR #21](https://github.com/tgale96/grouped_gemm/pull/21) is released (post v0.1.6). + +The published [Docker images](https://github.com/orgs/allenai/packages?repo_name=OLMo-core) contain all core and optional dependencies, and are regularly tested on our in-house H100 clusters. +But there are several things to keep in mind if you intend to use these images: + +- They do not come with the OLMo-core package installed, only its dependencies, to accommodate for regular code changes. +- They may not work on your own cluster if you have different hardware or driver/CUDA versions. + +If the published images do not work for your use-case for any of the above reasons, you could adapt our [Dockerfile](https://github.com/allenai/OLMo-core/blob/main/src/Dockerfile) to build your own images. + +## Official training scripts + +Official training scripts for released models can be found in [`src/scripts/official/`](https://github.com/allenai/OLMo-core/tree/main/src/scripts/official). + +These scripts are meant to be launched with ``torchrun``, or with OLMo-core's Beaker launch CLI if you have access to Beaker. + +For example: + +```bash +torchrun --nproc-per-node=8 src/scripts/official/OLMo2/OLMo-2-0325-32B-train.py \ + --save-folder=/path/to/save/checkpoints +``` + +You can override most configuration options from the command-line. For example, to override the learning rate you could launch the script like this: + +```bash +torchrun --nproc-per-node=8 src/scripts/official/OLMo2/OLMo-2-0325-32B-train.py \ + --save-folder=/path/to/save/checkpoints \ + --train_module.optim.lr=6e-3 +``` + +To continue annealing from a checkpoint, we use a separate script which can be launched like this: + +```bash +torchrun --nproc-per-node=8 src/scripts/official/OLMo2/OLMo-2-0325-32B-anneal.py \ + --save-folder=/path/to/save/checkpoints \ + --checkpoint=https://olmo-checkpoints.org/ai2-llm/peteish32/step721901 +``` + +### Available Training Scripts + +| Model Family | Directory | Description | +|--------------|-----------|-------------| +| **OLMo-2** | [`src/scripts/official/OLMo2/`](https://github.com/allenai/OLMo-core/tree/main/src/scripts/official/OLMo2) | Training scripts and model card for OLMo-2 32B models | +| **OLMo-3** | [`src/scripts/official/OLMo3/`](https://github.com/allenai/OLMo-core/tree/main/src/scripts/official/OLMo3) | Training scripts and model cards for OLMo-3 7B and 32B models | + +## Inference + +### With Hugging Face Transformers + +You can use our Hugging Face [transformers](https://github.com/huggingface/transformers) integration to run inference on the OLMo checkpoints: + +```bash +pip install transformers>=4.57.0 +``` + +```python +from transformers import AutoModelForCausalLM, AutoTokenizer +olmo = AutoModelForCausalLM.from_pretrained("allenai/Olmo-3-1125-32B") +tokenizer = AutoTokenizer.from_pretrained("allenai/Olmo-3-1125-32B") +message = ["Language modeling is "] +inputs = tokenizer(message, return_tensors='pt', return_token_type_ids=False) +# inputs = {k: v.to('cuda') for k,v in inputs.items()} # optional verifying cuda +# olmo = olmo.to('cuda') +response = olmo.generate(**inputs, max_new_tokens=100, do_sample=True, temperature=1.0, top_p=0.7) +print(tokenizer.batch_decode(response, skip_special_tokens=True)[0]) +``` + +Alternatively, with the Hugging Face pipeline abstraction: + +```python +from transformers import pipeline +olmo_pipe = pipeline("text-generation", model="allenai/Olmo-3-1125-32B") +print(olmo_pipe("Language modeling is")) +``` + +### With vLLM + +[vLLM](https://docs.vllm.ai/en/latest/) provides high-throughput inference for OLMo models. You can use it for offline batched inference: + +```bash +pip install vllm>=0.11.0 +``` + +```python +from vllm import LLM, SamplingParams +llm = LLM(model="allenai/Olmo-3-1125-32B") +sampling_params = SamplingParams(temperature=1.0, top_p=0.7) +prompts = ["Language modeling is"] +outputs = llm.generate(prompts, sampling_params) +for output in outputs: + prompt = output.prompt + generated_text = output.outputs[0].text + print(f"Prompt: {prompt!r}, Generated text: {generated_text!r}") +``` + +For more details, see the [vLLM documentation](https://docs.vllm.ai/en/latest/getting_started/quickstart/#offline-batched-inference). + +### With Olmo-core (beta) + +Autoregressive generation is supported directly in Olmo-core. Using this capability, we provide a chat-loop demo that can be used to interact with models in an interactive chat session: + +```bash +python -m olmo_core.generate.chat https://olmo-checkpoints.org/ai2-llm/Olmo-3-1025-7B/stage3/step11921/ --max-new-tokens 512 +``` + +## Evaluation + +Additional tools for evaluating OLMo models are available at the [OLMo Eval](https://github.com/allenai/OLMo-eval) and [olmes](https://github.com/allenai/olmes) repositories. + +## Development + +The Python library source code is located in `src/olmo_core`. The corresponding tests are located in `src/test`. The library docs are located in `docs`. You can build the docs locally with `make docs`. + +Code checks: + +- We use `pytest` to run tests. You can run all tests with `pytest -v src/test`. You can also point `pytest` at a specific test file to run it individually. +- We use `isort` and `black` for code formatting. Ideally you should integrate these into your editor, but you can also run them manually or configure them with a pre-commit hook. To validate that all files are formatted correctly, run `make style-check`. +- We use `ruff` as our primary linter. You can run it with `make lint-check`. +- We use `mypy` as our type checker. You can run it with `make type-check`. + +## Citing + +```bibtex +@misc{olmo20242olmo2furious, + title={{2 OLMo 2 Furious}}, + author={{Team OLMo} and Pete Walsh and Luca Soldaini and Dirk Groeneveld and Kyle Lo and Shane Arora and Akshita Bhagia and Yuling Gu and Shengyi Huang and Matt Jordan and Nathan Lambert and Dustin Schwenk and Oyvind Tafjord and Taira Anderson and David Atkinson and Faeze Brahman and Christopher Clark and Pradeep Dasigi and Nouha Dziri and Michal Guerquin and Hamish Ivison and Pang Wei Koh and Jiacheng Liu and Saumya Malik and William Merrill and Lester James V. Miranda and Jacob Morrison and Tyler Murray and Crystal Nam and Valentina Pyatkin and Aman Rangapur and Michael Schmitz and Sam Skjonsberg and David Wadden and Christopher Wilhelm and Michael Wilson and Luke Zettlemoyer and Ali Farhadi and Noah A. Smith and Hannaneh Hajishirzi}, + year={2024}, + eprint={2501.00656}, + archivePrefix={arXiv}, + primaryClass={cs.CL}, + url={https://arxiv.org/abs/2501.00656}, +} +``` diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo_core-2.4.0.dist-info/RECORD b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo_core-2.4.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..c2e88d58307510e82d892ffb56bd66ec83f406b0 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo_core-2.4.0.dist-info/RECORD @@ -0,0 +1,297 @@ +ai2_olmo_core-2.4.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +ai2_olmo_core-2.4.0.dist-info/METADATA,sha256=i79FLpuV65TpzWSuaTGLJhEo0PC35QRqX1B6eq7JMTI,24462 +ai2_olmo_core-2.4.0.dist-info/RECORD,, +ai2_olmo_core-2.4.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91 +ai2_olmo_core-2.4.0.dist-info/licenses/LICENSE,sha256=YvuKOpYh3COIF0yqq-nCMXtpS7mh1GyYvPVlW2j1G-M,11359 +ai2_olmo_core-2.4.0.dist-info/top_level.txt,sha256=UtCTFfoX3W7Uv2UKc7h_I8QyTlIAl_fZSZyb7UGwY6Q,10 +olmo_core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +olmo_core/__pycache__/__init__.cpython-310.pyc,, +olmo_core/__pycache__/aliases.cpython-310.pyc,, +olmo_core/__pycache__/config.cpython-310.pyc,, +olmo_core/__pycache__/doc_utils.cpython-310.pyc,, +olmo_core/__pycache__/exceptions.cpython-310.pyc,, +olmo_core/__pycache__/io.cpython-310.pyc,, +olmo_core/__pycache__/model_ladder.cpython-310.pyc,, +olmo_core/__pycache__/script_utils.cpython-310.pyc,, +olmo_core/__pycache__/utils.cpython-310.pyc,, +olmo_core/__pycache__/version.cpython-310.pyc,, +olmo_core/aliases.py,sha256=XWvWxUnmyAlg4lSNLHHATI6Vr1wsw2csndP81UhWVEs,114 +olmo_core/config.py,sha256=VbTYlZ_o_1kMfo1Lcs3ZKvVjfyK8awD1DZsxg3TT_Eg,11632 +olmo_core/data/__init__.py,sha256=OajbGC_Ey1fIS547tj3dWRF7ReEMgJ-iTBzSCUHycVg,2477 +olmo_core/data/__pycache__/__init__.cpython-310.pyc,, +olmo_core/data/__pycache__/collator.cpython-310.pyc,, +olmo_core/data/__pycache__/data_loader.cpython-310.pyc,, +olmo_core/data/__pycache__/numpy_dataset.cpython-310.pyc,, +olmo_core/data/__pycache__/source_mixture.cpython-310.pyc,, +olmo_core/data/__pycache__/tokenizer.cpython-310.pyc,, +olmo_core/data/__pycache__/types.cpython-310.pyc,, +olmo_core/data/__pycache__/utils.cpython-310.pyc,, +olmo_core/data/collator.py,sha256=f03Llo96jh2YV7O-L_0LhcAGvZ5GpVfnhDH2fhMKUxU,5537 +olmo_core/data/data_loader.py,sha256=1G6I1X0NN-FS4DwIiFy7IqBq_O894m48XHuQqM_q-vg,45476 +olmo_core/data/mixes/OLMo-longmino-mix-0625.txt,sha256=hWGScM5FrHrdJqaCJKBE2EhYgjtcLDA9Z_TjOYlmf_o,66030 +olmo_core/data/mixes/OLMo-longmino-mix-0925.txt,sha256=HXG_onn3rujGjLCifcvPSgRd5Y4h33fj0Wtcehs9yZs,66216 +olmo_core/data/mixes/OLMo-midtraining-mix-0625-100B.txt,sha256=nnPy6ZbsO6vvDcnzrSS5L19DzYKuIXv3XAKduKit1yA,2359991 +olmo_core/data/mixes/OLMo-midtraining-mix-0925-ingredient1-100B.txt,sha256=XGPAnEvtUvf_2BYwa99ZPRyhgZMwtrrBSW76dsU9v-0,2156993 +olmo_core/data/mixes/OLMo-midtraining-mix-0925-ingredient2-100B.txt,sha256=XGPAnEvtUvf_2BYwa99ZPRyhgZMwtrrBSW76dsU9v-0,2156993 +olmo_core/data/mixes/OLMo-mix-0625-150Bsample.txt,sha256=M-QmjnafVe8EQalmbRi5A2yNLnZdcRykBk6JRwdySj8,870288 +olmo_core/data/mixes/OLMo-mix-0625-700Bsample.txt,sha256=F8yCWQoQImyfK3YhVKsUdu9upzAnSaaD2LTANmlWLDw,30028 +olmo_core/data/mixes/OLMo-mix-0625-official.txt,sha256=13Bxanj-Dp-gdMifAQV0_TTsDudQy3kYgSDGIEfBonA,118078 +olmo_core/data/mixes/OLMo-mix-0625.txt,sha256=t4YWFTmMNYUyNqfU-E5AHrhB4ZwcU5HfoPU01XD5K-Y,116262 +olmo_core/data/mixes/OLMo-mix-0925-official.txt,sha256=5ygDlxunFQ1-z2Jgohq7QIaVO9kV7cuWiB0ueLHeZHE,110287 +olmo_core/data/mixes/OLMo-mix-0925.txt,sha256=_MaoK5pehoiF3s-8MEhpZ2RMfKSCp9aHEC9_9Zfb18k,109962 +olmo_core/data/mixes/OLMoE-mix-0824.txt,sha256=t4S7KjhnrE7LDlS9urh7_v1kgItLXqZJu3HQfwueCg8,120656 +olmo_core/data/mixes/__init__.py,sha256=AsfWpcsdc36396sC0oSsE70XBHtSIyiBNuovSTGc0UE,4989 +olmo_core/data/mixes/__pycache__/__init__.cpython-310.pyc,, +olmo_core/data/mixes/dolma17.txt,sha256=5csryxCmpE2y-H1wOkGu7O0-eAaqAiITkmOo8J89Gqo,105758 +olmo_core/data/mixes/v3-small-ppl-validation.txt,sha256=P8_jr3sOjrLdTnzPD6Xy-5W0s8FsU9Ocjrou5sVzttE,1050 +olmo_core/data/numpy_dataset.py,sha256=nKwAbtkNOGj-2t_ST8lysD_5CnvX9KsWrkcCd1GVBQQ,111657 +olmo_core/data/source_mixture.py,sha256=u0pAsaTAE3b7LxTGXR3bEKGqExQxUGZG_OAFQzcq1NU,23277 +olmo_core/data/tokenizer.py,sha256=_7HbHE6IfO5ZQiBQcoODKj2-PrFuPXXl0rnwjzGQMAA,3802 +olmo_core/data/types.py,sha256=25OrKLACouQduMoUwJmPZXjErDO0gxIc6WqIt9ygpik,1065 +olmo_core/data/utils.py,sha256=t8xjXBUqSVNViMNKBJo7TdAhrjvbmwJgqQJkE-i3ejg,36437 +olmo_core/distributed/__init__.py,sha256=CacGOPn8um0fqmNB5z4E6uXRCNO52ZasI_ucYrOJojY,76 +olmo_core/distributed/__pycache__/__init__.cpython-310.pyc,, +olmo_core/distributed/__pycache__/utils.cpython-310.pyc,, +olmo_core/distributed/checkpoint/__init__.py,sha256=WhIWB-EpiGvJJaw9FG-ZjVN1pQ37pVo1KUpXPQ8fjKw,31596 +olmo_core/distributed/checkpoint/__pycache__/__init__.cpython-310.pyc,, +olmo_core/distributed/checkpoint/__pycache__/filesystem.cpython-310.pyc,, +olmo_core/distributed/checkpoint/filesystem.py,sha256=gD9K6tYEeF22880ucVSmLOlEI-HJ6uEHGdMUyUV9fFc,15630 +olmo_core/distributed/parallel/__init__.py,sha256=cNfbyX4UdTLapHZr-Fi_94-tkbIOwcfzgIXBDh8HH4U,20199 +olmo_core/distributed/parallel/__pycache__/__init__.cpython-310.pyc,, +olmo_core/distributed/parallel/__pycache__/context_parallel.cpython-310.pyc,, +olmo_core/distributed/parallel/__pycache__/data_parallel.cpython-310.pyc,, +olmo_core/distributed/parallel/__pycache__/expert_parallel.cpython-310.pyc,, +olmo_core/distributed/parallel/__pycache__/pipeline_parallel.cpython-310.pyc,, +olmo_core/distributed/parallel/__pycache__/tensor_parallel.cpython-310.pyc,, +olmo_core/distributed/parallel/context_parallel.py,sha256=O6c9uSyIRd2kQbh8LIZ_eNehc_5CaSCSFmRFBHjqr5I,243 +olmo_core/distributed/parallel/data_parallel.py,sha256=8uSoVmRGI4zV9KDqtRL_pa2QVPdrpSzBUbhdDLHQFsA,2655 +olmo_core/distributed/parallel/expert_parallel.py,sha256=6pxELsC90UlV2TmtpwXsMkCezqAWGEf67du0TYGZRFI,241 +olmo_core/distributed/parallel/pipeline_parallel.py,sha256=l_Dypo2NWmfjI2-UCVrM13FJvprsUs_EIprRQ6cHEPs,6933 +olmo_core/distributed/parallel/tensor_parallel.py,sha256=M1L70Nj8dYIxRRlrTkfQ54HEfM02xXIzv3CneWmL7oI,2173 +olmo_core/distributed/utils.py,sha256=B1JCXd604jqQV0AaF7HIBg7_y4WI6Qlrax3woSQG4pY,17870 +olmo_core/doc_utils.py,sha256=6p5zoXjR3ozSLsluZSd7pMqodEmPJ_RHZA7yshQK3LA,537 +olmo_core/eval/__init__.py,sha256=ZpvrlpSrgD-Mj_7nnlAilJfqJe2xSQXndluxFsP_dL0,215 +olmo_core/eval/__pycache__/__init__.cpython-310.pyc,, +olmo_core/eval/__pycache__/evaluator.cpython-310.pyc,, +olmo_core/eval/__pycache__/lm_evaluator.cpython-310.pyc,, +olmo_core/eval/__pycache__/metrics.cpython-310.pyc,, +olmo_core/eval/__pycache__/task_groups.cpython-310.pyc,, +olmo_core/eval/evaluator.py,sha256=IAEtle6bJFcpNPGmUWv1zxtVkrpltwAvettIQ779YQY,2668 +olmo_core/eval/lm_evaluator.py,sha256=8jMpC5OOdZAA7rct-SViNJLm-5do0o7Ku6WDbPBWPcs,4444 +olmo_core/eval/metrics.py,sha256=SDY9TDklQmVi6zye_1ADtWkAweDL_1XYlG0EPYWCBIo,2807 +olmo_core/eval/task_groups.py,sha256=DKDYST-VfZTcRg5Wamn8TEQn61fWPRZvfgCRBeqP-6Y,5012 +olmo_core/exceptions.py,sha256=xDvUJ_l8G4a2Bqe4hAHxORBFLLh_lQQW8ilOpAf2u3U,641 +olmo_core/float8/__init__.py,sha256=HaTh6amNGemeGxBXrXSlt832NChMw_hA5qhD5sqzlUk,4109 +olmo_core/float8/__pycache__/__init__.cpython-310.pyc,, +olmo_core/float8/__pycache__/ao.cpython-310.pyc,, +olmo_core/float8/__pycache__/utils.cpython-310.pyc,, +olmo_core/float8/ao.py,sha256=Jf1AUHRaLuEfHEUGh0Eph8pRFzAU2lxVbIiSCb6deQ4,3989 +olmo_core/float8/utils.py,sha256=CfrJORwK4CfaEMVUnFuT1ImyQodWCqmiK2lEhrU70BA,1378 +olmo_core/generate/__init__.py,sha256=O7nvnSSGc6krMw2G9H-2pRnqY2utvczF996d4G6hQmc,361 +olmo_core/generate/__pycache__/__init__.cpython-310.pyc,, +olmo_core/generate/__pycache__/chat.cpython-310.pyc,, +olmo_core/generate/__pycache__/sampling.cpython-310.pyc,, +olmo_core/generate/__pycache__/utils.cpython-310.pyc,, +olmo_core/generate/chat.py,sha256=OvORsvdX2EOL6m_Pb7lUk_OO0ufAZRcjsAiypTJar6U,17664 +olmo_core/generate/generation_module/__init__.py,sha256=SnoUNb-mLD_qAxk6-K4_w431FymUXUTpZz5OwlPlwpc,361 +olmo_core/generate/generation_module/__pycache__/__init__.cpython-310.pyc,, +olmo_core/generate/generation_module/__pycache__/config.cpython-310.pyc,, +olmo_core/generate/generation_module/__pycache__/generation_module.cpython-310.pyc,, +olmo_core/generate/generation_module/config.py,sha256=7roI_q9swvHrgJmADPDdUqAFoHyYGjgTn8rXI4c6rbw,2732 +olmo_core/generate/generation_module/generation_module.py,sha256=PiWHPrLjUHwlGSPnqlJG89Me2lKLcs8Wnh4uAIqny5c,874 +olmo_core/generate/generation_module/transformer/__init__.py,sha256=P0aSMv5nn-MuMWOeBUVt7f2jiEzIp_SzD03Itehm95Y,204 +olmo_core/generate/generation_module/transformer/__pycache__/__init__.cpython-310.pyc,, +olmo_core/generate/generation_module/transformer/__pycache__/config.cpython-310.pyc,, +olmo_core/generate/generation_module/transformer/__pycache__/generation_module.cpython-310.pyc,, +olmo_core/generate/generation_module/transformer/config.py,sha256=4PPXxWqn6JLiaEwqiQmFi3GsaJ_GMesUunCAM8SXiNo,3804 +olmo_core/generate/generation_module/transformer/generation_module.py,sha256=-XBDzm7cDV_6E-qSDfhcKffFjQQZBP90EAaGy17Iv3E,22430 +olmo_core/generate/sampling.py,sha256=5B3-F4EhpL_CS6fkq299bNL-BtN7IRcNnlDPZ4NjW2g,4486 +olmo_core/generate/utils.py,sha256=QHOvt5X1gc_nLdglml9S7ldz-nUutYbpylRdrz9vjzw,793 +olmo_core/internal/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +olmo_core/internal/__pycache__/__init__.cpython-310.pyc,, +olmo_core/internal/__pycache__/common.cpython-310.pyc,, +olmo_core/internal/__pycache__/cookbook.cpython-310.pyc,, +olmo_core/internal/__pycache__/experiment.cpython-310.pyc,, +olmo_core/internal/__pycache__/model_ladder.cpython-310.pyc,, +olmo_core/internal/common.py,sha256=NBhxdN7Av1YhLs6dt3V90ylQx2DLzEw1-SFfY3dAb64,9286 +olmo_core/internal/cookbook.py,sha256=Jxe9j_5vHuJdbxIXA20ywMOYTc-tgfER_ZYhvnpDst4,5486 +olmo_core/internal/experiment.py,sha256=yLDsZ3QR-9hXAjxK6WutoLMVgDjUKNaQJcgvYnQmXgI,20055 +olmo_core/internal/model_ladder.py,sha256=Bl--RFq6eBtW6vrPXdbDyDLh3dWM8UE0ke4NBg3kktI,6425 +olmo_core/io.py,sha256=D0wLVLLjc4kJDUPpiLZL0KOzcVEyhethvOgyZhmZOg4,35990 +olmo_core/kernels/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +olmo_core/kernels/__pycache__/__init__.cpython-310.pyc,, +olmo_core/kernels/__pycache__/moe.cpython-310.pyc,, +olmo_core/kernels/moe.py,sha256=s-baQjMwzOHeoqmx3Kr9KhgnGVuBoYyT8LZbgFOhSVE,15947 +olmo_core/launch/__init__.py,sha256=7nvo9YJev0oHqyn4hmxUogGjlzQWicrju5VQxsGjmfU,63 +olmo_core/launch/__pycache__/__init__.cpython-310.pyc,, +olmo_core/launch/__pycache__/beaker.cpython-310.pyc,, +olmo_core/launch/__pycache__/reorder_ranks_in_gcp.cpython-310.pyc,, +olmo_core/launch/__pycache__/select_beaker_hosts.cpython-310.pyc,, +olmo_core/launch/__pycache__/utils.cpython-310.pyc,, +olmo_core/launch/beaker.py,sha256=LshGcGhwdjrcyfmDTIxG09nYscEuHCA13VfZKcdAoXk,36455 +olmo_core/launch/reorder_ranks_in_gcp.py,sha256=lON8YzZ83OxCa1N1h_jzaL5e8-y5yWcgpv-APncF67o,4135 +olmo_core/launch/select_beaker_hosts.py,sha256=eBZrOlhaLtMzpZ6RCBXdMkbmY7HJClRk5sHsrlDEcIU,11561 +olmo_core/launch/utils.py,sha256=ERZf3O2yh8a1Da-Rw24LSwoM-kzY6jGYBWHwqHJ8-Es,2663 +olmo_core/model_ladder.py,sha256=oz__aVMPAU7qrquHi7w5dIEHnKDSqYkYoZAlVLEhHFM,15064 +olmo_core/nn/__init__.py,sha256=C1yT4sObTBqoIyRk4dvoRRGB3zLg2mimAE5RlZkIJpQ,57 +olmo_core/nn/__pycache__/__init__.cpython-310.pyc,, +olmo_core/nn/__pycache__/buffer_cache.cpython-310.pyc,, +olmo_core/nn/__pycache__/cross_entropy_loss.cpython-310.pyc,, +olmo_core/nn/__pycache__/feed_forward.cpython-310.pyc,, +olmo_core/nn/__pycache__/layer_norm.cpython-310.pyc,, +olmo_core/nn/__pycache__/lm_head.cpython-310.pyc,, +olmo_core/nn/__pycache__/rope.cpython-310.pyc,, +olmo_core/nn/__pycache__/utils.cpython-310.pyc,, +olmo_core/nn/attention/__init__.py,sha256=kQ3-Q9xLTItv0-DkycBIZcd55pxY1yYd73Lct2RbfQs,34442 +olmo_core/nn/attention/__pycache__/__init__.cpython-310.pyc,, +olmo_core/nn/attention/__pycache__/backend.cpython-310.pyc,, +olmo_core/nn/attention/__pycache__/flash_attn_api.cpython-310.pyc,, +olmo_core/nn/attention/__pycache__/kv_cache.cpython-310.pyc,, +olmo_core/nn/attention/__pycache__/ring.cpython-310.pyc,, +olmo_core/nn/attention/__pycache__/te_attn_api.cpython-310.pyc,, +olmo_core/nn/attention/backend.py,sha256=a7UdJhTm52V_1xC2ujNjR6n7KqQ16fifUhw6tuQUA_0,24899 +olmo_core/nn/attention/flash_attn_api.py,sha256=dNxvox4Igc9BXNlJLc2hVjNxPrZgFQWy3w3KmwpH4n0,13539 +olmo_core/nn/attention/kv_cache.py,sha256=juvVDx6hTvK5_3Mfq0HlkgZkcNaSGa6RPmG9W2VlLEs,3863 +olmo_core/nn/attention/ring.py,sha256=HYY44Id3di8PEU_wMj_2-6J_xRmNY2w19YE4Q0LMjkE,13514 +olmo_core/nn/attention/te_attn_api.py,sha256=GueeH9-LKxzqro5a6YkcMn899flRBqQnUV06ig1JyVM,293 +olmo_core/nn/buffer_cache.py,sha256=3MrWKdI0AA4iiQIDqMJyl0HwdByqDg853wgksM_XnT0,2346 +olmo_core/nn/conversion/__init__.py,sha256=uCDzaxrBI8U_m8quzLiWX3DDwWKvGoTmLGT1OvMUoOY,348 +olmo_core/nn/conversion/__pycache__/__init__.cpython-310.pyc,, +olmo_core/nn/conversion/__pycache__/state_converter.cpython-310.pyc,, +olmo_core/nn/conversion/__pycache__/state_mapping.cpython-310.pyc,, +olmo_core/nn/conversion/state_converter.py,sha256=jj4kkvlp1SIb4_HLerLbq_UQ0HGIZqZ_5Pa67t0-QqQ,5674 +olmo_core/nn/conversion/state_mapping.py,sha256=eu_yy8-kIzppPD-rM-ZqZ9dI2-5SYFx7F-rn-kHEWS0,10817 +olmo_core/nn/cross_entropy_loss.py,sha256=bHwy2fN5XjvLVCz7IBdj1dUoXs42iKeSR72LAmtuwfM,7225 +olmo_core/nn/feed_forward.py,sha256=hmbeWHNS3l9SV15Sr1DlFHeKpBvstGOqw8Z55qbt2Ug,7202 +olmo_core/nn/functional/__init__.py,sha256=DAjfYafxKgdUrfgmbMZaLNDaefJb8EfESb-GJhRpfOk,455 +olmo_core/nn/functional/__pycache__/__init__.cpython-310.pyc,, +olmo_core/nn/functional/__pycache__/cross_entropy_loss.cpython-310.pyc,, +olmo_core/nn/functional/cross_entropy_loss.py,sha256=i9FnEpKMZmXGmXi0ZoS3rhtQdN-lWyTL80AwPJWoaf0,4505 +olmo_core/nn/hf/__init__.py,sha256=FQfkS3ZdT92Ngrk7fZwUQVcmZdNoL-aZs9g6zjjYSX4,688 +olmo_core/nn/hf/__pycache__/__init__.cpython-310.pyc,, +olmo_core/nn/hf/__pycache__/checkpoint.cpython-310.pyc,, +olmo_core/nn/hf/__pycache__/config.cpython-310.pyc,, +olmo_core/nn/hf/__pycache__/convert.cpython-310.pyc,, +olmo_core/nn/hf/checkpoint.py,sha256=ghk-_i-nXebpZFKvINQ13ma85kfmKil3G4A2A2NYQng,7429 +olmo_core/nn/hf/config.py,sha256=X4fgfcyZSu6b15vynwmV6iZQbvbkRYRSWcW0vMXV7Tg,9705 +olmo_core/nn/hf/convert.py,sha256=wzVv1_yPRxnpXjPHMd84hwTvQC2-hbX8ZvSka6v5OjU,21361 +olmo_core/nn/layer_norm.py,sha256=tzm4xPhEfi8Hz0o-j3C75Yxb8nTKrTJMssO3FOYgAoM,9184 +olmo_core/nn/lm_head.py,sha256=_cgLUu-egIKVukbWQb2mgQouJ5Uk-LQyP0kfbSX0rg8,19921 +olmo_core/nn/moe/__init__.py,sha256=tPBREjIFac9oYTGIH86r6vgt4dfMscN6ZFP63YOKjZQ,569 +olmo_core/nn/moe/__pycache__/__init__.cpython-310.pyc,, +olmo_core/nn/moe/__pycache__/loss.cpython-310.pyc,, +olmo_core/nn/moe/__pycache__/mlp.cpython-310.pyc,, +olmo_core/nn/moe/__pycache__/moe.cpython-310.pyc,, +olmo_core/nn/moe/__pycache__/parallel_mlp.cpython-310.pyc,, +olmo_core/nn/moe/__pycache__/router.cpython-310.pyc,, +olmo_core/nn/moe/loss.py,sha256=HVZ4fOUFlo5bCNZiLv9AuZ8wnbzx6rjJRrHVvqI5Ucs,5870 +olmo_core/nn/moe/mlp.py,sha256=o6wF6G9iPAL6HLkXXboowbkksy_gl23uMwEJ3rbnbrE,10653 +olmo_core/nn/moe/moe.py,sha256=Q7kAfy84zCY6einPV5SnduLbCMoNDH9PaYpd60GbPYM,12596 +olmo_core/nn/moe/parallel_mlp.py,sha256=FbnMQw3pGfJGW4Xj6g70PT91fdZJvayx3RteK2nuYNM,30351 +olmo_core/nn/moe/router.py,sha256=3ilzo6otNRiNg3gE4Tt1xoKmSgMgex0if4zZcE2I6ZI,21866 +olmo_core/nn/rope.py,sha256=WKhxHlCzo6Q19qsgpcmTYmXhJ2UfNT4iJ5F9SYjSWpg,30870 +olmo_core/nn/transformer/__init__.py,sha256=wMhtrODKXpwcj0K7SopsS6PZgBfaudYhzQxyssPmK1w,1305 +olmo_core/nn/transformer/__pycache__/__init__.cpython-310.pyc,, +olmo_core/nn/transformer/__pycache__/block.cpython-310.pyc,, +olmo_core/nn/transformer/__pycache__/config.cpython-310.pyc,, +olmo_core/nn/transformer/__pycache__/init.cpython-310.pyc,, +olmo_core/nn/transformer/__pycache__/model.cpython-310.pyc,, +olmo_core/nn/transformer/block.py,sha256=SVXRnjkZGDuU_WO7Y6xCaSaswvBuYsGq0HuTHnXxUFs,34600 +olmo_core/nn/transformer/config.py,sha256=DwHp5loelJ3bdZkyF_bbWOMcwehLb1fCbghUhY1z3JI,41366 +olmo_core/nn/transformer/init.py,sha256=Zs8OFKdd0QiILqlkDd5HQuNwxiXXQVpdnofiUmMpTiA,6411 +olmo_core/nn/transformer/model.py,sha256=r6m14Vy-C-yX09KKameahjo3ECpvnAgJnW2RagEDmoU,42230 +olmo_core/nn/utils.py,sha256=R6nQHvsRIDcX9gvQqB3gIHaft8s0vP-8NCKuZ7w1M8s,2620 +olmo_core/ops/__init__.py,sha256=OkGQqXX1QquZvb99rNPXuSCMjCSaqdtZHX4nfV2teY4,910 +olmo_core/ops/__pycache__/__init__.cpython-310.pyc,, +olmo_core/ops/__pycache__/moe.cpython-310.pyc,, +olmo_core/ops/moe.py,sha256=vsYw3M-yWjw9KVgQTLfPpbjRzdbvYys4Y9lfGPHXoQU,8920 +olmo_core/optim/__init__.py,sha256=JFasWRYyxP3kDzPAco0JsdR4rpN-WtRkTseSH1KJqkQ,1140 +olmo_core/optim/__pycache__/__init__.cpython-310.pyc,, +olmo_core/optim/__pycache__/adam.cpython-310.pyc,, +olmo_core/optim/__pycache__/adamw.cpython-310.pyc,, +olmo_core/optim/__pycache__/config.cpython-310.pyc,, +olmo_core/optim/__pycache__/lion.cpython-310.pyc,, +olmo_core/optim/__pycache__/noop.cpython-310.pyc,, +olmo_core/optim/__pycache__/scheduler.cpython-310.pyc,, +olmo_core/optim/__pycache__/skip_step_optimizer.cpython-310.pyc,, +olmo_core/optim/adam.py,sha256=foIBbiK3PlxBdWnHsnIE3gS1F0lVBCLD1oNVEjfL-TM,582 +olmo_core/optim/adamw.py,sha256=jEMwwQOkKbxJItgo1pF3tkTa43xACj6lbPfxy6aB7jw,9410 +olmo_core/optim/config.py,sha256=CwjeoyqnwE-m7ZcaE7BO0fL9ofPo9pMhLK4KKy_vVcM,7224 +olmo_core/optim/lion.py,sha256=6aCDZsTfcZPqsIbuTC5MvgT7xrlbAgiQiihBAdcxyAs,4605 +olmo_core/optim/noop.py,sha256=lr2Qm9ywryZGsmgfCrTD2600iL0cd6p5_N-2qcSTxI8,2836 +olmo_core/optim/scheduler.py,sha256=BfUgIa6WnEqVmTfYFSm-A6O389oX69J6Q1cvMdudnPA,24570 +olmo_core/optim/skip_step_optimizer.py,sha256=kd39C7ldxA7AEEqA75C_h2zuxt26Hg96IECWDtS5ByU,4420 +olmo_core/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +olmo_core/script_utils.py,sha256=vW9TNEKjg_F1hL_s2cfpXYpuMO5ht5EivsQkQlze92g,6253 +olmo_core/testing/__init__.py,sha256=VVcJChWpn9Zbq-vndjZvyDheDAOMbId4qbVO2qKBA2g,936 +olmo_core/testing/__pycache__/__init__.cpython-310.pyc,, +olmo_core/testing/__pycache__/distributed.cpython-310.pyc,, +olmo_core/testing/__pycache__/utils.cpython-310.pyc,, +olmo_core/testing/distributed.py,sha256=WNZZRssFr7eCIrkqkJL-oSsmW86kDHW3c6TrH2opnJk,3801 +olmo_core/testing/utils.py,sha256=Vfuq8_qbTMqPm-vRXm9FOsK21xQwDCQmEU5zpUxO2Rc,3910 +olmo_core/train/__init__.py,sha256=QllngPRgTyjyNF9GILCfkQ9_w8vZftp6fHHjPCd8oIg,5243 +olmo_core/train/__pycache__/__init__.cpython-310.pyc,, +olmo_core/train/__pycache__/checkpoint.cpython-310.pyc,, +olmo_core/train/__pycache__/common.cpython-310.pyc,, +olmo_core/train/__pycache__/config.cpython-310.pyc,, +olmo_core/train/__pycache__/trainer.cpython-310.pyc,, +olmo_core/train/__pycache__/utils.cpython-310.pyc,, +olmo_core/train/callbacks/__init__.py,sha256=eEN2UiyTRAbCSZTdSFVC216apDW-F1DSeve5dpfYV5w,1903 +olmo_core/train/callbacks/__pycache__/__init__.cpython-310.pyc,, +olmo_core/train/callbacks/__pycache__/batch_size_scheduler.cpython-310.pyc,, +olmo_core/train/callbacks/__pycache__/beaker.cpython-310.pyc,, +olmo_core/train/callbacks/__pycache__/callback.cpython-310.pyc,, +olmo_core/train/callbacks/__pycache__/checkpointer.cpython-310.pyc,, +olmo_core/train/callbacks/__pycache__/comet.cpython-310.pyc,, +olmo_core/train/callbacks/__pycache__/config_saver.cpython-310.pyc,, +olmo_core/train/callbacks/__pycache__/console_logger.cpython-310.pyc,, +olmo_core/train/callbacks/__pycache__/evaluator_callback.cpython-310.pyc,, +olmo_core/train/callbacks/__pycache__/gap_monitor.cpython-310.pyc,, +olmo_core/train/callbacks/__pycache__/garbage_collector.cpython-310.pyc,, +olmo_core/train/callbacks/__pycache__/gpu_memory_monitor.cpython-310.pyc,, +olmo_core/train/callbacks/__pycache__/list_checkpointer.cpython-310.pyc,, +olmo_core/train/callbacks/__pycache__/monkey_patcher.cpython-310.pyc,, +olmo_core/train/callbacks/__pycache__/profiler.cpython-310.pyc,, +olmo_core/train/callbacks/__pycache__/sequence_length_scheduler.cpython-310.pyc,, +olmo_core/train/callbacks/__pycache__/slack_notifier.cpython-310.pyc,, +olmo_core/train/callbacks/__pycache__/speed_monitor.cpython-310.pyc,, +olmo_core/train/callbacks/__pycache__/wandb.cpython-310.pyc,, +olmo_core/train/callbacks/batch_size_scheduler.py,sha256=cuHEz0Fi_8HHiB2uD9TjoTWP-jv_oC66rtBEnZjCX3I,8966 +olmo_core/train/callbacks/beaker.py,sha256=W_TBzw6VB7RN0pNiSz9V9GQXf_mPbxuswWZ-ltB-bCY,5546 +olmo_core/train/callbacks/callback.py,sha256=z6XAHJq1x-03RD7rY0JdlhhXFFlFAnwoJonQfVH3o7M,4052 +olmo_core/train/callbacks/checkpointer.py,sha256=BA2JqUJ1Yf2bN2M-OHtKhP6qZsjD-k6KAiaPLk-rMNA,10132 +olmo_core/train/callbacks/comet.py,sha256=52Hqep7Ii5BATb1mbgZj5luWap5ez35QlSyhxn1vAtQ,7781 +olmo_core/train/callbacks/config_saver.py,sha256=N1zAfyhQo26Tx0EDPFfTWu670WHynjhy_QOAiT-8s0k,2729 +olmo_core/train/callbacks/console_logger.py,sha256=lLwyD743W3nz_7vQziSG-x0z5MsO-6_lQXAn040Fqi8,2948 +olmo_core/train/callbacks/evaluator_callback.py,sha256=-8wnF55o7TEYutmFCDzR7V0mYKNLNcwTaD_Lb1LwzHA,16473 +olmo_core/train/callbacks/gap_monitor.py,sha256=5mM7m0wYMgLpMiOtXVWwgYcU5wMImTlpSh3qKC6r_XE,7053 +olmo_core/train/callbacks/garbage_collector.py,sha256=mQpq-ssLKPAMSRI6F7nb_VSk5yP5ZiqzE3NqB5Af15U,1426 +olmo_core/train/callbacks/gpu_memory_monitor.py,sha256=fgpMMOFanUPfmWUk5cKZCbcrw6-TZXXEm0JujqMt1gM,2736 +olmo_core/train/callbacks/list_checkpointer.py,sha256=6ur7xPnyEhoUFPe7dOsSNcxpKomG_PJocUrnEXlUeyQ,2035 +olmo_core/train/callbacks/monkey_patcher.py,sha256=d_c1D0MpJJzzMxaOmH5e5gOgZ4oOi6xqnEWNLbG4OtU,694 +olmo_core/train/callbacks/profiler.py,sha256=Nt8osZTWx_h0KgRpXaWIEeSpACRstzUJFgXEm3qlnb4,6579 +olmo_core/train/callbacks/sequence_length_scheduler.py,sha256=A3IiAfrUGWGoiFf6xMJz5YmEAKqXSZQTM3WWG4eFoCU,6675 +olmo_core/train/callbacks/slack_notifier.py,sha256=lnTa5CeBetCrBi1pkPknv2UcKDY-uhHE5rztFmgK3SQ,4339 +olmo_core/train/callbacks/speed_monitor.py,sha256=U3aYwbrhlKb4_nREPM3s00md3Da0LDjA2qHFb37ISdo,6522 +olmo_core/train/callbacks/wandb.py,sha256=vqVhKyrVte-Wl9eF2BmqG3dwGqGqgBQOUsjvXzYDoqo,4851 +olmo_core/train/checkpoint.py,sha256=7x2ntjzM-b27ykGu4YT4axtyajB_Ja30ZmL4P_W5nns,17287 +olmo_core/train/common.py,sha256=KWB5T9ZHf_FqgIlQ0sfujzGCM3jGvR9h1PC62APtG1k,6463 +olmo_core/train/config.py,sha256=aaHb5dyriRDcemMPLiXXG0qmf8oYNRN6mbxxlohKF_4,7100 +olmo_core/train/train_module/__init__.py,sha256=EbKjo69OP7LcCVWXgnTjSf-p6RZFwI3uSjRqfVxIHL8,1190 +olmo_core/train/train_module/__pycache__/__init__.cpython-310.pyc,, +olmo_core/train/train_module/__pycache__/train_module.cpython-310.pyc,, +olmo_core/train/train_module/train_module.py,sha256=1FqhHiVA1Ca4cD79fFNX5F9I3nFtAgofa_v22xOrPdM,13599 +olmo_core/train/train_module/transformer/__init__.py,sha256=yAtsjmsc7yZ1Q4mQiEgJZG3CLmyZbM_3j9Nq_E7zf4g,1036 +olmo_core/train/train_module/transformer/__pycache__/__init__.cpython-310.pyc,, +olmo_core/train/train_module/transformer/__pycache__/common.cpython-310.pyc,, +olmo_core/train/train_module/transformer/__pycache__/config.cpython-310.pyc,, +olmo_core/train/train_module/transformer/__pycache__/pipeline_train_module.cpython-310.pyc,, +olmo_core/train/train_module/transformer/__pycache__/train_module.cpython-310.pyc,, +olmo_core/train/train_module/transformer/common.py,sha256=1KU_SDadtqyAmaqwHspIj_5DwDqBBLc5u6eTy_HiRfY,6005 +olmo_core/train/train_module/transformer/config.py,sha256=N2kd3R7G9850LutkzTmzCCDjuVRpen2_FbLsl69C_pQ,12230 +olmo_core/train/train_module/transformer/pipeline_train_module.py,sha256=iVkEHz7iMcIj3A9x5wh_Ti44o-bAUnqOWN-j3iin_2I,28412 +olmo_core/train/train_module/transformer/train_module.py,sha256=0hB_BIP7nl7621n3hHLpLqW7-DF-Rz9CRr4OB-oZNow,26638 +olmo_core/train/trainer.py,sha256=n_aUSAUp1RAFRifLMgctyKB3_xp5f1DjhW1hf7vMY6w,52976 +olmo_core/train/utils.py,sha256=KQp10vHsw4wnHuwtmaMadKrWHCIoraAl3OuYdF3kbyY,12830 +olmo_core/utils.py,sha256=Tcg84KbyWn7MxlNjLxXOzCrEl5GNGmWJXtxFF5COleI,22679 +olmo_core/version.py,sha256=RJiyeJ_YuVZ4Lrb0ppk0_e-tttQsSAn5g3MyuHsLEjQ,308 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo_core-2.4.0.dist-info/WHEEL b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo_core-2.4.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..e7fa31b6f3f78deb1022c1f7927f07d4d16da822 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo_core-2.4.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo_core-2.4.0.dist-info/top_level.txt b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo_core-2.4.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..a4839365c5a7660ac2017ca3ee83ab52ae424893 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo_core-2.4.0.dist-info/top_level.txt @@ -0,0 +1 @@ +olmo_core diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/annotated_types-0.7.0.dist-info/INSTALLER b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/annotated_types-0.7.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/annotated_types-0.7.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/annotated_types-0.7.0.dist-info/METADATA b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/annotated_types-0.7.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..3ac05cfd1077ba5664e98ecd1342f7c54360b936 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/annotated_types-0.7.0.dist-info/METADATA @@ -0,0 +1,295 @@ +Metadata-Version: 2.3 +Name: annotated-types +Version: 0.7.0 +Summary: Reusable constraint types to use with typing.Annotated +Project-URL: Homepage, https://github.com/annotated-types/annotated-types +Project-URL: Source, https://github.com/annotated-types/annotated-types +Project-URL: Changelog, https://github.com/annotated-types/annotated-types/releases +Author-email: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com>, Samuel Colvin , Zac Hatfield-Dodds +License-File: LICENSE +Classifier: Development Status :: 4 - Beta +Classifier: Environment :: Console +Classifier: Environment :: MacOS X +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Information Technology +Classifier: License :: OSI Approved :: MIT License +Classifier: Operating System :: POSIX :: Linux +Classifier: Operating System :: Unix +Classifier: Programming Language :: Python :: 3 :: Only +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: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Typing :: Typed +Requires-Python: >=3.8 +Requires-Dist: typing-extensions>=4.0.0; python_version < '3.9' +Description-Content-Type: text/markdown + +# annotated-types + +[![CI](https://github.com/annotated-types/annotated-types/workflows/CI/badge.svg?event=push)](https://github.com/annotated-types/annotated-types/actions?query=event%3Apush+branch%3Amain+workflow%3ACI) +[![pypi](https://img.shields.io/pypi/v/annotated-types.svg)](https://pypi.python.org/pypi/annotated-types) +[![versions](https://img.shields.io/pypi/pyversions/annotated-types.svg)](https://github.com/annotated-types/annotated-types) +[![license](https://img.shields.io/github/license/annotated-types/annotated-types.svg)](https://github.com/annotated-types/annotated-types/blob/main/LICENSE) + +[PEP-593](https://peps.python.org/pep-0593/) added `typing.Annotated` as a way of +adding context-specific metadata to existing types, and specifies that +`Annotated[T, x]` _should_ be treated as `T` by any tool or library without special +logic for `x`. + +This package provides metadata objects which can be used to represent common +constraints such as upper and lower bounds on scalar values and collection sizes, +a `Predicate` marker for runtime checks, and +descriptions of how we intend these metadata to be interpreted. In some cases, +we also note alternative representations which do not require this package. + +## Install + +```bash +pip install annotated-types +``` + +## Examples + +```python +from typing import Annotated +from annotated_types import Gt, Len, Predicate + +class MyClass: + age: Annotated[int, Gt(18)] # Valid: 19, 20, ... + # Invalid: 17, 18, "19", 19.0, ... + factors: list[Annotated[int, Predicate(is_prime)]] # Valid: 2, 3, 5, 7, 11, ... + # Invalid: 4, 8, -2, 5.0, "prime", ... + + my_list: Annotated[list[int], Len(0, 10)] # Valid: [], [10, 20, 30, 40, 50] + # Invalid: (1, 2), ["abc"], [0] * 20 +``` + +## Documentation + +_While `annotated-types` avoids runtime checks for performance, users should not +construct invalid combinations such as `MultipleOf("non-numeric")` or `Annotated[int, Len(3)]`. +Downstream implementors may choose to raise an error, emit a warning, silently ignore +a metadata item, etc., if the metadata objects described below are used with an +incompatible type - or for any other reason!_ + +### Gt, Ge, Lt, Le + +Express inclusive and/or exclusive bounds on orderable values - which may be numbers, +dates, times, strings, sets, etc. Note that the boundary value need not be of the +same type that was annotated, so long as they can be compared: `Annotated[int, Gt(1.5)]` +is fine, for example, and implies that the value is an integer x such that `x > 1.5`. + +We suggest that implementors may also interpret `functools.partial(operator.le, 1.5)` +as being equivalent to `Gt(1.5)`, for users who wish to avoid a runtime dependency on +the `annotated-types` package. + +To be explicit, these types have the following meanings: + +* `Gt(x)` - value must be "Greater Than" `x` - equivalent to exclusive minimum +* `Ge(x)` - value must be "Greater than or Equal" to `x` - equivalent to inclusive minimum +* `Lt(x)` - value must be "Less Than" `x` - equivalent to exclusive maximum +* `Le(x)` - value must be "Less than or Equal" to `x` - equivalent to inclusive maximum + +### Interval + +`Interval(gt, ge, lt, le)` allows you to specify an upper and lower bound with a single +metadata object. `None` attributes should be ignored, and non-`None` attributes +treated as per the single bounds above. + +### MultipleOf + +`MultipleOf(multiple_of=x)` might be interpreted in two ways: + +1. Python semantics, implying `value % multiple_of == 0`, or +2. [JSONschema semantics](https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.6.2.1), + where `int(value / multiple_of) == value / multiple_of`. + +We encourage users to be aware of these two common interpretations and their +distinct behaviours, especially since very large or non-integer numbers make +it easy to cause silent data corruption due to floating-point imprecision. + +We encourage libraries to carefully document which interpretation they implement. + +### MinLen, MaxLen, Len + +`Len()` implies that `min_length <= len(value) <= max_length` - lower and upper bounds are inclusive. + +As well as `Len()` which can optionally include upper and lower bounds, we also +provide `MinLen(x)` and `MaxLen(y)` which are equivalent to `Len(min_length=x)` +and `Len(max_length=y)` respectively. + +`Len`, `MinLen`, and `MaxLen` may be used with any type which supports `len(value)`. + +Examples of usage: + +* `Annotated[list, MaxLen(10)]` (or `Annotated[list, Len(max_length=10))`) - list must have a length of 10 or less +* `Annotated[str, MaxLen(10)]` - string must have a length of 10 or less +* `Annotated[list, MinLen(3))` (or `Annotated[list, Len(min_length=3))`) - list must have a length of 3 or more +* `Annotated[list, Len(4, 6)]` - list must have a length of 4, 5, or 6 +* `Annotated[list, Len(8, 8)]` - list must have a length of exactly 8 + +#### Changed in v0.4.0 + +* `min_inclusive` has been renamed to `min_length`, no change in meaning +* `max_exclusive` has been renamed to `max_length`, upper bound is now **inclusive** instead of **exclusive** +* The recommendation that slices are interpreted as `Len` has been removed due to ambiguity and different semantic + meaning of the upper bound in slices vs. `Len` + +See [issue #23](https://github.com/annotated-types/annotated-types/issues/23) for discussion. + +### Timezone + +`Timezone` can be used with a `datetime` or a `time` to express which timezones +are allowed. `Annotated[datetime, Timezone(None)]` must be a naive datetime. +`Timezone[...]` ([literal ellipsis](https://docs.python.org/3/library/constants.html#Ellipsis)) +expresses that any timezone-aware datetime is allowed. You may also pass a specific +timezone string or [`tzinfo`](https://docs.python.org/3/library/datetime.html#tzinfo-objects) +object such as `Timezone(timezone.utc)` or `Timezone("Africa/Abidjan")` to express that you only +allow a specific timezone, though we note that this is often a symptom of fragile design. + +#### Changed in v0.x.x + +* `Timezone` accepts [`tzinfo`](https://docs.python.org/3/library/datetime.html#tzinfo-objects) objects instead of + `timezone`, extending compatibility to [`zoneinfo`](https://docs.python.org/3/library/zoneinfo.html) and third party libraries. + +### Unit + +`Unit(unit: str)` expresses that the annotated numeric value is the magnitude of +a quantity with the specified unit. For example, `Annotated[float, Unit("m/s")]` +would be a float representing a velocity in meters per second. + +Please note that `annotated_types` itself makes no attempt to parse or validate +the unit string in any way. That is left entirely to downstream libraries, +such as [`pint`](https://pint.readthedocs.io) or +[`astropy.units`](https://docs.astropy.org/en/stable/units/). + +An example of how a library might use this metadata: + +```python +from annotated_types import Unit +from typing import Annotated, TypeVar, Callable, Any, get_origin, get_args + +# given a type annotated with a unit: +Meters = Annotated[float, Unit("m")] + + +# you can cast the annotation to a specific unit type with any +# callable that accepts a string and returns the desired type +T = TypeVar("T") +def cast_unit(tp: Any, unit_cls: Callable[[str], T]) -> T | None: + if get_origin(tp) is Annotated: + for arg in get_args(tp): + if isinstance(arg, Unit): + return unit_cls(arg.unit) + return None + + +# using `pint` +import pint +pint_unit = cast_unit(Meters, pint.Unit) + + +# using `astropy.units` +import astropy.units as u +astropy_unit = cast_unit(Meters, u.Unit) +``` + +### Predicate + +`Predicate(func: Callable)` expresses that `func(value)` is truthy for valid values. +Users should prefer the statically inspectable metadata above, but if you need +the full power and flexibility of arbitrary runtime predicates... here it is. + +For some common constraints, we provide generic types: + +* `IsLower = Annotated[T, Predicate(str.islower)]` +* `IsUpper = Annotated[T, Predicate(str.isupper)]` +* `IsDigit = Annotated[T, Predicate(str.isdigit)]` +* `IsFinite = Annotated[T, Predicate(math.isfinite)]` +* `IsNotFinite = Annotated[T, Predicate(Not(math.isfinite))]` +* `IsNan = Annotated[T, Predicate(math.isnan)]` +* `IsNotNan = Annotated[T, Predicate(Not(math.isnan))]` +* `IsInfinite = Annotated[T, Predicate(math.isinf)]` +* `IsNotInfinite = Annotated[T, Predicate(Not(math.isinf))]` + +so that you can write e.g. `x: IsFinite[float] = 2.0` instead of the longer +(but exactly equivalent) `x: Annotated[float, Predicate(math.isfinite)] = 2.0`. + +Some libraries might have special logic to handle known or understandable predicates, +for example by checking for `str.isdigit` and using its presence to both call custom +logic to enforce digit-only strings, and customise some generated external schema. +Users are therefore encouraged to avoid indirection like `lambda s: s.lower()`, in +favor of introspectable methods such as `str.lower` or `re.compile("pattern").search`. + +To enable basic negation of commonly used predicates like `math.isnan` without introducing introspection that makes it impossible for implementers to introspect the predicate we provide a `Not` wrapper that simply negates the predicate in an introspectable manner. Several of the predicates listed above are created in this manner. + +We do not specify what behaviour should be expected for predicates that raise +an exception. For example `Annotated[int, Predicate(str.isdigit)]` might silently +skip invalid constraints, or statically raise an error; or it might try calling it +and then propagate or discard the resulting +`TypeError: descriptor 'isdigit' for 'str' objects doesn't apply to a 'int' object` +exception. We encourage libraries to document the behaviour they choose. + +### Doc + +`doc()` can be used to add documentation information in `Annotated`, for function and method parameters, variables, class attributes, return types, and any place where `Annotated` can be used. + +It expects a value that can be statically analyzed, as the main use case is for static analysis, editors, documentation generators, and similar tools. + +It returns a `DocInfo` class with a single attribute `documentation` containing the value passed to `doc()`. + +This is the early adopter's alternative form of the [`typing-doc` proposal](https://github.com/tiangolo/fastapi/blob/typing-doc/typing_doc.md). + +### Integrating downstream types with `GroupedMetadata` + +Implementers may choose to provide a convenience wrapper that groups multiple pieces of metadata. +This can help reduce verbosity and cognitive overhead for users. +For example, an implementer like Pydantic might provide a `Field` or `Meta` type that accepts keyword arguments and transforms these into low-level metadata: + +```python +from dataclasses import dataclass +from typing import Iterator +from annotated_types import GroupedMetadata, Ge + +@dataclass +class Field(GroupedMetadata): + ge: int | None = None + description: str | None = None + + def __iter__(self) -> Iterator[object]: + # Iterating over a GroupedMetadata object should yield annotated-types + # constraint metadata objects which describe it as fully as possible, + # and may include other unknown objects too. + if self.ge is not None: + yield Ge(self.ge) + if self.description is not None: + yield Description(self.description) +``` + +Libraries consuming annotated-types constraints should check for `GroupedMetadata` and unpack it by iterating over the object and treating the results as if they had been "unpacked" in the `Annotated` type. The same logic should be applied to the [PEP 646 `Unpack` type](https://peps.python.org/pep-0646/), so that `Annotated[T, Field(...)]`, `Annotated[T, Unpack[Field(...)]]` and `Annotated[T, *Field(...)]` are all treated consistently. + +Libraries consuming annotated-types should also ignore any metadata they do not recongize that came from unpacking a `GroupedMetadata`, just like they ignore unrecognized metadata in `Annotated` itself. + +Our own `annotated_types.Interval` class is a `GroupedMetadata` which unpacks itself into `Gt`, `Lt`, etc., so this is not an abstract concern. Similarly, `annotated_types.Len` is a `GroupedMetadata` which unpacks itself into `MinLen` (optionally) and `MaxLen`. + +### Consuming metadata + +We intend to not be prescriptive as to _how_ the metadata and constraints are used, but as an example of how one might parse constraints from types annotations see our [implementation in `test_main.py`](https://github.com/annotated-types/annotated-types/blob/f59cf6d1b5255a0fe359b93896759a180bec30ae/tests/test_main.py#L94-L103). + +It is up to the implementer to determine how this metadata is used. +You could use the metadata for runtime type checking, for generating schemas or to generate example data, amongst other use cases. + +## Design & History + +This package was designed at the PyCon 2022 sprints by the maintainers of Pydantic +and Hypothesis, with the goal of making it as easy as possible for end-users to +provide more informative annotations for use by runtime libraries. + +It is deliberately minimal, and following PEP-593 allows considerable downstream +discretion in what (if anything!) they choose to support. Nonetheless, we expect +that staying simple and covering _only_ the most common use-cases will give users +and maintainers the best experience we can. If you'd like more constraints for your +types - follow our lead, by defining them and documenting them downstream! diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/annotated_types-0.7.0.dist-info/RECORD b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/annotated_types-0.7.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..7c37220e01bbc498033ab3a214d91603ccde5037 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/annotated_types-0.7.0.dist-info/RECORD @@ -0,0 +1,10 @@ +annotated_types-0.7.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +annotated_types-0.7.0.dist-info/METADATA,sha256=7ltqxksJJ0wCYFGBNIQCWTlWQGeAH0hRFdnK3CB895E,15046 +annotated_types-0.7.0.dist-info/RECORD,, +annotated_types-0.7.0.dist-info/WHEEL,sha256=zEMcRr9Kr03x1ozGwg5v9NQBKn3kndp6LSoSlVg-jhU,87 +annotated_types-0.7.0.dist-info/licenses/LICENSE,sha256=_hBJiEsaDZNCkB6I4H8ykl0ksxIdmXK2poBfuYJLCV0,1083 +annotated_types/__init__.py,sha256=RynLsRKUEGI0KimXydlD1fZEfEzWwDo0Uon3zOKhG1Q,13819 +annotated_types/__pycache__/__init__.cpython-310.pyc,, +annotated_types/__pycache__/test_cases.cpython-310.pyc,, +annotated_types/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +annotated_types/test_cases.py,sha256=zHFX6EpcMbGJ8FzBYDbO56bPwx_DYIVSKbZM-4B3_lg,6421 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/annotated_types-0.7.0.dist-info/WHEEL b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/annotated_types-0.7.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..516596c76787b10928cbab24f22c0ea00433b15d --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/annotated_types-0.7.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.24.2 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/annotated_types/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/annotated_types/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..74e0deeab3f5904260ac2d36d64fbdec7e0ee0bf --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/annotated_types/__init__.py @@ -0,0 +1,432 @@ +import math +import sys +import types +from dataclasses import dataclass +from datetime import tzinfo +from typing import TYPE_CHECKING, Any, Callable, Iterator, Optional, SupportsFloat, SupportsIndex, TypeVar, Union + +if sys.version_info < (3, 8): + from typing_extensions import Protocol, runtime_checkable +else: + from typing import Protocol, runtime_checkable + +if sys.version_info < (3, 9): + from typing_extensions import Annotated, Literal +else: + from typing import Annotated, Literal + +if sys.version_info < (3, 10): + EllipsisType = type(Ellipsis) + KW_ONLY = {} + SLOTS = {} +else: + from types import EllipsisType + + KW_ONLY = {"kw_only": True} + SLOTS = {"slots": True} + + +__all__ = ( + 'BaseMetadata', + 'GroupedMetadata', + 'Gt', + 'Ge', + 'Lt', + 'Le', + 'Interval', + 'MultipleOf', + 'MinLen', + 'MaxLen', + 'Len', + 'Timezone', + 'Predicate', + 'LowerCase', + 'UpperCase', + 'IsDigits', + 'IsFinite', + 'IsNotFinite', + 'IsNan', + 'IsNotNan', + 'IsInfinite', + 'IsNotInfinite', + 'doc', + 'DocInfo', + '__version__', +) + +__version__ = '0.7.0' + + +T = TypeVar('T') + + +# arguments that start with __ are considered +# positional only +# see https://peps.python.org/pep-0484/#positional-only-arguments + + +class SupportsGt(Protocol): + def __gt__(self: T, __other: T) -> bool: + ... + + +class SupportsGe(Protocol): + def __ge__(self: T, __other: T) -> bool: + ... + + +class SupportsLt(Protocol): + def __lt__(self: T, __other: T) -> bool: + ... + + +class SupportsLe(Protocol): + def __le__(self: T, __other: T) -> bool: + ... + + +class SupportsMod(Protocol): + def __mod__(self: T, __other: T) -> T: + ... + + +class SupportsDiv(Protocol): + def __div__(self: T, __other: T) -> T: + ... + + +class BaseMetadata: + """Base class for all metadata. + + This exists mainly so that implementers + can do `isinstance(..., BaseMetadata)` while traversing field annotations. + """ + + __slots__ = () + + +@dataclass(frozen=True, **SLOTS) +class Gt(BaseMetadata): + """Gt(gt=x) implies that the value must be greater than x. + + It can be used with any type that supports the ``>`` operator, + including numbers, dates and times, strings, sets, and so on. + """ + + gt: SupportsGt + + +@dataclass(frozen=True, **SLOTS) +class Ge(BaseMetadata): + """Ge(ge=x) implies that the value must be greater than or equal to x. + + It can be used with any type that supports the ``>=`` operator, + including numbers, dates and times, strings, sets, and so on. + """ + + ge: SupportsGe + + +@dataclass(frozen=True, **SLOTS) +class Lt(BaseMetadata): + """Lt(lt=x) implies that the value must be less than x. + + It can be used with any type that supports the ``<`` operator, + including numbers, dates and times, strings, sets, and so on. + """ + + lt: SupportsLt + + +@dataclass(frozen=True, **SLOTS) +class Le(BaseMetadata): + """Le(le=x) implies that the value must be less than or equal to x. + + It can be used with any type that supports the ``<=`` operator, + including numbers, dates and times, strings, sets, and so on. + """ + + le: SupportsLe + + +@runtime_checkable +class GroupedMetadata(Protocol): + """A grouping of multiple objects, like typing.Unpack. + + `GroupedMetadata` on its own is not metadata and has no meaning. + All of the constraints and metadata should be fully expressable + in terms of the `BaseMetadata`'s returned by `GroupedMetadata.__iter__()`. + + Concrete implementations should override `GroupedMetadata.__iter__()` + to add their own metadata. + For example: + + >>> @dataclass + >>> class Field(GroupedMetadata): + >>> gt: float | None = None + >>> description: str | None = None + ... + >>> def __iter__(self) -> Iterable[object]: + >>> if self.gt is not None: + >>> yield Gt(self.gt) + >>> if self.description is not None: + >>> yield Description(self.gt) + + Also see the implementation of `Interval` below for an example. + + Parsers should recognize this and unpack it so that it can be used + both with and without unpacking: + + - `Annotated[int, Field(...)]` (parser must unpack Field) + - `Annotated[int, *Field(...)]` (PEP-646) + """ # noqa: trailing-whitespace + + @property + def __is_annotated_types_grouped_metadata__(self) -> Literal[True]: + return True + + def __iter__(self) -> Iterator[object]: + ... + + if not TYPE_CHECKING: + __slots__ = () # allow subclasses to use slots + + def __init_subclass__(cls, *args: Any, **kwargs: Any) -> None: + # Basic ABC like functionality without the complexity of an ABC + super().__init_subclass__(*args, **kwargs) + if cls.__iter__ is GroupedMetadata.__iter__: + raise TypeError("Can't subclass GroupedMetadata without implementing __iter__") + + def __iter__(self) -> Iterator[object]: # noqa: F811 + raise NotImplementedError # more helpful than "None has no attribute..." type errors + + +@dataclass(frozen=True, **KW_ONLY, **SLOTS) +class Interval(GroupedMetadata): + """Interval can express inclusive or exclusive bounds with a single object. + + It accepts keyword arguments ``gt``, ``ge``, ``lt``, and/or ``le``, which + are interpreted the same way as the single-bound constraints. + """ + + gt: Union[SupportsGt, None] = None + ge: Union[SupportsGe, None] = None + lt: Union[SupportsLt, None] = None + le: Union[SupportsLe, None] = None + + def __iter__(self) -> Iterator[BaseMetadata]: + """Unpack an Interval into zero or more single-bounds.""" + if self.gt is not None: + yield Gt(self.gt) + if self.ge is not None: + yield Ge(self.ge) + if self.lt is not None: + yield Lt(self.lt) + if self.le is not None: + yield Le(self.le) + + +@dataclass(frozen=True, **SLOTS) +class MultipleOf(BaseMetadata): + """MultipleOf(multiple_of=x) might be interpreted in two ways: + + 1. Python semantics, implying ``value % multiple_of == 0``, or + 2. JSONschema semantics, where ``int(value / multiple_of) == value / multiple_of`` + + We encourage users to be aware of these two common interpretations, + and libraries to carefully document which they implement. + """ + + multiple_of: Union[SupportsDiv, SupportsMod] + + +@dataclass(frozen=True, **SLOTS) +class MinLen(BaseMetadata): + """ + MinLen() implies minimum inclusive length, + e.g. ``len(value) >= min_length``. + """ + + min_length: Annotated[int, Ge(0)] + + +@dataclass(frozen=True, **SLOTS) +class MaxLen(BaseMetadata): + """ + MaxLen() implies maximum inclusive length, + e.g. ``len(value) <= max_length``. + """ + + max_length: Annotated[int, Ge(0)] + + +@dataclass(frozen=True, **SLOTS) +class Len(GroupedMetadata): + """ + Len() implies that ``min_length <= len(value) <= max_length``. + + Upper bound may be omitted or ``None`` to indicate no upper length bound. + """ + + min_length: Annotated[int, Ge(0)] = 0 + max_length: Optional[Annotated[int, Ge(0)]] = None + + def __iter__(self) -> Iterator[BaseMetadata]: + """Unpack a Len into zone or more single-bounds.""" + if self.min_length > 0: + yield MinLen(self.min_length) + if self.max_length is not None: + yield MaxLen(self.max_length) + + +@dataclass(frozen=True, **SLOTS) +class Timezone(BaseMetadata): + """Timezone(tz=...) requires a datetime to be aware (or ``tz=None``, naive). + + ``Annotated[datetime, Timezone(None)]`` must be a naive datetime. + ``Timezone[...]`` (the ellipsis literal) expresses that the datetime must be + tz-aware but any timezone is allowed. + + You may also pass a specific timezone string or tzinfo object such as + ``Timezone(timezone.utc)`` or ``Timezone("Africa/Abidjan")`` to express that + you only allow a specific timezone, though we note that this is often + a symptom of poor design. + """ + + tz: Union[str, tzinfo, EllipsisType, None] + + +@dataclass(frozen=True, **SLOTS) +class Unit(BaseMetadata): + """Indicates that the value is a physical quantity with the specified unit. + + It is intended for usage with numeric types, where the value represents the + magnitude of the quantity. For example, ``distance: Annotated[float, Unit('m')]`` + or ``speed: Annotated[float, Unit('m/s')]``. + + Interpretation of the unit string is left to the discretion of the consumer. + It is suggested to follow conventions established by python libraries that work + with physical quantities, such as + + - ``pint`` : + - ``astropy.units``: + + For indicating a quantity with a certain dimensionality but without a specific unit + it is recommended to use square brackets, e.g. `Annotated[float, Unit('[time]')]`. + Note, however, ``annotated_types`` itself makes no use of the unit string. + """ + + unit: str + + +@dataclass(frozen=True, **SLOTS) +class Predicate(BaseMetadata): + """``Predicate(func: Callable)`` implies `func(value)` is truthy for valid values. + + Users should prefer statically inspectable metadata, but if you need the full + power and flexibility of arbitrary runtime predicates... here it is. + + We provide a few predefined predicates for common string constraints: + ``IsLower = Predicate(str.islower)``, ``IsUpper = Predicate(str.isupper)``, and + ``IsDigits = Predicate(str.isdigit)``. Users are encouraged to use methods which + can be given special handling, and avoid indirection like ``lambda s: s.lower()``. + + Some libraries might have special logic to handle certain predicates, e.g. by + checking for `str.isdigit` and using its presence to both call custom logic to + enforce digit-only strings, and customise some generated external schema. + + We do not specify what behaviour should be expected for predicates that raise + an exception. For example `Annotated[int, Predicate(str.isdigit)]` might silently + skip invalid constraints, or statically raise an error; or it might try calling it + and then propagate or discard the resulting exception. + """ + + func: Callable[[Any], bool] + + def __repr__(self) -> str: + if getattr(self.func, "__name__", "") == "": + return f"{self.__class__.__name__}({self.func!r})" + if isinstance(self.func, (types.MethodType, types.BuiltinMethodType)) and ( + namespace := getattr(self.func.__self__, "__name__", None) + ): + return f"{self.__class__.__name__}({namespace}.{self.func.__name__})" + if isinstance(self.func, type(str.isascii)): # method descriptor + return f"{self.__class__.__name__}({self.func.__qualname__})" + return f"{self.__class__.__name__}({self.func.__name__})" + + +@dataclass +class Not: + func: Callable[[Any], bool] + + def __call__(self, __v: Any) -> bool: + return not self.func(__v) + + +_StrType = TypeVar("_StrType", bound=str) + +LowerCase = Annotated[_StrType, Predicate(str.islower)] +""" +Return True if the string is a lowercase string, False otherwise. + +A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string. +""" # noqa: E501 +UpperCase = Annotated[_StrType, Predicate(str.isupper)] +""" +Return True if the string is an uppercase string, False otherwise. + +A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string. +""" # noqa: E501 +IsDigit = Annotated[_StrType, Predicate(str.isdigit)] +IsDigits = IsDigit # type: ignore # plural for backwards compatibility, see #63 +""" +Return True if the string is a digit string, False otherwise. + +A string is a digit string if all characters in the string are digits and there is at least one character in the string. +""" # noqa: E501 +IsAscii = Annotated[_StrType, Predicate(str.isascii)] +""" +Return True if all characters in the string are ASCII, False otherwise. + +ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too. +""" + +_NumericType = TypeVar('_NumericType', bound=Union[SupportsFloat, SupportsIndex]) +IsFinite = Annotated[_NumericType, Predicate(math.isfinite)] +"""Return True if x is neither an infinity nor a NaN, and False otherwise.""" +IsNotFinite = Annotated[_NumericType, Predicate(Not(math.isfinite))] +"""Return True if x is one of infinity or NaN, and False otherwise""" +IsNan = Annotated[_NumericType, Predicate(math.isnan)] +"""Return True if x is a NaN (not a number), and False otherwise.""" +IsNotNan = Annotated[_NumericType, Predicate(Not(math.isnan))] +"""Return True if x is anything but NaN (not a number), and False otherwise.""" +IsInfinite = Annotated[_NumericType, Predicate(math.isinf)] +"""Return True if x is a positive or negative infinity, and False otherwise.""" +IsNotInfinite = Annotated[_NumericType, Predicate(Not(math.isinf))] +"""Return True if x is neither a positive or negative infinity, and False otherwise.""" + +try: + from typing_extensions import DocInfo, doc # type: ignore [attr-defined] +except ImportError: + + @dataclass(frozen=True, **SLOTS) + class DocInfo: # type: ignore [no-redef] + """ " + The return value of doc(), mainly to be used by tools that want to extract the + Annotated documentation at runtime. + """ + + documentation: str + """The documentation string passed to doc().""" + + def doc( + documentation: str, + ) -> DocInfo: + """ + Add documentation to a type annotation inside of Annotated. + + For example: + + >>> def hi(name: Annotated[int, doc("The name of the user")]) -> None: ... + """ + return DocInfo(documentation) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/annotated_types/py.typed b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/annotated_types/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/annotated_types/test_cases.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/annotated_types/test_cases.py new file mode 100644 index 0000000000000000000000000000000000000000..d9164d6883d2dd47cb766b483592ca3730f6f09d --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/annotated_types/test_cases.py @@ -0,0 +1,151 @@ +import math +import sys +from datetime import date, datetime, timedelta, timezone +from decimal import Decimal +from typing import Any, Dict, Iterable, Iterator, List, NamedTuple, Set, Tuple + +if sys.version_info < (3, 9): + from typing_extensions import Annotated +else: + from typing import Annotated + +import annotated_types as at + + +class Case(NamedTuple): + """ + A test case for `annotated_types`. + """ + + annotation: Any + valid_cases: Iterable[Any] + invalid_cases: Iterable[Any] + + +def cases() -> Iterable[Case]: + # Gt, Ge, Lt, Le + yield Case(Annotated[int, at.Gt(4)], (5, 6, 1000), (4, 0, -1)) + yield Case(Annotated[float, at.Gt(0.5)], (0.6, 0.7, 0.8, 0.9), (0.5, 0.0, -0.1)) + yield Case( + Annotated[datetime, at.Gt(datetime(2000, 1, 1))], + [datetime(2000, 1, 2), datetime(2000, 1, 3)], + [datetime(2000, 1, 1), datetime(1999, 12, 31)], + ) + yield Case( + Annotated[datetime, at.Gt(date(2000, 1, 1))], + [date(2000, 1, 2), date(2000, 1, 3)], + [date(2000, 1, 1), date(1999, 12, 31)], + ) + yield Case( + Annotated[datetime, at.Gt(Decimal('1.123'))], + [Decimal('1.1231'), Decimal('123')], + [Decimal('1.123'), Decimal('0')], + ) + + yield Case(Annotated[int, at.Ge(4)], (4, 5, 6, 1000, 4), (0, -1)) + yield Case(Annotated[float, at.Ge(0.5)], (0.5, 0.6, 0.7, 0.8, 0.9), (0.4, 0.0, -0.1)) + yield Case( + Annotated[datetime, at.Ge(datetime(2000, 1, 1))], + [datetime(2000, 1, 2), datetime(2000, 1, 3)], + [datetime(1998, 1, 1), datetime(1999, 12, 31)], + ) + + yield Case(Annotated[int, at.Lt(4)], (0, -1), (4, 5, 6, 1000, 4)) + yield Case(Annotated[float, at.Lt(0.5)], (0.4, 0.0, -0.1), (0.5, 0.6, 0.7, 0.8, 0.9)) + yield Case( + Annotated[datetime, at.Lt(datetime(2000, 1, 1))], + [datetime(1999, 12, 31), datetime(1999, 12, 31)], + [datetime(2000, 1, 2), datetime(2000, 1, 3)], + ) + + yield Case(Annotated[int, at.Le(4)], (4, 0, -1), (5, 6, 1000)) + yield Case(Annotated[float, at.Le(0.5)], (0.5, 0.0, -0.1), (0.6, 0.7, 0.8, 0.9)) + yield Case( + Annotated[datetime, at.Le(datetime(2000, 1, 1))], + [datetime(2000, 1, 1), datetime(1999, 12, 31)], + [datetime(2000, 1, 2), datetime(2000, 1, 3)], + ) + + # Interval + yield Case(Annotated[int, at.Interval(gt=4)], (5, 6, 1000), (4, 0, -1)) + yield Case(Annotated[int, at.Interval(gt=4, lt=10)], (5, 6), (4, 10, 1000, 0, -1)) + yield Case(Annotated[float, at.Interval(ge=0.5, le=1)], (0.5, 0.9, 1), (0.49, 1.1)) + yield Case( + Annotated[datetime, at.Interval(gt=datetime(2000, 1, 1), le=datetime(2000, 1, 3))], + [datetime(2000, 1, 2), datetime(2000, 1, 3)], + [datetime(2000, 1, 1), datetime(2000, 1, 4)], + ) + + yield Case(Annotated[int, at.MultipleOf(multiple_of=3)], (0, 3, 9), (1, 2, 4)) + yield Case(Annotated[float, at.MultipleOf(multiple_of=0.5)], (0, 0.5, 1, 1.5), (0.4, 1.1)) + + # lengths + + yield Case(Annotated[str, at.MinLen(3)], ('123', '1234', 'x' * 10), ('', '1', '12')) + yield Case(Annotated[str, at.Len(3)], ('123', '1234', 'x' * 10), ('', '1', '12')) + yield Case(Annotated[List[int], at.MinLen(3)], ([1, 2, 3], [1, 2, 3, 4], [1] * 10), ([], [1], [1, 2])) + yield Case(Annotated[List[int], at.Len(3)], ([1, 2, 3], [1, 2, 3, 4], [1] * 10), ([], [1], [1, 2])) + + yield Case(Annotated[str, at.MaxLen(4)], ('', '1234'), ('12345', 'x' * 10)) + yield Case(Annotated[str, at.Len(0, 4)], ('', '1234'), ('12345', 'x' * 10)) + yield Case(Annotated[List[str], at.MaxLen(4)], ([], ['a', 'bcdef'], ['a', 'b', 'c']), (['a'] * 5, ['b'] * 10)) + yield Case(Annotated[List[str], at.Len(0, 4)], ([], ['a', 'bcdef'], ['a', 'b', 'c']), (['a'] * 5, ['b'] * 10)) + + yield Case(Annotated[str, at.Len(3, 5)], ('123', '12345'), ('', '1', '12', '123456', 'x' * 10)) + yield Case(Annotated[str, at.Len(3, 3)], ('123',), ('12', '1234')) + + yield Case(Annotated[Dict[int, int], at.Len(2, 3)], [{1: 1, 2: 2}], [{}, {1: 1}, {1: 1, 2: 2, 3: 3, 4: 4}]) + yield Case(Annotated[Set[int], at.Len(2, 3)], ({1, 2}, {1, 2, 3}), (set(), {1}, {1, 2, 3, 4})) + yield Case(Annotated[Tuple[int, ...], at.Len(2, 3)], ((1, 2), (1, 2, 3)), ((), (1,), (1, 2, 3, 4))) + + # Timezone + + yield Case( + Annotated[datetime, at.Timezone(None)], [datetime(2000, 1, 1)], [datetime(2000, 1, 1, tzinfo=timezone.utc)] + ) + yield Case( + Annotated[datetime, at.Timezone(...)], [datetime(2000, 1, 1, tzinfo=timezone.utc)], [datetime(2000, 1, 1)] + ) + yield Case( + Annotated[datetime, at.Timezone(timezone.utc)], + [datetime(2000, 1, 1, tzinfo=timezone.utc)], + [datetime(2000, 1, 1), datetime(2000, 1, 1, tzinfo=timezone(timedelta(hours=6)))], + ) + yield Case( + Annotated[datetime, at.Timezone('Europe/London')], + [datetime(2000, 1, 1, tzinfo=timezone(timedelta(0), name='Europe/London'))], + [datetime(2000, 1, 1), datetime(2000, 1, 1, tzinfo=timezone(timedelta(hours=6)))], + ) + + # Quantity + + yield Case(Annotated[float, at.Unit(unit='m')], (5, 4.2), ('5m', '4.2m')) + + # predicate types + + yield Case(at.LowerCase[str], ['abc', 'foobar'], ['', 'A', 'Boom']) + yield Case(at.UpperCase[str], ['ABC', 'DEFO'], ['', 'a', 'abc', 'AbC']) + yield Case(at.IsDigit[str], ['123'], ['', 'ab', 'a1b2']) + yield Case(at.IsAscii[str], ['123', 'foo bar'], ['£100', '😊', 'whatever 👀']) + + yield Case(Annotated[int, at.Predicate(lambda x: x % 2 == 0)], [0, 2, 4], [1, 3, 5]) + + yield Case(at.IsFinite[float], [1.23], [math.nan, math.inf, -math.inf]) + yield Case(at.IsNotFinite[float], [math.nan, math.inf], [1.23]) + yield Case(at.IsNan[float], [math.nan], [1.23, math.inf]) + yield Case(at.IsNotNan[float], [1.23, math.inf], [math.nan]) + yield Case(at.IsInfinite[float], [math.inf], [math.nan, 1.23]) + yield Case(at.IsNotInfinite[float], [math.nan, 1.23], [math.inf]) + + # check stacked predicates + yield Case(at.IsInfinite[Annotated[float, at.Predicate(lambda x: x > 0)]], [math.inf], [-math.inf, 1.23, math.nan]) + + # doc + yield Case(Annotated[int, at.doc("A number")], [1, 2], []) + + # custom GroupedMetadata + class MyCustomGroupedMetadata(at.GroupedMetadata): + def __iter__(self) -> Iterator[at.Predicate]: + yield at.Predicate(lambda x: float(x).is_integer()) + + yield Case(Annotated[float, MyCustomGroupedMetadata()], [0, 2.0], [0.01, 1.5]) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/antlr4_python3_runtime-4.11.0.dist-info/INSTALLER b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/antlr4_python3_runtime-4.11.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/antlr4_python3_runtime-4.11.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/antlr4_python3_runtime-4.11.0.dist-info/METADATA b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/antlr4_python3_runtime-4.11.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..8c24934219ca6ae2e4330df610ae080c1ad1963b --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/antlr4_python3_runtime-4.11.0.dist-info/METADATA @@ -0,0 +1,10 @@ +Metadata-Version: 2.1 +Name: antlr4-python3-runtime +Version: 4.11.0 +Summary: ANTLR 4.11.0 runtime for Python 3 +Home-page: http://www.antlr.org +Author: Eric Vergnaud, Terence Parr, Sam Harwell +Author-email: eric.vergnaud@wanadoo.fr +License: BSD +Requires-Dist: typing ; python_version < "3.5" + diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/antlr4_python3_runtime-4.11.0.dist-info/RECORD b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/antlr4_python3_runtime-4.11.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..411997a796f41617b6701d7072b03aff63a06c41 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/antlr4_python3_runtime-4.11.0.dist-info/RECORD @@ -0,0 +1,123 @@ +../../../bin/pygrun,sha256=F8g7o1YZkUdt8uydXn4aiEGSwvm4tPYgK5f16JO3egs,247 +antlr4/BufferedTokenStream.py,sha256=_BwmzOH1TO6yL2yC_ZaUzkghq8wzc0UPHfI3UpnZUwM,10780 +antlr4/CommonTokenFactory.py,sha256=Tv16zg_pWD1Dv3IphsxFu8nwWdLeXYcqJ8CC5yHwjH8,2110 +antlr4/CommonTokenStream.py,sha256=NNJHXwRg2_Zn46ZhJyDxZtvZzsPWhb6JjXa7BjM45eg,2770 +antlr4/FileStream.py,sha256=-ZR_-jl_If9IIBYLINIwlQrlTSmu5k1VUKDc3ie7WR4,868 +antlr4/InputStream.py,sha256=sggjE2jEGvSgQmxFvqeeuT3aOVgcH5tS7mMybW8wKS4,2334 +antlr4/IntervalSet.py,sha256=Cd0WKhd_kYbiLYKkDNncgSM19GAuS7OaTOC4-5Yubs4,5965 +antlr4/LL1Analyzer.py,sha256=oJBvO7_S8cAlb_D4qWNxd2IlK0qP4ka-oeoDxx16CZ4,7752 +antlr4/Lexer.py,sha256=C72hqayfkympxb46AcSnhPD9kVZ0quWgboGxa6gcIcg,11542 +antlr4/ListTokenSource.py,sha256=IffLMo7YQnD_CjKryrrgNWSk0q5QSYd7puZyyUk7vOk,5356 +antlr4/Parser.py,sha256=F2Q25z0-__KHfa354KQhDu3ZOVzLFfag3s2ixJ4dl_o,22883 +antlr4/ParserInterpreter.py,sha256=-QU9kn4x3WCQ-LSA99R231HoicTqakiHZ5KM72l-hIo,7206 +antlr4/ParserRuleContext.py,sha256=wHAVdOxMAO5jkUqloTXVzn_xYnJhiHbvvuhZpth0ZF8,6762 +antlr4/PredictionContext.py,sha256=cb4KI6EGpS7sRzJ8UvPEkxphINZuWhyiZ95752g3prI,22977 +antlr4/Recognizer.py,sha256=tMXl-YTlUqLYXfYTfQy7fUX9V5KKXEO96WBTdAb3dgk,5384 +antlr4/RuleContext.py,sha256=GiviRv2k_al1IBgdJOEEoD0ohJaVd-_h5T_CPG_Bsmg,8099 +antlr4/StdinStream.py,sha256=MMSH4zN8T6i_nu-3_TlN-3E4nPM4b5KgK4GT6n_FUQA,303 +antlr4/Token.py,sha256=OtWCab4Ut52X_nLLAA-8x4Zl6xaF6TEN-0033uaoaEo,5206 +antlr4/TokenStreamRewriter.py,sha256=cuErQTrXwC_0kqVv3MsTWGZSm-E1Vy1yzA-3SOhKd_s,10324 +antlr4/Utils.py,sha256=Oyg8CJCRL1TrF_QSB_LLlVdWOB4loVcKOgFNT-icO7c,931 +antlr4/__init__.py,sha256=g8UGpflnlMWcAyLtihejzrgAP1Uo3b9GhwfI8QnZjtw,1125 +antlr4/__pycache__/BufferedTokenStream.cpython-310.pyc,, +antlr4/__pycache__/CommonTokenFactory.cpython-310.pyc,, +antlr4/__pycache__/CommonTokenStream.cpython-310.pyc,, +antlr4/__pycache__/FileStream.cpython-310.pyc,, +antlr4/__pycache__/InputStream.cpython-310.pyc,, +antlr4/__pycache__/IntervalSet.cpython-310.pyc,, +antlr4/__pycache__/LL1Analyzer.cpython-310.pyc,, +antlr4/__pycache__/Lexer.cpython-310.pyc,, +antlr4/__pycache__/ListTokenSource.cpython-310.pyc,, +antlr4/__pycache__/Parser.cpython-310.pyc,, +antlr4/__pycache__/ParserInterpreter.cpython-310.pyc,, +antlr4/__pycache__/ParserRuleContext.cpython-310.pyc,, +antlr4/__pycache__/PredictionContext.cpython-310.pyc,, +antlr4/__pycache__/Recognizer.cpython-310.pyc,, +antlr4/__pycache__/RuleContext.cpython-310.pyc,, +antlr4/__pycache__/StdinStream.cpython-310.pyc,, +antlr4/__pycache__/Token.cpython-310.pyc,, +antlr4/__pycache__/TokenStreamRewriter.cpython-310.pyc,, +antlr4/__pycache__/Utils.cpython-310.pyc,, +antlr4/__pycache__/__init__.cpython-310.pyc,, +antlr4/__pycache__/_pygrun.cpython-310.pyc,, +antlr4/_pygrun.py,sha256=0iyrI1ZYoDznH_IZdtqtazTNuyZSvqLz2D4WBnbVNbI,6289 +antlr4/atn/ATN.py,sha256=LYE8kT-D8FpUd5fpOtyOLqvXLFkUSa83TVFowhCWAiY,5789 +antlr4/atn/ATNConfig.py,sha256=tNdIC6_GrxXllHBx3npAWyDh6KrohLZDV_XyPrydRMY,6565 +antlr4/atn/ATNConfigSet.py,sha256=qRzVsBeMqk2txjG3DrGptwF6Vb2hHC5w3umkSL0GNJw,8312 +antlr4/atn/ATNDeserializationOptions.py,sha256=lUV_bGW6mxj7t20esda5Yv-X9m-U_x1-0xaLifhXIPo,1010 +antlr4/atn/ATNDeserializer.py,sha256=3VDf5ToU5cVwq1j-nCsMhhVQVu2SzrjGfdhZcWriHZ0,18958 +antlr4/atn/ATNSimulator.py,sha256=mDc-G3GF3kSeqpfGDabUOLJ0WLVTqibxZlkvXQYmBRk,2298 +antlr4/atn/ATNState.py,sha256=NbndISWUwFDF_vuBfbTiZZ8GPHoQa6UXdqbD-yjJE7c,7663 +antlr4/atn/ATNType.py,sha256=xgv8AMVU7tc07U73_hRTm1AiZ7MvGhoaP5fTiOrrCGg,422 +antlr4/atn/LexerATNSimulator.py,sha256=kYXRwUvHptSRU8T_K9pSrGlCk9YypWeHlAcjgry1VVo,25465 +antlr4/atn/LexerAction.py,sha256=KUeJwKekBch0m1poSPskHIh-15dcKAG4lR7zlq98tzc,10014 +antlr4/atn/LexerActionExecutor.py,sha256=7rlg17THcwLsuTmh7NsLrTbRH4DTrm8qIdW9_235CEc,6420 +antlr4/atn/ParserATNSimulator.py,sha256=IKCzsDLcznROSVojU-daAygKr3svl0DmK5DhkUllASY,80365 +antlr4/atn/PredictionMode.py,sha256=i8B7MULA7v-qbXeCY_xp6sgi21kHM6kybqIrG6rSrro,22486 +antlr4/atn/SemanticContext.py,sha256=5MB8uOBfsQEIPZMN6yw_meokK_uxUWI6ZjjpT1Agn7E,10561 +antlr4/atn/Transition.py,sha256=ZAsEFpa5I_n-zxD6U-DauM5_33jFK65x3PWu6-NW0RA,8762 +antlr4/atn/__init__.py,sha256=gsnQdtTH8IUgCiVUpQfzhxx2pFRvksW76SjwIk3fYSk,28 +antlr4/atn/__pycache__/ATN.cpython-310.pyc,, +antlr4/atn/__pycache__/ATNConfig.cpython-310.pyc,, +antlr4/atn/__pycache__/ATNConfigSet.cpython-310.pyc,, +antlr4/atn/__pycache__/ATNDeserializationOptions.cpython-310.pyc,, +antlr4/atn/__pycache__/ATNDeserializer.cpython-310.pyc,, +antlr4/atn/__pycache__/ATNSimulator.cpython-310.pyc,, +antlr4/atn/__pycache__/ATNState.cpython-310.pyc,, +antlr4/atn/__pycache__/ATNType.cpython-310.pyc,, +antlr4/atn/__pycache__/LexerATNSimulator.cpython-310.pyc,, +antlr4/atn/__pycache__/LexerAction.cpython-310.pyc,, +antlr4/atn/__pycache__/LexerActionExecutor.cpython-310.pyc,, +antlr4/atn/__pycache__/ParserATNSimulator.cpython-310.pyc,, +antlr4/atn/__pycache__/PredictionMode.cpython-310.pyc,, +antlr4/atn/__pycache__/SemanticContext.cpython-310.pyc,, +antlr4/atn/__pycache__/Transition.cpython-310.pyc,, +antlr4/atn/__pycache__/__init__.cpython-310.pyc,, +antlr4/dfa/DFA.py,sha256=weIh0uaRfakP12mFvHo7U0tqO3GONV3-nHFkc2xk-ZE,5388 +antlr4/dfa/DFASerializer.py,sha256=1st_HO85yXLYy7gInTEnkztgA6am4CT-yReh-mazp9E,2518 +antlr4/dfa/DFAState.py,sha256=R7JwKf0GtAEs9J_MD_Y0WKcuzdt0BVX1sow-uv9yFYc,5583 +antlr4/dfa/__init__.py,sha256=gsnQdtTH8IUgCiVUpQfzhxx2pFRvksW76SjwIk3fYSk,28 +antlr4/dfa/__pycache__/DFA.cpython-310.pyc,, +antlr4/dfa/__pycache__/DFASerializer.cpython-310.pyc,, +antlr4/dfa/__pycache__/DFAState.cpython-310.pyc,, +antlr4/dfa/__pycache__/__init__.cpython-310.pyc,, +antlr4/error/DiagnosticErrorListener.py,sha256=EwS2D_Ox6CmvCa16NPJ9ud4QYPHmlPXt6-Wdn1h5Kg8,4430 +antlr4/error/ErrorListener.py,sha256=yP_MDguol4Cj0_pEPyNzeH3v4ZvUjW5iwDjhYTVAHbE,2722 +antlr4/error/ErrorStrategy.py,sha256=0mhzFL57ZVnjKkGrtadta93Zm3NXdF-HW10DVD07VXs,30391 +antlr4/error/Errors.py,sha256=hlKngclBfXdkDiAymhYsvh2OCXlvmHM2kTl_A1vgp-w,6759 +antlr4/error/__init__.py,sha256=gsnQdtTH8IUgCiVUpQfzhxx2pFRvksW76SjwIk3fYSk,28 +antlr4/error/__pycache__/DiagnosticErrorListener.cpython-310.pyc,, +antlr4/error/__pycache__/ErrorListener.cpython-310.pyc,, +antlr4/error/__pycache__/ErrorStrategy.cpython-310.pyc,, +antlr4/error/__pycache__/Errors.cpython-310.pyc,, +antlr4/error/__pycache__/__init__.cpython-310.pyc,, +antlr4/tree/Chunk.py,sha256=oCIZjolLq9xkxtVDROEDxfUGgndcEnsDW0eUmLM7Gpk,695 +antlr4/tree/ParseTreeMatch.py,sha256=Dc6GVWSUqoIAFXUaUZqUwCUlZfTcgUbGLGzNf6QxQvE,4485 +antlr4/tree/ParseTreePattern.py,sha256=rGVYxhs9wYLNoR44sjdiNwXROkooJLwoPJAOxn8K4K8,2835 +antlr4/tree/ParseTreePatternMatcher.py,sha256=HtE9yi1Urr2QPLGLJDBvr0lxv6bjuj9CHl-4clahSe8,16388 +antlr4/tree/RuleTagToken.py,sha256=n4zXcmrrfsGyl91pj5ZYcc_CeKMhPrvYkUdppgMBpbY,2022 +antlr4/tree/TokenTagToken.py,sha256=S3o3DJhfzL5kpClxsKyI-Il-xvuuZQiBAIsLCKFjRHo,1576 +antlr4/tree/Tree.py,sha256=ZI7U_5IxBLm_IrnfJOtb12BCPIWyzfeZtLnhHKVVZIw,5572 +antlr4/tree/Trees.py,sha256=JtQ7cYWmKwI9TIBP6y9XIgjlNS4mYjv3ARwOfwWc5Vg,3968 +antlr4/tree/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +antlr4/tree/__pycache__/Chunk.cpython-310.pyc,, +antlr4/tree/__pycache__/ParseTreeMatch.cpython-310.pyc,, +antlr4/tree/__pycache__/ParseTreePattern.cpython-310.pyc,, +antlr4/tree/__pycache__/ParseTreePatternMatcher.cpython-310.pyc,, +antlr4/tree/__pycache__/RuleTagToken.cpython-310.pyc,, +antlr4/tree/__pycache__/TokenTagToken.cpython-310.pyc,, +antlr4/tree/__pycache__/Tree.cpython-310.pyc,, +antlr4/tree/__pycache__/Trees.cpython-310.pyc,, +antlr4/tree/__pycache__/__init__.cpython-310.pyc,, +antlr4/xpath/XPath.py,sha256=qoihVNLvdI5AFi_M3YWoiBFwGO0-x68pCSNOfHgKQbI,9661 +antlr4/xpath/XPathLexer.py,sha256=Dh-4DSobLUERz6iESERcUBtQaUaYVPwi3C74bWZ_Bzs,3446 +antlr4/xpath/__init__.py,sha256=gsnQdtTH8IUgCiVUpQfzhxx2pFRvksW76SjwIk3fYSk,28 +antlr4/xpath/__pycache__/XPath.cpython-310.pyc,, +antlr4/xpath/__pycache__/XPathLexer.cpython-310.pyc,, +antlr4/xpath/__pycache__/__init__.cpython-310.pyc,, +antlr4_python3_runtime-4.11.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +antlr4_python3_runtime-4.11.0.dist-info/METADATA,sha256=Ndproapb7NxiRP-ltT13tUk85hpHBKt-QKAOO_Q3wzM,291 +antlr4_python3_runtime-4.11.0.dist-info/RECORD,, +antlr4_python3_runtime-4.11.0.dist-info/WHEEL,sha256=G16H4A3IeoQmnOrYV4ueZGKSjhipXx8zc8nu9FGlvMA,92 +antlr4_python3_runtime-4.11.0.dist-info/entry_points.txt,sha256=M2tWLwWgEVV1Djr6ugO3b3902YJIpTDHoM8BFMAt4P4,47 +antlr4_python3_runtime-4.11.0.dist-info/top_level.txt,sha256=OsoZsh9bb30wgXb2zBUjdDwYg46MfV-RVZA6Pk8pcB0,7 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/antlr4_python3_runtime-4.11.0.dist-info/WHEEL b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/antlr4_python3_runtime-4.11.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..becc9a66ea739ba941d48a749e248761cc6e658a --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/antlr4_python3_runtime-4.11.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.37.1) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/antlr4_python3_runtime-4.11.0.dist-info/entry_points.txt b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/antlr4_python3_runtime-4.11.0.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..32c27e63d238254aa07b5fdddce1ff046b291618 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/antlr4_python3_runtime-4.11.0.dist-info/entry_points.txt @@ -0,0 +1,2 @@ +[console_scripts] +pygrun = antlr4._pygrun:main diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/antlr4_python3_runtime-4.11.0.dist-info/top_level.txt b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/antlr4_python3_runtime-4.11.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..3dee19f3e13c2cbbb49b818e6ac67c63f77b865f --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/antlr4_python3_runtime-4.11.0.dist-info/top_level.txt @@ -0,0 +1 @@ +antlr4 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/bcb_execution/Dockerfile b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/bcb_execution/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ef960217b565ff36de5e9b3e465af72d3e882bd6 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/bcb_execution/Dockerfile @@ -0,0 +1,27 @@ +# Based on: https://github.com/bigcode-project/bigcodebench/blob/main/Docker/Evaluate.Dockerfile + +FROM public.ecr.aws/lambda/python:3.10 + +ENV PIP_NO_CACHE_DIR=1 + +RUN yum update -y && yum install -y git gcc-c++ python3-tkinter zip unzip procps R libxml2-devel libxslt-devel + +RUN pip install --upgrade pip +RUN pip install fastapi gunicorn uvicorn[standard] httpx pydantic==2.* plotly + +RUN pip install -I --timeout 2000 -r https://github.com/bigcode-project/bigcodebench-annotation/releases/download/v0.1.0/requirements.txt + +RUN python -m nltk.downloader punkt + +COPY . . + +# For matplotlib import caching in reliability guard +RUN mkdir -p /api/cache/matplotlib +ENV MPLCONFIGDIR=/api/cache/matplotlib + +COPY . ${LAMBDA_TASK_ROOT} + +EXPOSE 8000 + +# Dual-mode startup: Lambda handler OR HTTP server +CMD ["sh", "-c", "if [ \"$AWS_LAMBDA_RUNTIME_API\" ]; then python -m awslambdaric app.handler; else uvicorn app:app --host 0.0.0.0 --port 8000; fi"] \ No newline at end of file diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/bcb_execution/README.md b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/bcb_execution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..17aced45fc9d5282804477aff92fd0313150695e --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/bcb_execution/README.md @@ -0,0 +1,65 @@ +Deploy a lambda verifier for BigCodeBench. Based on [MultiPL-E](../multiple_execution/README.md). + +### Setup + +Make sure you have credentials for the S2 account in `~/.aws/credentials`: + +```sh +[s2] +aws_access_key_id=... +aws_secret_access_key=... +``` + +### Build and deploy + +```sh +# Build + tag docker +docker buildx build --platform linux/amd64 -t codex/bcb:latest . +docker tag codex/bcb:latest 896129387501.dkr.ecr.us-east-1.amazonaws.com/codex/bcb:latest + +# (One time setup) Create ECR registry +aws ecr create-repository --repository-name codex/bcb --region us-east-1 --profile s2 + +# Push to ECR +aws ecr get-login-password --region us-east-1 --profile s2 | docker login --username AWS --password-stdin 896129387501.dkr.ecr.us-east-1.amazonaws.com +docker push 896129387501.dkr.ecr.us-east-1.amazonaws.com/codex/bcb:latest + +# (One time setup) Create lambda func +aws lambda create-function \ + --profile s2 \ + --function-name bcb \ + --package-type Image \ + --code ImageUri=896129387501.dkr.ecr.us-east-1.amazonaws.com/codex/bcb:latest \ + --role arn:aws:iam::896129387501:role/lambda-ex \ + --region us-east-1 + +# Deploy to lambda +aws lambda update-function-code \ + --profile s2 \ + --function-name bcb \ + --image-uri 896129387501.dkr.ecr.us-east-1.amazonaws.com/codex/bcb:latest \ + --region us-east-1 + +# Update and pin the production lambda +NEW_VERSION=$(aws lambda publish-version \ + --profile s2 \ + --function-name bcb \ + --description "" \ + --region us-east-1 \ + --query 'Version' --output text) + +# (One time setup) Create lambda alias +aws lambda create-alias \ + --profile s2 \ + --function-name bcb \ + --name prod \ + --function-version $NEW_VERSION \ + --region us-east-1 + +aws lambda update-alias \ + --profile s2 \ + --function-name bcb \ + --name prod \ + --function-version $NEW_VERSION \ + --region us-east-1 +``` \ No newline at end of file diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/bcb_execution/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/bcb_execution/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/bcb_execution/app.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/bcb_execution/app.py new file mode 100644 index 0000000000000000000000000000000000000000..40225bc593e47e5bce36cf45456f4831aba4c042 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/bcb_execution/app.py @@ -0,0 +1,85 @@ +import json +from typing import Optional + +from fastapi import FastAPI, HTTPException +from pydantic import BaseModel + +from execution import untrusted_check + + +app = FastAPI(title="BCB Execution Service", version="1.0.0") + + +class BCBExecutionRequest(BaseModel): + solution: str + test: str + res_id: str + task_id: str + entry_point: str + calibrate: bool = True + no_gt: bool = True + min_time_limit: int = 1 + max_as_limit: int = 30 * 1024 + max_data_limit: int = 30 * 1024 + max_stack_limit: int = 10 + gt_time_limit: int = 20 + code_prompt: Optional[str] = None + + +class BCBExecutionResponse(BaseModel): + task_id: str + res_id: str + tested_completion: str + passed: bool + exec_result: str + + +@app.get("/health") +async def health_check(): + return {"status": "healthy"} + + +@app.post("/execute", response_model=BCBExecutionResponse) +async def execute_code(request: BCBExecutionRequest): + try: + solution = request.solution + + if request.calibrate and request.code_prompt: + solution = request.code_prompt + "\n pass\n" + solution + + if not request.no_gt: + raise HTTPException( + status_code=501, + detail="Groundtruth execution is not implemented yet!" + ) + + stat, details = untrusted_check( + code=solution, + test_code=request.test, + entry_point=request.entry_point, + min_time_limit=request.min_time_limit, + max_as_limit=request.max_as_limit, + max_data_limit=request.max_data_limit, + max_stack_limit=request.max_stack_limit, + gt_time_limit=request.gt_time_limit, + ) + + passed = stat == "pass" + + return BCBExecutionResponse( + task_id=request.task_id, + res_id=request.res_id, + tested_completion=solution, + passed=passed, + exec_result=json.dumps(details) if details else stat, + ) + + except Exception as e: + raise HTTPException(status_code=500, detail=str(e)) + + +# Handler for AWS Lambda +def handler(event, context): + request = BCBExecutionRequest(**event) + response = execute_code(request) + return json.dumps(response.dict()) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/bcb_execution/execution.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/bcb_execution/execution.py new file mode 100644 index 0000000000000000000000000000000000000000..86147c2e3dd50fc567e5bc9b0cf307208c3b9c2c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/bcb_execution/execution.py @@ -0,0 +1,521 @@ +# Based on: https://github.com/bigcode-project/bigcodebench/blob/main/bigcodebench/eval/utils.py + +# The MIT License +# +# Copyright (c) OpenAI (https://openai.com) +# +# 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. + +import contextlib +import faulthandler +import io +import itertools +import multiprocessing +import os +import platform +import signal +import subprocess +import sys +import tempfile +import time +import types +import unittest +from multiprocessing import Manager +from typing import List, Tuple, Union + +import numpy as np + +TIMEOUT_LIMIT = 120.0 # BCB default is 240.0 + + +@contextlib.contextmanager +def swallow_subprocess_output(): + """Context manager to swallow stdout and stderr for subprocesses.""" + original_popen = subprocess.Popen + original_run = subprocess.run + + def _popen_patch(*args, **kwargs): + if "capture_output" in kwargs and kwargs["capture_output"]: + # Avoid setting stdout or stderr if capture_output is True + kwargs.pop("stdout", None) + kwargs.pop("stderr", None) + else: + kwargs.setdefault("stdout", subprocess.PIPE) + kwargs.setdefault("stderr", subprocess.PIPE) + return original_popen(*args, **kwargs) + + def _run_patch(*args, **kwargs): + if "capture_output" in kwargs and kwargs["capture_output"]: + # Avoid setting stdout or stderr if capture_output is True + kwargs.pop("stdout", None) + kwargs.pop("stderr", None) + else: + kwargs.setdefault("stdout", subprocess.PIPE) + kwargs.setdefault("stderr", subprocess.PIPE) + return original_run(*args, **kwargs) + + subprocess.Popen = _popen_patch + subprocess.run = _run_patch + try: + yield + finally: + subprocess.Popen = original_popen + subprocess.run = original_run + + +@contextlib.contextmanager +def swallow_io(): + stream = WriteOnlyStringIO() + with contextlib.redirect_stdout(stream): + with contextlib.redirect_stderr(stream): + with redirect_stdin(stream): + with swallow_subprocess_output(): + yield + + +@contextlib.contextmanager +def time_limit(seconds: float): + def signal_handler(signum, frame): + raise TimeoutException("Timed out!") + + signal.setitimer(signal.ITIMER_REAL, seconds) + signal.signal(signal.SIGALRM, signal_handler) + try: + yield + finally: + signal.setitimer(signal.ITIMER_REAL, 0) + + +@contextlib.contextmanager +def create_tempdir(): + with tempfile.TemporaryDirectory() as dirname: + with chdir(dirname): + yield dirname + + +@contextlib.contextmanager +def chdir(root): + if root == ".": + yield + return + cwd = os.getcwd() + os.chdir(root) + try: + yield + except BaseException as exc: + raise exc + finally: + os.chdir(cwd) + + +@contextlib.contextmanager +def safe_environment(): + # Save original functions + original_kill = os.kill + original_killpg = os.killpg + original_system = os.system + original_subprocess_call = subprocess.call + original_subprocess_check_output = subprocess.check_output + original_subprocess_run = subprocess.run + original_subprocess_popen = subprocess.Popen + original_os_popen = os.popen + original_os_execv = os.execv + original_os_execvp = os.execvp + original_os_execvpe = os.execvpe + + current_pid = os.getpid() + current_pgid = os.getpgid(current_pid) + manager = multiprocessing.Manager() + child_pids = manager.list() + + def safe_kill(pid, sig): + try: + _ = os.getpgid(pid) + if pid == current_pid or pid in child_pids: + original_kill(pid, sig) + else: + print(f"Prevented attempt to kill PID {pid} with signal {sig}") + except ProcessLookupError: + pass + + def safe_killpg(pgid, sig): + if pgid == current_pgid or pgid in {os.getpgid(pid) for pid in child_pids}: + original_killpg(pgid, sig) + else: + print(f"Prevented attempt to kill PGID {pgid} with signal {sig}") + + def safe_system(command): + print(f"Intercepted system command: {command}") + if "kill" in command or "killall" in command: + return 0 # Simulate successful execution without doing anything + return original_system(command) + + def safe_subprocess_call(command, *args, **kwargs): + print(f"Intercepted subprocess call: {command}") + if "kill" in command or "killall" in command: + return 0 # Simulate successful execution without doing anything + return original_subprocess_call(command, *args, **kwargs) + + def safe_subprocess_check_output(command, *args, **kwargs): + print(f"Intercepted command: {command}") + if "ps" in command: + return b"" # Simulate no processes found + return original_subprocess_check_output(command, *args, **kwargs) + + def safe_subprocess_run(*args, **kwargs): + print(f"Intercepted subprocess run command: {args}") + if "kill" in args[0] or "killall" in args[0]: + return subprocess.CompletedProcess(args, 0, b"", b"") # Simulate successful execution + return original_subprocess_run(*args, **kwargs) + + class SafePopen(subprocess.Popen): + def __init__(self, *args, **kwargs): + print(f"Intercepted Popen command: {args}") + kwargs["preexec_fn"] = os.setsid # Start the process in a new session + super().__init__(*args, **kwargs) + child_pids.append(self.pid) + + def communicate(self, *args, **kwargs): + try: + return super().communicate(*args, **kwargs) + except subprocess.TimeoutExpired: + print("Timeout expired, intercepted and returning None") + return None, None + + def kill(self): + print(f"Intercepted kill call for PID {self.pid}") + safe_kill(self.pid, signal.SIGTERM) + + def terminate(self): + print(f"Intercepted terminate call for PID {self.pid}") + safe_kill(self.pid, signal.SIGTERM) + + def safe_os_popen(command): + print(f"Intercepted os.popen command: {command}") + if "kill" in command or "killall" in command: + return os.popen("echo Intercepted") + return original_os_popen(command) + + def safe_exec(*args, **kwargs): + print(f"Intercepted exec command: {args}") + + # Override the risky functions with the safe versions + os.kill = safe_kill + os.killpg = safe_killpg + os.system = safe_system + subprocess.call = safe_subprocess_call + subprocess.check_output = safe_subprocess_check_output + subprocess.run = safe_subprocess_run + subprocess.Popen = SafePopen + os.popen = safe_os_popen + os.execv = safe_exec + os.execvp = safe_exec + os.execvpe = safe_exec + + try: + yield + finally: + for pid in child_pids: + try: + os.kill(pid, signal.SIGTERM) + for _ in range(10): + time.sleep(0.1) + try: + os.kill(pid, 0) + except ProcessLookupError: + break + else: + os.kill(pid, signal.SIGKILL) + except ProcessLookupError: + pass + except Exception as e: + print(f"Error handling process {pid}: {e}") + + os.kill = original_kill + os.killpg = original_killpg + os.system = original_system + subprocess.call = original_subprocess_call + subprocess.check_output = original_subprocess_check_output + subprocess.run = original_subprocess_run + subprocess.Popen = original_subprocess_popen + os.popen = original_os_popen + os.execv = original_os_execv + os.execvp = original_os_execvp + os.execvpe = original_os_execvpe + + +class TimeoutException(Exception): + pass + + +class WriteOnlyStringIO(io.StringIO): + """StringIO that throws an exception when it's read from""" + + def read(self, *args, **kwargs): + raise IOError + + def readline(self, *args, **kwargs): + raise IOError + + def readlines(self, *args, **kwargs): + raise IOError + + def readable(self, *args, **kwargs): + """Returns True if the IO object can be read.""" + return False + + +class redirect_stdin(contextlib._RedirectStream): # type: ignore + _stream = "stdin" + + +def reliability_guard(max_as_limit, max_data_limit, max_stack_limit): + """ + This disables various destructive functions and prevents the generated code + from interfering with the test (e.g. fork bomb, killing other processes, + removing filesystem files, etc.) + + WARNING + This function is NOT a security sandbox. Untrusted code, including, model- + generated code, should not be blindly executed outside of one. See the + Codex paper for more information about OpenAI's code sandbox, and proceed + with caution. + """ + + import os + import time + + os.environ["TZ"] = "UTC" + time.tzset() + + os.environ["OMP_NUM_THREADS"] = "1" + os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" + os.environ["TF_ENABLE_ONEDNN_OPTS"] = "0" + + if max_as_limit and max_data_limit and max_stack_limit: + import resource + + max_as_limit = max_as_limit * 1024 * 1024 + max_data_limit = max_data_limit * 1024 * 1024 + max_stack_limit = max_stack_limit * 1024 * 1024 + + resource.setrlimit(resource.RLIMIT_AS, (max_as_limit, max_as_limit)) + resource.setrlimit(resource.RLIMIT_DATA, (max_data_limit, max_data_limit)) + if not platform.uname().system == "Darwin": + resource.setrlimit(resource.RLIMIT_STACK, (max_stack_limit, max_stack_limit)) + + faulthandler.disable() + + import builtins + + builtins.exit = None + builtins.quit = None + + import matplotlib.pyplot as plt + + plt.close("all") + + +# unbiased estimator from https://github.com/openai/human-eval +def estimate_pass_at_k( + num_samples: Union[int, List[int], np.ndarray], + num_correct: Union[List[int], np.ndarray], + k: int, +) -> np.ndarray: + """ + Estimates pass@k of each problem and returns them in an array. + """ + + def estimator(n: int, c: int, k: int) -> float: + """ + Calculates 1 - comb(n - c, k) / comb(n, k). + """ + if n - c < k: + return 1.0 + return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1, n + 1)) + + if isinstance(num_samples, int): + num_samples_it = itertools.repeat(num_samples, len(num_correct)) + else: + assert len(num_samples) == len(num_correct) + num_samples_it = iter(num_samples) + + return np.array([estimator(int(n), int(c), k) for n, c in zip(num_samples_it, num_correct)]) + + +PASS = "pass" +FAIL = "fail" +TIMEOUT = "timeout" + +_SUCCESS = 0 +_FAILED = 1 +_TIMEOUT = 2 +_UNKNOWN = 3 + +_mapping = {_SUCCESS: PASS, _FAILED: FAIL, _TIMEOUT: TIMEOUT, _UNKNOWN: None} + + +def is_floats(x) -> bool: + # check if it is float; List[float]; Tuple[float] + if isinstance(x, float): + return True + if isinstance(x, (list, tuple)): + return all(isinstance(i, float) for i in x) + if isinstance(x, np.ndarray): + return x.dtype == np.float64 or x.dtype == np.float32 + return False + + +def unsafe_execute( + entry_point: str, + code: str, + test_code: str, + timeout: float, + max_as_limit: float, + max_data_limit: float, + max_stack_limit: float, + stat, # Value + details, # Array +): + with safe_environment(), create_tempdir(): + # These system calls are needed when cleaning up tempdir. + import builtins + import os + import shutil + + rmtree = shutil.rmtree + rmdir = os.rmdir + chdir = os.chdir + # Disable functionalities that can make destructive changes to the test. + reliability_guard(max_as_limit, max_data_limit, max_stack_limit) + module_name = "__test__" + new_module = types.ModuleType(module_name) + # Set necessary attributes for the module + new_module.__dict__.update( + { + "__builtins__": builtins, + "__file__": f"{module_name}.py", + "__package__": None, + "__doc__": None, + "sys": sys, + "os": os, + "environ": os.environ, + } + ) + + try: + full_code = code + "\n" + test_code + + with swallow_io(): + exec(compile(full_code, f"{module_name}.py", "exec"), new_module.__dict__) + sys.modules[module_name] = new_module + TestCases = getattr(new_module, "TestCases") + loader = unittest.TestLoader() + suite = loader.loadTestsFromTestCase(TestCases) + test_result = unittest.TestResult() + _ = time.time() + with time_limit(timeout): + suite.run(test_result) + + issues = test_result.failures + test_result.errors + for test, trace in issues: + details[test.id().split(".")[-1]] = trace + stat.value = _SUCCESS + except BaseException as e: + details["ALL"] = str(e) + stat.value = _FAILED + # Needed for cleaning up. + shutil.rmtree = rmtree + os.rmdir = rmdir + os.chdir = chdir + + +def untrusted_check( + code: str, + test_code: str, + entry_point: str, + max_as_limit: float, + max_data_limit: float, + max_stack_limit: float, + min_time_limit: float = 10, + gt_time_limit: float = 60, +) -> Tuple[str, np.ndarray]: + min_time_limit = max(min_time_limit, gt_time_limit) + timeout = max(os.getenv("BIGCODEBENCH_TIMEOUT_PER_TASK", TIMEOUT_LIMIT), min_time_limit) + 1 + # shared memory objects + manager = Manager() + stat = manager.Value("i", 0) + manager = Manager() + details = manager.dict() + + p = multiprocessing.Process( + target=unsafe_execute, + args=( + entry_point, + code, + test_code, + timeout, + max_as_limit, + max_data_limit, + max_stack_limit, + stat, + details, + ), + ) + p.start() + p.join(timeout=timeout + 1) + if p.is_alive(): + p.terminate() + time.sleep(0.1) + if p.is_alive(): + p.kill() + time.sleep(0.1) + + stat = _mapping[stat.value] + # convert details to a dict + details = dict(details) + + if not stat: + stat = TIMEOUT + if stat == PASS: + if details: + stat = FAIL + + return stat, details + + +def evaluate_files( + files: List[str], + inputs: List, + entry_point: str, + min_time_limit: float = 0.1, + gt_time_limit_factor: float = 2.0, +) -> List[Tuple[str, List[bool]]]: + ret = [] + # sort files by the id in name (i.e., "../n.py") + files = sorted(files, key=lambda x: int(x.split("/")[-1].split(".")[0])) + for file in files: + code = open(file, "r").read() + stat, det = untrusted_check( + code, + inputs, + entry_point, + ) + ret.append((stat, det.tolist())) + return ret diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/bettermap/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/bettermap/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..415a5d133c938d95699be0d64f1452ff0ed3e857 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/bettermap/__init__.py @@ -0,0 +1 @@ +from .bettermap import * diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/bettermap/bettermap.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/bettermap/bettermap.py new file mode 100644 index 0000000000000000000000000000000000000000..8b2cac142e07e6e06f0479a8bc064099965ddf95 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/bettermap/bettermap.py @@ -0,0 +1,215 @@ +#!/usr/bin/python3 +import io +import sys +from concurrent.futures import ThreadPoolExecutor + +import itertools +import multiprocessing as mp +from multiprocessing.connection import Connection +from multiprocessing.context import ForkProcess +from typing import Iterable, List, Optional, Any, Dict, Tuple + +import dill + +from queue import Queue +from threading import Thread + + +mpctx = mp.get_context("fork") + + +def threaded_generator(g, maxsize: int = 16): + q: Queue = Queue(maxsize=maxsize) + + sentinel = object() + + def fill_queue(): + try: + for value in g: + q.put(value) + finally: + q.put(sentinel) + + thread = Thread(name=repr(g), target=fill_queue, daemon=True) + thread.start() + + yield from iter(q.get, sentinel) + + +def slices(n: int, i: Iterable) -> Iterable[List]: + i = iter(i) + while True: + s = list(itertools.islice(i, n)) + if len(s) > 0: + yield s + else: + break + + +def map_per_process( + fn, + input_sequence: Iterable, + *, + serialization_items: Optional[List[Any]] = None, + parallelism: int = mpctx.cpu_count() +) -> Iterable: + if serialization_items is not None and len(serialization_items) > 0: + serialization_ids = [id(o) for o in serialization_items] + class MapPickler(dill.Pickler): + def persistent_id(self, obj): + try: + return serialization_ids.index(id(obj)) + except ValueError: + return None + class MapUnpickler(dill.Unpickler): + def persistent_load(self, pid): + return serialization_items[pid] + else: + MapPickler = dill.Pickler # type: ignore + MapUnpickler = dill.Unpickler # type: ignore + def pickle(o: Any) -> bytes: + with io.BytesIO() as buffer: + pickler = MapPickler(buffer) + pickler.dump(o) + return buffer.getvalue() + def unpickle(b: bytes) -> Any: + with io.BytesIO(b) as buffer: + unpickler = MapUnpickler(buffer) + return unpickler.load() + + pipeno_to_pipe: Dict[int, Connection] = {} + pipeno_to_process: Dict[int, ForkProcess] = {} + + def process_one_item(send_pipe: Connection, item): + try: + processed_item = fn(item) + except Exception as e: + import traceback + send_pipe.send((None, (e, traceback.format_exc()))) + else: + send_pipe.send((pickle(processed_item), None)) + send_pipe.close() + + def yield_from_pipes(pipes: List[Connection]): + for pipe in pipes: + result, error = pipe.recv() + pipeno = pipe.fileno() + del pipeno_to_pipe[pipeno] + pipe.close() + + process = pipeno_to_process[pipeno] + process.join() + del pipeno_to_process[pipeno] + + if error is None: + yield unpickle(result) + else: + e, tb = error + sys.stderr.write("".join(tb)) + raise e + + try: + for item in input_sequence: + receive_pipe, send_pipe = mpctx.Pipe(duplex=False) + process = mpctx.Process(target=process_one_item, args=(send_pipe, item)) + pipeno_to_pipe[receive_pipe.fileno()] = receive_pipe + pipeno_to_process[receive_pipe.fileno()] = process + process.start() + + # read out the values + timeout = 0 if len(pipeno_to_process) < parallelism else None + # If we have fewer processes going than we have CPUs, we just pick up the values + # that are done. If we are at the process limit, we wait until one of them is done. + ready_pipes = mp.connection.wait(pipeno_to_pipe.values(), timeout=timeout) + yield from yield_from_pipes(ready_pipes) # type: ignore + + # yield the rest of the items + while len(pipeno_to_process) > 0: + ready_pipes = mp.connection.wait(pipeno_to_pipe.values(), timeout=None) + yield from yield_from_pipes(ready_pipes) # type: ignore + + finally: + for process in pipeno_to_process.values(): + if process.is_alive(): + process.terminate() + + +def ordered_map_per_process( + fn, + input_sequence: Iterable, + *, + serialization_items: Optional[List[Any]] = None +) -> Iterable: + def process_item(item): + index, item = item + return index, fn(item) + results_with_index = map_per_process( + process_item, + enumerate(input_sequence), + serialization_items=serialization_items) + + expected_index = 0 + items_in_wait: List[Tuple[int, Any]] = [] + for item in results_with_index: + index, result = item + if index == expected_index: + yield result + expected_index = index + 1 + + items_in_wait.sort(reverse=True) + while len(items_in_wait) > 0 and items_in_wait[-1][0] == expected_index: + index, result = items_in_wait.pop() + yield result + expected_index = index + 1 + else: + items_in_wait.append(item) + + +def ordered_map_per_thread( + fn, + input_sequence: Iterable, + *, + parallelism: int = mpctx.cpu_count() +) -> Iterable: + executor = ThreadPoolExecutor(max_workers=parallelism) + input_sequence = (executor.submit(fn, item) for item in input_sequence) + input_sequence = threaded_generator(input_sequence, maxsize=parallelism) + for future in input_sequence: + yield future.result() + executor.shutdown() + + +def map_in_chunks( + fn, + input_sequence: Iterable, + *, + chunk_size: int = 10, + serialization_items: Optional[List[Any]] = None +) -> Iterable: + def process_chunk(chunk: List) -> List: + return list(map(fn, chunk)) + + processed_chunks = map_per_process( + process_chunk, + slices(chunk_size, input_sequence), + serialization_items=serialization_items) + for processed_chunk in processed_chunks: + yield from processed_chunk + + +def ordered_map_in_chunks( + fn, + input_sequence: Iterable, + *, + chunk_size: int = 10, + serialization_items: Optional[List[Any]] = None +) -> Iterable: + def process_chunk(chunk: List) -> List: + return list(map(fn, chunk)) + + processed_chunks = ordered_map_per_process( + process_chunk, + slices(chunk_size, input_sequence), + serialization_items=serialization_items) + for processed_chunk in processed_chunks: + yield from processed_chunk diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c99ec3d481788c39ea12dc57e4b61547176c8e88 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/__init__.py @@ -0,0 +1,14 @@ +__all__ = ['FFI', 'VerificationError', 'VerificationMissing', 'CDefError', + 'FFIError'] + +from .api import FFI +from .error import CDefError, FFIError, VerificationError, VerificationMissing +from .error import PkgConfigError + +__version__ = "2.0.0" +__version_info__ = (2, 0, 0) + +# The verifier module file names are based on the CRC32 of a string that +# contains the following version number. It may be older than __version__ +# if nothing is clearly incompatible. +__version_verifier_modules__ = "0.8.6" diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/_cffi_errors.h b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/_cffi_errors.h new file mode 100644 index 0000000000000000000000000000000000000000..158e0590346a9a8b2ab047ac1bd23bcb3af21398 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/_cffi_errors.h @@ -0,0 +1,149 @@ +#ifndef CFFI_MESSAGEBOX +# ifdef _MSC_VER +# define CFFI_MESSAGEBOX 1 +# else +# define CFFI_MESSAGEBOX 0 +# endif +#endif + + +#if CFFI_MESSAGEBOX +/* Windows only: logic to take the Python-CFFI embedding logic + initialization errors and display them in a background thread + with MessageBox. The idea is that if the whole program closes + as a result of this problem, then likely it is already a console + program and you can read the stderr output in the console too. + If it is not a console program, then it will likely show its own + dialog to complain, or generally not abruptly close, and for this + case the background thread should stay alive. +*/ +static void *volatile _cffi_bootstrap_text; + +static PyObject *_cffi_start_error_capture(void) +{ + PyObject *result = NULL; + PyObject *x, *m, *bi; + + if (InterlockedCompareExchangePointer(&_cffi_bootstrap_text, + (void *)1, NULL) != NULL) + return (PyObject *)1; + + m = PyImport_AddModule("_cffi_error_capture"); + if (m == NULL) + goto error; + + result = PyModule_GetDict(m); + if (result == NULL) + goto error; + +#if PY_MAJOR_VERSION >= 3 + bi = PyImport_ImportModule("builtins"); +#else + bi = PyImport_ImportModule("__builtin__"); +#endif + if (bi == NULL) + goto error; + PyDict_SetItemString(result, "__builtins__", bi); + Py_DECREF(bi); + + x = PyRun_String( + "import sys\n" + "class FileLike:\n" + " def write(self, x):\n" + " try:\n" + " of.write(x)\n" + " except: pass\n" + " self.buf += x\n" + " def flush(self):\n" + " pass\n" + "fl = FileLike()\n" + "fl.buf = ''\n" + "of = sys.stderr\n" + "sys.stderr = fl\n" + "def done():\n" + " sys.stderr = of\n" + " return fl.buf\n", /* make sure the returned value stays alive */ + Py_file_input, + result, result); + Py_XDECREF(x); + + error: + if (PyErr_Occurred()) + { + PyErr_WriteUnraisable(Py_None); + PyErr_Clear(); + } + return result; +} + +#pragma comment(lib, "user32.lib") + +static DWORD WINAPI _cffi_bootstrap_dialog(LPVOID ignored) +{ + Sleep(666); /* may be interrupted if the whole process is closing */ +#if PY_MAJOR_VERSION >= 3 + MessageBoxW(NULL, (wchar_t *)_cffi_bootstrap_text, + L"Python-CFFI error", + MB_OK | MB_ICONERROR); +#else + MessageBoxA(NULL, (char *)_cffi_bootstrap_text, + "Python-CFFI error", + MB_OK | MB_ICONERROR); +#endif + _cffi_bootstrap_text = NULL; + return 0; +} + +static void _cffi_stop_error_capture(PyObject *ecap) +{ + PyObject *s; + void *text; + + if (ecap == (PyObject *)1) + return; + + if (ecap == NULL) + goto error; + + s = PyRun_String("done()", Py_eval_input, ecap, ecap); + if (s == NULL) + goto error; + + /* Show a dialog box, but in a background thread, and + never show multiple dialog boxes at once. */ +#if PY_MAJOR_VERSION >= 3 + text = PyUnicode_AsWideCharString(s, NULL); +#else + text = PyString_AsString(s); +#endif + + _cffi_bootstrap_text = text; + + if (text != NULL) + { + HANDLE h; + h = CreateThread(NULL, 0, _cffi_bootstrap_dialog, + NULL, 0, NULL); + if (h != NULL) + CloseHandle(h); + } + /* decref the string, but it should stay alive as 'fl.buf' + in the small module above. It will really be freed only if + we later get another similar error. So it's a leak of at + most one copy of the small module. That's fine for this + situation which is usually a "fatal error" anyway. */ + Py_DECREF(s); + PyErr_Clear(); + return; + + error: + _cffi_bootstrap_text = NULL; + PyErr_Clear(); +} + +#else + +static PyObject *_cffi_start_error_capture(void) { return NULL; } +static void _cffi_stop_error_capture(PyObject *ecap) { } + +#endif diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/_cffi_include.h b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/_cffi_include.h new file mode 100644 index 0000000000000000000000000000000000000000..908a1d7343f1869bc8818ca8e786f2c94a4732d2 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/_cffi_include.h @@ -0,0 +1,389 @@ +#define _CFFI_ + +/* We try to define Py_LIMITED_API before including Python.h. + + Mess: we can only define it if Py_DEBUG, Py_TRACE_REFS and + Py_REF_DEBUG are not defined. This is a best-effort approximation: + we can learn about Py_DEBUG from pyconfig.h, but it is unclear if + the same works for the other two macros. Py_DEBUG implies them, + but not the other way around. + + The implementation is messy (issue #350): on Windows, with _MSC_VER, + we have to define Py_LIMITED_API even before including pyconfig.h. + In that case, we guess what pyconfig.h will do to the macros above, + and check our guess after the #include. + + Note that on Windows, with CPython 3.x, you need >= 3.5 and virtualenv + version >= 16.0.0. With older versions of either, you don't get a + copy of PYTHON3.DLL in the virtualenv. We can't check the version of + CPython *before* we even include pyconfig.h. ffi.set_source() puts + a ``#define _CFFI_NO_LIMITED_API'' at the start of this file if it is + running on Windows < 3.5, as an attempt at fixing it, but that's + arguably wrong because it may not be the target version of Python. + Still better than nothing I guess. As another workaround, you can + remove the definition of Py_LIMITED_API here. + + See also 'py_limited_api' in cffi/setuptools_ext.py. +*/ +#if !defined(_CFFI_USE_EMBEDDING) && !defined(Py_LIMITED_API) +# ifdef _MSC_VER +# if !defined(_DEBUG) && !defined(Py_DEBUG) && !defined(Py_TRACE_REFS) && !defined(Py_REF_DEBUG) && !defined(_CFFI_NO_LIMITED_API) +# define Py_LIMITED_API +# endif +# include + /* sanity-check: Py_LIMITED_API will cause crashes if any of these + are also defined. Normally, the Python file PC/pyconfig.h does not + cause any of these to be defined, with the exception that _DEBUG + causes Py_DEBUG. Double-check that. */ +# ifdef Py_LIMITED_API +# if defined(Py_DEBUG) +# error "pyconfig.h unexpectedly defines Py_DEBUG, but Py_LIMITED_API is set" +# endif +# if defined(Py_TRACE_REFS) +# error "pyconfig.h unexpectedly defines Py_TRACE_REFS, but Py_LIMITED_API is set" +# endif +# if defined(Py_REF_DEBUG) +# error "pyconfig.h unexpectedly defines Py_REF_DEBUG, but Py_LIMITED_API is set" +# endif +# endif +# else +# include +# if !defined(Py_DEBUG) && !defined(Py_TRACE_REFS) && !defined(Py_REF_DEBUG) && !defined(_CFFI_NO_LIMITED_API) +# define Py_LIMITED_API +# endif +# endif +#endif + +#include +#ifdef __cplusplus +extern "C" { +#endif +#include +#include "parse_c_type.h" + +/* this block of #ifs should be kept exactly identical between + c/_cffi_backend.c, cffi/vengine_cpy.py, cffi/vengine_gen.py + and cffi/_cffi_include.h */ +#if defined(_MSC_VER) +# include /* for alloca() */ +# if _MSC_VER < 1600 /* MSVC < 2010 */ + typedef __int8 int8_t; + typedef __int16 int16_t; + typedef __int32 int32_t; + typedef __int64 int64_t; + typedef unsigned __int8 uint8_t; + typedef unsigned __int16 uint16_t; + typedef unsigned __int32 uint32_t; + typedef unsigned __int64 uint64_t; + typedef __int8 int_least8_t; + typedef __int16 int_least16_t; + typedef __int32 int_least32_t; + typedef __int64 int_least64_t; + typedef unsigned __int8 uint_least8_t; + typedef unsigned __int16 uint_least16_t; + typedef unsigned __int32 uint_least32_t; + typedef unsigned __int64 uint_least64_t; + typedef __int8 int_fast8_t; + typedef __int16 int_fast16_t; + typedef __int32 int_fast32_t; + typedef __int64 int_fast64_t; + typedef unsigned __int8 uint_fast8_t; + typedef unsigned __int16 uint_fast16_t; + typedef unsigned __int32 uint_fast32_t; + typedef unsigned __int64 uint_fast64_t; + typedef __int64 intmax_t; + typedef unsigned __int64 uintmax_t; +# else +# include +# endif +# if _MSC_VER < 1800 /* MSVC < 2013 */ +# ifndef __cplusplus + typedef unsigned char _Bool; +# endif +# endif +# define _cffi_float_complex_t _Fcomplex /* include for it */ +# define _cffi_double_complex_t _Dcomplex /* include for it */ +#else +# include +# if (defined (__SVR4) && defined (__sun)) || defined(_AIX) || defined(__hpux) +# include +# endif +# define _cffi_float_complex_t float _Complex +# define _cffi_double_complex_t double _Complex +#endif + +#ifdef __GNUC__ +# define _CFFI_UNUSED_FN __attribute__((unused)) +#else +# define _CFFI_UNUSED_FN /* nothing */ +#endif + +#ifdef __cplusplus +# ifndef _Bool + typedef bool _Bool; /* semi-hackish: C++ has no _Bool; bool is builtin */ +# endif +#endif + +/********** CPython-specific section **********/ +#ifndef PYPY_VERSION + + +#if PY_MAJOR_VERSION >= 3 +# define PyInt_FromLong PyLong_FromLong +#endif + +#define _cffi_from_c_double PyFloat_FromDouble +#define _cffi_from_c_float PyFloat_FromDouble +#define _cffi_from_c_long PyInt_FromLong +#define _cffi_from_c_ulong PyLong_FromUnsignedLong +#define _cffi_from_c_longlong PyLong_FromLongLong +#define _cffi_from_c_ulonglong PyLong_FromUnsignedLongLong +#define _cffi_from_c__Bool PyBool_FromLong + +#define _cffi_to_c_double PyFloat_AsDouble +#define _cffi_to_c_float PyFloat_AsDouble + +#define _cffi_from_c_int(x, type) \ + (((type)-1) > 0 ? /* unsigned */ \ + (sizeof(type) < sizeof(long) ? \ + PyInt_FromLong((long)x) : \ + sizeof(type) == sizeof(long) ? \ + PyLong_FromUnsignedLong((unsigned long)x) : \ + PyLong_FromUnsignedLongLong((unsigned long long)x)) : \ + (sizeof(type) <= sizeof(long) ? \ + PyInt_FromLong((long)x) : \ + PyLong_FromLongLong((long long)x))) + +#define _cffi_to_c_int(o, type) \ + ((type)( \ + sizeof(type) == 1 ? (((type)-1) > 0 ? (type)_cffi_to_c_u8(o) \ + : (type)_cffi_to_c_i8(o)) : \ + sizeof(type) == 2 ? (((type)-1) > 0 ? (type)_cffi_to_c_u16(o) \ + : (type)_cffi_to_c_i16(o)) : \ + sizeof(type) == 4 ? (((type)-1) > 0 ? (type)_cffi_to_c_u32(o) \ + : (type)_cffi_to_c_i32(o)) : \ + sizeof(type) == 8 ? (((type)-1) > 0 ? (type)_cffi_to_c_u64(o) \ + : (type)_cffi_to_c_i64(o)) : \ + (Py_FatalError("unsupported size for type " #type), (type)0))) + +#define _cffi_to_c_i8 \ + ((int(*)(PyObject *))_cffi_exports[1]) +#define _cffi_to_c_u8 \ + ((int(*)(PyObject *))_cffi_exports[2]) +#define _cffi_to_c_i16 \ + ((int(*)(PyObject *))_cffi_exports[3]) +#define _cffi_to_c_u16 \ + ((int(*)(PyObject *))_cffi_exports[4]) +#define _cffi_to_c_i32 \ + ((int(*)(PyObject *))_cffi_exports[5]) +#define _cffi_to_c_u32 \ + ((unsigned int(*)(PyObject *))_cffi_exports[6]) +#define _cffi_to_c_i64 \ + ((long long(*)(PyObject *))_cffi_exports[7]) +#define _cffi_to_c_u64 \ + ((unsigned long long(*)(PyObject *))_cffi_exports[8]) +#define _cffi_to_c_char \ + ((int(*)(PyObject *))_cffi_exports[9]) +#define _cffi_from_c_pointer \ + ((PyObject *(*)(char *, struct _cffi_ctypedescr *))_cffi_exports[10]) +#define _cffi_to_c_pointer \ + ((char *(*)(PyObject *, struct _cffi_ctypedescr *))_cffi_exports[11]) +#define _cffi_get_struct_layout \ + not used any more +#define _cffi_restore_errno \ + ((void(*)(void))_cffi_exports[13]) +#define _cffi_save_errno \ + ((void(*)(void))_cffi_exports[14]) +#define _cffi_from_c_char \ + ((PyObject *(*)(char))_cffi_exports[15]) +#define _cffi_from_c_deref \ + ((PyObject *(*)(char *, struct _cffi_ctypedescr *))_cffi_exports[16]) +#define _cffi_to_c \ + ((int(*)(char *, struct _cffi_ctypedescr *, PyObject *))_cffi_exports[17]) +#define _cffi_from_c_struct \ + ((PyObject *(*)(char *, struct _cffi_ctypedescr *))_cffi_exports[18]) +#define _cffi_to_c_wchar_t \ + ((_cffi_wchar_t(*)(PyObject *))_cffi_exports[19]) +#define _cffi_from_c_wchar_t \ + ((PyObject *(*)(_cffi_wchar_t))_cffi_exports[20]) +#define _cffi_to_c_long_double \ + ((long double(*)(PyObject *))_cffi_exports[21]) +#define _cffi_to_c__Bool \ + ((_Bool(*)(PyObject *))_cffi_exports[22]) +#define _cffi_prepare_pointer_call_argument \ + ((Py_ssize_t(*)(struct _cffi_ctypedescr *, \ + PyObject *, char **))_cffi_exports[23]) +#define _cffi_convert_array_from_object \ + ((int(*)(char *, struct _cffi_ctypedescr *, PyObject *))_cffi_exports[24]) +#define _CFFI_CPIDX 25 +#define _cffi_call_python \ + ((void(*)(struct _cffi_externpy_s *, char *))_cffi_exports[_CFFI_CPIDX]) +#define _cffi_to_c_wchar3216_t \ + ((int(*)(PyObject *))_cffi_exports[26]) +#define _cffi_from_c_wchar3216_t \ + ((PyObject *(*)(int))_cffi_exports[27]) +#define _CFFI_NUM_EXPORTS 28 + +struct _cffi_ctypedescr; + +static void *_cffi_exports[_CFFI_NUM_EXPORTS]; + +#define _cffi_type(index) ( \ + assert((((uintptr_t)_cffi_types[index]) & 1) == 0), \ + (struct _cffi_ctypedescr *)_cffi_types[index]) + +static PyObject *_cffi_init(const char *module_name, Py_ssize_t version, + const struct _cffi_type_context_s *ctx) +{ + PyObject *module, *o_arg, *new_module; + void *raw[] = { + (void *)module_name, + (void *)version, + (void *)_cffi_exports, + (void *)ctx, + }; + + module = PyImport_ImportModule("_cffi_backend"); + if (module == NULL) + goto failure; + + o_arg = PyLong_FromVoidPtr((void *)raw); + if (o_arg == NULL) + goto failure; + + new_module = PyObject_CallMethod( + module, (char *)"_init_cffi_1_0_external_module", (char *)"O", o_arg); + + Py_DECREF(o_arg); + Py_DECREF(module); + return new_module; + + failure: + Py_XDECREF(module); + return NULL; +} + + +#ifdef HAVE_WCHAR_H +typedef wchar_t _cffi_wchar_t; +#else +typedef uint16_t _cffi_wchar_t; /* same random pick as _cffi_backend.c */ +#endif + +_CFFI_UNUSED_FN static uint16_t _cffi_to_c_char16_t(PyObject *o) +{ + if (sizeof(_cffi_wchar_t) == 2) + return (uint16_t)_cffi_to_c_wchar_t(o); + else + return (uint16_t)_cffi_to_c_wchar3216_t(o); +} + +_CFFI_UNUSED_FN static PyObject *_cffi_from_c_char16_t(uint16_t x) +{ + if (sizeof(_cffi_wchar_t) == 2) + return _cffi_from_c_wchar_t((_cffi_wchar_t)x); + else + return _cffi_from_c_wchar3216_t((int)x); +} + +_CFFI_UNUSED_FN static int _cffi_to_c_char32_t(PyObject *o) +{ + if (sizeof(_cffi_wchar_t) == 4) + return (int)_cffi_to_c_wchar_t(o); + else + return (int)_cffi_to_c_wchar3216_t(o); +} + +_CFFI_UNUSED_FN static PyObject *_cffi_from_c_char32_t(unsigned int x) +{ + if (sizeof(_cffi_wchar_t) == 4) + return _cffi_from_c_wchar_t((_cffi_wchar_t)x); + else + return _cffi_from_c_wchar3216_t((int)x); +} + +union _cffi_union_alignment_u { + unsigned char m_char; + unsigned short m_short; + unsigned int m_int; + unsigned long m_long; + unsigned long long m_longlong; + float m_float; + double m_double; + long double m_longdouble; +}; + +struct _cffi_freeme_s { + struct _cffi_freeme_s *next; + union _cffi_union_alignment_u alignment; +}; + +_CFFI_UNUSED_FN static int +_cffi_convert_array_argument(struct _cffi_ctypedescr *ctptr, PyObject *arg, + char **output_data, Py_ssize_t datasize, + struct _cffi_freeme_s **freeme) +{ + char *p; + if (datasize < 0) + return -1; + + p = *output_data; + if (p == NULL) { + struct _cffi_freeme_s *fp = (struct _cffi_freeme_s *)PyObject_Malloc( + offsetof(struct _cffi_freeme_s, alignment) + (size_t)datasize); + if (fp == NULL) + return -1; + fp->next = *freeme; + *freeme = fp; + p = *output_data = (char *)&fp->alignment; + } + memset((void *)p, 0, (size_t)datasize); + return _cffi_convert_array_from_object(p, ctptr, arg); +} + +_CFFI_UNUSED_FN static void +_cffi_free_array_arguments(struct _cffi_freeme_s *freeme) +{ + do { + void *p = (void *)freeme; + freeme = freeme->next; + PyObject_Free(p); + } while (freeme != NULL); +} + +/********** end CPython-specific section **********/ +#else +_CFFI_UNUSED_FN +static void (*_cffi_call_python_org)(struct _cffi_externpy_s *, char *); +# define _cffi_call_python _cffi_call_python_org +#endif + + +#define _cffi_array_len(array) (sizeof(array) / sizeof((array)[0])) + +#define _cffi_prim_int(size, sign) \ + ((size) == 1 ? ((sign) ? _CFFI_PRIM_INT8 : _CFFI_PRIM_UINT8) : \ + (size) == 2 ? ((sign) ? _CFFI_PRIM_INT16 : _CFFI_PRIM_UINT16) : \ + (size) == 4 ? ((sign) ? _CFFI_PRIM_INT32 : _CFFI_PRIM_UINT32) : \ + (size) == 8 ? ((sign) ? _CFFI_PRIM_INT64 : _CFFI_PRIM_UINT64) : \ + _CFFI__UNKNOWN_PRIM) + +#define _cffi_prim_float(size) \ + ((size) == sizeof(float) ? _CFFI_PRIM_FLOAT : \ + (size) == sizeof(double) ? _CFFI_PRIM_DOUBLE : \ + (size) == sizeof(long double) ? _CFFI__UNKNOWN_LONG_DOUBLE : \ + _CFFI__UNKNOWN_FLOAT_PRIM) + +#define _cffi_check_int(got, got_nonpos, expected) \ + ((got_nonpos) == (expected <= 0) && \ + (got) == (unsigned long long)expected) + +#ifdef MS_WIN32 +# define _cffi_stdcall __stdcall +#else +# define _cffi_stdcall /* nothing */ +#endif + +#ifdef __cplusplus +} +#endif diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/_embedding.h b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/_embedding.h new file mode 100644 index 0000000000000000000000000000000000000000..64c04f67cacb5d9f2aeb295e0e48a07720d07076 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/_embedding.h @@ -0,0 +1,550 @@ + +/***** Support code for embedding *****/ + +#ifdef __cplusplus +extern "C" { +#endif + + +#if defined(_WIN32) +# define CFFI_DLLEXPORT __declspec(dllexport) +#elif defined(__GNUC__) +# define CFFI_DLLEXPORT __attribute__((visibility("default"))) +#else +# define CFFI_DLLEXPORT /* nothing */ +#endif + + +/* There are two global variables of type _cffi_call_python_fnptr: + + * _cffi_call_python, which we declare just below, is the one called + by ``extern "Python"`` implementations. + + * _cffi_call_python_org, which on CPython is actually part of the + _cffi_exports[] array, is the function pointer copied from + _cffi_backend. If _cffi_start_python() fails, then this is set + to NULL; otherwise, it should never be NULL. + + After initialization is complete, both are equal. However, the + first one remains equal to &_cffi_start_and_call_python until the + very end of initialization, when we are (or should be) sure that + concurrent threads also see a completely initialized world, and + only then is it changed. +*/ +#undef _cffi_call_python +typedef void (*_cffi_call_python_fnptr)(struct _cffi_externpy_s *, char *); +static void _cffi_start_and_call_python(struct _cffi_externpy_s *, char *); +static _cffi_call_python_fnptr _cffi_call_python = &_cffi_start_and_call_python; + + +#ifndef _MSC_VER + /* --- Assuming a GCC not infinitely old --- */ +# define cffi_compare_and_swap(l,o,n) __sync_bool_compare_and_swap(l,o,n) +# define cffi_write_barrier() __sync_synchronize() +# if !defined(__amd64__) && !defined(__x86_64__) && \ + !defined(__i386__) && !defined(__i386) +# define cffi_read_barrier() __sync_synchronize() +# else +# define cffi_read_barrier() (void)0 +# endif +#else + /* --- Windows threads version --- */ +# include +# define cffi_compare_and_swap(l,o,n) \ + (InterlockedCompareExchangePointer(l,n,o) == (o)) +# define cffi_write_barrier() InterlockedCompareExchange(&_cffi_dummy,0,0) +# define cffi_read_barrier() (void)0 +static volatile LONG _cffi_dummy; +#endif + +#ifdef WITH_THREAD +# ifndef _MSC_VER +# include + static pthread_mutex_t _cffi_embed_startup_lock; +# else + static CRITICAL_SECTION _cffi_embed_startup_lock; +# endif + static char _cffi_embed_startup_lock_ready = 0; +#endif + +static void _cffi_acquire_reentrant_mutex(void) +{ + static void *volatile lock = NULL; + + while (!cffi_compare_and_swap(&lock, NULL, (void *)1)) { + /* should ideally do a spin loop instruction here, but + hard to do it portably and doesn't really matter I + think: pthread_mutex_init() should be very fast, and + this is only run at start-up anyway. */ + } + +#ifdef WITH_THREAD + if (!_cffi_embed_startup_lock_ready) { +# ifndef _MSC_VER + pthread_mutexattr_t attr; + pthread_mutexattr_init(&attr); + pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); + pthread_mutex_init(&_cffi_embed_startup_lock, &attr); +# else + InitializeCriticalSection(&_cffi_embed_startup_lock); +# endif + _cffi_embed_startup_lock_ready = 1; + } +#endif + + while (!cffi_compare_and_swap(&lock, (void *)1, NULL)) + ; + +#ifndef _MSC_VER + pthread_mutex_lock(&_cffi_embed_startup_lock); +#else + EnterCriticalSection(&_cffi_embed_startup_lock); +#endif +} + +static void _cffi_release_reentrant_mutex(void) +{ +#ifndef _MSC_VER + pthread_mutex_unlock(&_cffi_embed_startup_lock); +#else + LeaveCriticalSection(&_cffi_embed_startup_lock); +#endif +} + + +/********** CPython-specific section **********/ +#ifndef PYPY_VERSION + +#include "_cffi_errors.h" + + +#define _cffi_call_python_org _cffi_exports[_CFFI_CPIDX] + +PyMODINIT_FUNC _CFFI_PYTHON_STARTUP_FUNC(void); /* forward */ + +static void _cffi_py_initialize(void) +{ + /* XXX use initsigs=0, which "skips initialization registration of + signal handlers, which might be useful when Python is + embedded" according to the Python docs. But review and think + if it should be a user-controllable setting. + + XXX we should also give a way to write errors to a buffer + instead of to stderr. + + XXX if importing 'site' fails, CPython (any version) calls + exit(). Should we try to work around this behavior here? + */ + Py_InitializeEx(0); +} + +static int _cffi_initialize_python(void) +{ + /* This initializes Python, imports _cffi_backend, and then the + present .dll/.so is set up as a CPython C extension module. + */ + int result; + PyGILState_STATE state; + PyObject *pycode=NULL, *global_dict=NULL, *x; + PyObject *builtins; + + state = PyGILState_Ensure(); + + /* Call the initxxx() function from the present module. It will + create and initialize us as a CPython extension module, instead + of letting the startup Python code do it---it might reimport + the same .dll/.so and get maybe confused on some platforms. + It might also have troubles locating the .dll/.so again for all + I know. + */ + (void)_CFFI_PYTHON_STARTUP_FUNC(); + if (PyErr_Occurred()) + goto error; + + /* Now run the Python code provided to ffi.embedding_init_code(). + */ + pycode = Py_CompileString(_CFFI_PYTHON_STARTUP_CODE, + "", + Py_file_input); + if (pycode == NULL) + goto error; + global_dict = PyDict_New(); + if (global_dict == NULL) + goto error; + builtins = PyEval_GetBuiltins(); + if (builtins == NULL) + goto error; + if (PyDict_SetItemString(global_dict, "__builtins__", builtins) < 0) + goto error; + x = PyEval_EvalCode( +#if PY_MAJOR_VERSION < 3 + (PyCodeObject *) +#endif + pycode, global_dict, global_dict); + if (x == NULL) + goto error; + Py_DECREF(x); + + /* Done! Now if we've been called from + _cffi_start_and_call_python() in an ``extern "Python"``, we can + only hope that the Python code did correctly set up the + corresponding @ffi.def_extern() function. Otherwise, the + general logic of ``extern "Python"`` functions (inside the + _cffi_backend module) will find that the reference is still + missing and print an error. + */ + result = 0; + done: + Py_XDECREF(pycode); + Py_XDECREF(global_dict); + PyGILState_Release(state); + return result; + + error:; + { + /* Print as much information as potentially useful. + Debugging load-time failures with embedding is not fun + */ + PyObject *ecap; + PyObject *exception, *v, *tb, *f, *modules, *mod; + PyErr_Fetch(&exception, &v, &tb); + ecap = _cffi_start_error_capture(); + f = PySys_GetObject((char *)"stderr"); + if (f != NULL && f != Py_None) { + PyFile_WriteString( + "Failed to initialize the Python-CFFI embedding logic:\n\n", f); + } + + if (exception != NULL) { + PyErr_NormalizeException(&exception, &v, &tb); + PyErr_Display(exception, v, tb); + } + Py_XDECREF(exception); + Py_XDECREF(v); + Py_XDECREF(tb); + + if (f != NULL && f != Py_None) { + PyFile_WriteString("\nFrom: " _CFFI_MODULE_NAME + "\ncompiled with cffi version: 2.0.0" + "\n_cffi_backend module: ", f); + modules = PyImport_GetModuleDict(); + mod = PyDict_GetItemString(modules, "_cffi_backend"); + if (mod == NULL) { + PyFile_WriteString("not loaded", f); + } + else { + v = PyObject_GetAttrString(mod, "__file__"); + PyFile_WriteObject(v, f, 0); + Py_XDECREF(v); + } + PyFile_WriteString("\nsys.path: ", f); + PyFile_WriteObject(PySys_GetObject((char *)"path"), f, 0); + PyFile_WriteString("\n\n", f); + } + _cffi_stop_error_capture(ecap); + } + result = -1; + goto done; +} + +#if PY_VERSION_HEX < 0x03080000 +PyAPI_DATA(char *) _PyParser_TokenNames[]; /* from CPython */ +#endif + +static int _cffi_carefully_make_gil(void) +{ + /* This does the basic initialization of Python. It can be called + completely concurrently from unrelated threads. It assumes + that we don't hold the GIL before (if it exists), and we don't + hold it afterwards. + + (What it really does used to be completely different in Python 2 + and Python 3, with the Python 2 solution avoiding the spin-lock + around the Py_InitializeEx() call. However, after recent changes + to CPython 2.7 (issue #358) it no longer works. So we use the + Python 3 solution everywhere.) + + This initializes Python by calling Py_InitializeEx(). + Important: this must not be called concurrently at all. + So we use a global variable as a simple spin lock. This global + variable must be from 'libpythonX.Y.so', not from this + cffi-based extension module, because it must be shared from + different cffi-based extension modules. + + In Python < 3.8, we choose + _PyParser_TokenNames[0] as a completely arbitrary pointer value + that is never written to. The default is to point to the + string "ENDMARKER". We change it temporarily to point to the + next character in that string. (Yes, I know it's REALLY + obscure.) + + In Python >= 3.8, this string array is no longer writable, so + instead we pick PyCapsuleType.tp_version_tag. We can't change + Python < 3.8 because someone might use a mixture of cffi + embedded modules, some of which were compiled before this file + changed. + + In Python >= 3.12, this stopped working because that particular + tp_version_tag gets modified during interpreter startup. It's + arguably a bad idea before 3.12 too, but again we can't change + that because someone might use a mixture of cffi embedded + modules, and no-one reported a bug so far. In Python >= 3.12 + we go instead for PyCapsuleType.tp_as_buffer, which is supposed + to always be NULL. We write to it temporarily a pointer to + a struct full of NULLs, which is semantically the same. + */ + +#ifdef WITH_THREAD +# if PY_VERSION_HEX < 0x03080000 + char *volatile *lock = (char *volatile *)_PyParser_TokenNames; + char *old_value, *locked_value; + + while (1) { /* spin loop */ + old_value = *lock; + locked_value = old_value + 1; + if (old_value[0] == 'E') { + assert(old_value[1] == 'N'); + if (cffi_compare_and_swap(lock, old_value, locked_value)) + break; + } + else { + assert(old_value[0] == 'N'); + /* should ideally do a spin loop instruction here, but + hard to do it portably and doesn't really matter I + think: PyEval_InitThreads() should be very fast, and + this is only run at start-up anyway. */ + } + } +# else +# if PY_VERSION_HEX < 0x030C0000 + int volatile *lock = (int volatile *)&PyCapsule_Type.tp_version_tag; + int old_value, locked_value = -42; + assert(!(PyCapsule_Type.tp_flags & Py_TPFLAGS_HAVE_VERSION_TAG)); +# else + static struct ebp_s { PyBufferProcs buf; int mark; } empty_buffer_procs; + empty_buffer_procs.mark = -42; + PyBufferProcs *volatile *lock = (PyBufferProcs *volatile *) + &PyCapsule_Type.tp_as_buffer; + PyBufferProcs *old_value, *locked_value = &empty_buffer_procs.buf; +# endif + + while (1) { /* spin loop */ + old_value = *lock; + if (old_value == 0) { + if (cffi_compare_and_swap(lock, old_value, locked_value)) + break; + } + else { +# if PY_VERSION_HEX < 0x030C0000 + assert(old_value == locked_value); +# else + /* The pointer should point to a possibly different + empty_buffer_procs from another C extension module */ + assert(((struct ebp_s *)old_value)->mark == -42); +# endif + /* should ideally do a spin loop instruction here, but + hard to do it portably and doesn't really matter I + think: PyEval_InitThreads() should be very fast, and + this is only run at start-up anyway. */ + } + } +# endif +#endif + + /* call Py_InitializeEx() */ + if (!Py_IsInitialized()) { + _cffi_py_initialize(); +#if PY_VERSION_HEX < 0x03070000 + PyEval_InitThreads(); +#endif + PyEval_SaveThread(); /* release the GIL */ + /* the returned tstate must be the one that has been stored into the + autoTLSkey by _PyGILState_Init() called from Py_Initialize(). */ + } + else { +#if PY_VERSION_HEX < 0x03070000 + /* PyEval_InitThreads() is always a no-op from CPython 3.7 */ + PyGILState_STATE state = PyGILState_Ensure(); + PyEval_InitThreads(); + PyGILState_Release(state); +#endif + } + +#ifdef WITH_THREAD + /* release the lock */ + while (!cffi_compare_and_swap(lock, locked_value, old_value)) + ; +#endif + + return 0; +} + +/********** end CPython-specific section **********/ + + +#else + + +/********** PyPy-specific section **********/ + +PyMODINIT_FUNC _CFFI_PYTHON_STARTUP_FUNC(const void *[]); /* forward */ + +static struct _cffi_pypy_init_s { + const char *name; + void *func; /* function pointer */ + const char *code; +} _cffi_pypy_init = { + _CFFI_MODULE_NAME, + _CFFI_PYTHON_STARTUP_FUNC, + _CFFI_PYTHON_STARTUP_CODE, +}; + +extern int pypy_carefully_make_gil(const char *); +extern int pypy_init_embedded_cffi_module(int, struct _cffi_pypy_init_s *); + +static int _cffi_carefully_make_gil(void) +{ + return pypy_carefully_make_gil(_CFFI_MODULE_NAME); +} + +static int _cffi_initialize_python(void) +{ + return pypy_init_embedded_cffi_module(0xB011, &_cffi_pypy_init); +} + +/********** end PyPy-specific section **********/ + + +#endif + + +#ifdef __GNUC__ +__attribute__((noinline)) +#endif +static _cffi_call_python_fnptr _cffi_start_python(void) +{ + /* Delicate logic to initialize Python. This function can be + called multiple times concurrently, e.g. when the process calls + its first ``extern "Python"`` functions in multiple threads at + once. It can also be called recursively, in which case we must + ignore it. We also have to consider what occurs if several + different cffi-based extensions reach this code in parallel + threads---it is a different copy of the code, then, and we + can't have any shared global variable unless it comes from + 'libpythonX.Y.so'. + + Idea: + + * _cffi_carefully_make_gil(): "carefully" call + PyEval_InitThreads() (possibly with Py_InitializeEx() first). + + * then we use a (local) custom lock to make sure that a call to this + cffi-based extension will wait if another call to the *same* + extension is running the initialization in another thread. + It is reentrant, so that a recursive call will not block, but + only one from a different thread. + + * then we grab the GIL and (Python 2) we call Py_InitializeEx(). + At this point, concurrent calls to Py_InitializeEx() are not + possible: we have the GIL. + + * do the rest of the specific initialization, which may + temporarily release the GIL but not the custom lock. + Only release the custom lock when we are done. + */ + static char called = 0; + + if (_cffi_carefully_make_gil() != 0) + return NULL; + + _cffi_acquire_reentrant_mutex(); + + /* Here the GIL exists, but we don't have it. We're only protected + from concurrency by the reentrant mutex. */ + + /* This file only initializes the embedded module once, the first + time this is called, even if there are subinterpreters. */ + if (!called) { + called = 1; /* invoke _cffi_initialize_python() only once, + but don't set '_cffi_call_python' right now, + otherwise concurrent threads won't call + this function at all (we need them to wait) */ + if (_cffi_initialize_python() == 0) { + /* now initialization is finished. Switch to the fast-path. */ + + /* We would like nobody to see the new value of + '_cffi_call_python' without also seeing the rest of the + data initialized. However, this is not possible. But + the new value of '_cffi_call_python' is the function + 'cffi_call_python()' from _cffi_backend. So: */ + cffi_write_barrier(); + /* ^^^ we put a write barrier here, and a corresponding + read barrier at the start of cffi_call_python(). This + ensures that after that read barrier, we see everything + done here before the write barrier. + */ + + assert(_cffi_call_python_org != NULL); + _cffi_call_python = (_cffi_call_python_fnptr)_cffi_call_python_org; + } + else { + /* initialization failed. Reset this to NULL, even if it was + already set to some other value. Future calls to + _cffi_start_python() are still forced to occur, and will + always return NULL from now on. */ + _cffi_call_python_org = NULL; + } + } + + _cffi_release_reentrant_mutex(); + + return (_cffi_call_python_fnptr)_cffi_call_python_org; +} + +static +void _cffi_start_and_call_python(struct _cffi_externpy_s *externpy, char *args) +{ + _cffi_call_python_fnptr fnptr; + int current_err = errno; +#ifdef _MSC_VER + int current_lasterr = GetLastError(); +#endif + fnptr = _cffi_start_python(); + if (fnptr == NULL) { + fprintf(stderr, "function %s() called, but initialization code " + "failed. Returning 0.\n", externpy->name); + memset(args, 0, externpy->size_of_result); + } +#ifdef _MSC_VER + SetLastError(current_lasterr); +#endif + errno = current_err; + + if (fnptr != NULL) + fnptr(externpy, args); +} + + +/* The cffi_start_python() function makes sure Python is initialized + and our cffi module is set up. It can be called manually from the + user C code. The same effect is obtained automatically from any + dll-exported ``extern "Python"`` function. This function returns + -1 if initialization failed, 0 if all is OK. */ +_CFFI_UNUSED_FN +static int cffi_start_python(void) +{ + if (_cffi_call_python == &_cffi_start_and_call_python) { + if (_cffi_start_python() == NULL) + return -1; + } + cffi_read_barrier(); + return 0; +} + +#undef cffi_compare_and_swap +#undef cffi_write_barrier +#undef cffi_read_barrier + +#ifdef __cplusplus +} +#endif diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/_imp_emulation.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/_imp_emulation.py new file mode 100644 index 0000000000000000000000000000000000000000..136abdddf9d1276095e6f6724298ac19811c136a --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/_imp_emulation.py @@ -0,0 +1,83 @@ + +try: + # this works on Python < 3.12 + from imp import * + +except ImportError: + # this is a limited emulation for Python >= 3.12. + # Note that this is used only for tests or for the old ffi.verify(). + # This is copied from the source code of Python 3.11. + + from _imp import (acquire_lock, release_lock, + is_builtin, is_frozen) + + from importlib._bootstrap import _load + + from importlib import machinery + import os + import sys + import tokenize + + SEARCH_ERROR = 0 + PY_SOURCE = 1 + PY_COMPILED = 2 + C_EXTENSION = 3 + PY_RESOURCE = 4 + PKG_DIRECTORY = 5 + C_BUILTIN = 6 + PY_FROZEN = 7 + PY_CODERESOURCE = 8 + IMP_HOOK = 9 + + def get_suffixes(): + extensions = [(s, 'rb', C_EXTENSION) + for s in machinery.EXTENSION_SUFFIXES] + source = [(s, 'r', PY_SOURCE) for s in machinery.SOURCE_SUFFIXES] + bytecode = [(s, 'rb', PY_COMPILED) for s in machinery.BYTECODE_SUFFIXES] + return extensions + source + bytecode + + def find_module(name, path=None): + if not isinstance(name, str): + raise TypeError("'name' must be a str, not {}".format(type(name))) + elif not isinstance(path, (type(None), list)): + # Backwards-compatibility + raise RuntimeError("'path' must be None or a list, " + "not {}".format(type(path))) + + if path is None: + if is_builtin(name): + return None, None, ('', '', C_BUILTIN) + elif is_frozen(name): + return None, None, ('', '', PY_FROZEN) + else: + path = sys.path + + for entry in path: + package_directory = os.path.join(entry, name) + for suffix in ['.py', machinery.BYTECODE_SUFFIXES[0]]: + package_file_name = '__init__' + suffix + file_path = os.path.join(package_directory, package_file_name) + if os.path.isfile(file_path): + return None, package_directory, ('', '', PKG_DIRECTORY) + for suffix, mode, type_ in get_suffixes(): + file_name = name + suffix + file_path = os.path.join(entry, file_name) + if os.path.isfile(file_path): + break + else: + continue + break # Break out of outer loop when breaking out of inner loop. + else: + raise ImportError(name, name=name) + + encoding = None + if 'b' not in mode: + with open(file_path, 'rb') as file: + encoding = tokenize.detect_encoding(file.readline)[0] + file = open(file_path, mode, encoding=encoding) + return file, file_path, (suffix, mode, type_) + + def load_dynamic(name, path, file=None): + loader = machinery.ExtensionFileLoader(name, path) + spec = machinery.ModuleSpec(name=name, loader=loader, origin=path) + return _load(spec) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/_shimmed_dist_utils.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/_shimmed_dist_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c3d23128189fc121bff3f86b19330b0ac5ce0a45 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/_shimmed_dist_utils.py @@ -0,0 +1,45 @@ +""" +Temporary shim module to indirect the bits of distutils we need from setuptools/distutils while providing useful +error messages beyond `No module named 'distutils' on Python >= 3.12, or when setuptools' vendored distutils is broken. + +This is a compromise to avoid a hard-dep on setuptools for Python >= 3.12, since many users don't need runtime compilation support from CFFI. +""" +import sys + +try: + # import setuptools first; this is the most robust way to ensure its embedded distutils is available + # (the .pth shim should usually work, but this is even more robust) + import setuptools +except Exception as ex: + if sys.version_info >= (3, 12): + # Python 3.12 has no built-in distutils to fall back on, so any import problem is fatal + raise Exception("This CFFI feature requires setuptools on Python >= 3.12. The setuptools module is missing or non-functional.") from ex + + # silently ignore on older Pythons (support fallback to stdlib distutils where available) +else: + del setuptools + +try: + # bring in just the bits of distutils we need, whether they really came from setuptools or stdlib-embedded distutils + from distutils import log, sysconfig + from distutils.ccompiler import CCompiler + from distutils.command.build_ext import build_ext + from distutils.core import Distribution, Extension + from distutils.dir_util import mkpath + from distutils.errors import DistutilsSetupError, CompileError, LinkError + from distutils.log import set_threshold, set_verbosity + + if sys.platform == 'win32': + try: + # FUTURE: msvc9compiler module was removed in setuptools 74; consider removing, as it's only used by an ancient patch in `recompiler` + from distutils.msvc9compiler import MSVCCompiler + except ImportError: + MSVCCompiler = None +except Exception as ex: + if sys.version_info >= (3, 12): + raise Exception("This CFFI feature requires setuptools on Python >= 3.12. Please install the setuptools package.") from ex + + # anything older, just let the underlying distutils import error fly + raise Exception("This CFFI feature requires distutils. Please install the distutils or setuptools package.") from ex + +del sys diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/api.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/api.py new file mode 100644 index 0000000000000000000000000000000000000000..5a474f3da9288e51df2ab93f7c40372955986265 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/api.py @@ -0,0 +1,967 @@ +import sys, types +from .lock import allocate_lock +from .error import CDefError +from . import model + +try: + callable +except NameError: + # Python 3.1 + from collections import Callable + callable = lambda x: isinstance(x, Callable) + +try: + basestring +except NameError: + # Python 3.x + basestring = str + +_unspecified = object() + + + +class FFI(object): + r''' + The main top-level class that you instantiate once, or once per module. + + Example usage: + + ffi = FFI() + ffi.cdef(""" + int printf(const char *, ...); + """) + + C = ffi.dlopen(None) # standard library + -or- + C = ffi.verify() # use a C compiler: verify the decl above is right + + C.printf("hello, %s!\n", ffi.new("char[]", "world")) + ''' + + def __init__(self, backend=None): + """Create an FFI instance. The 'backend' argument is used to + select a non-default backend, mostly for tests. + """ + if backend is None: + # You need PyPy (>= 2.0 beta), or a CPython (>= 2.6) with + # _cffi_backend.so compiled. + import _cffi_backend as backend + from . import __version__ + if backend.__version__ != __version__: + # bad version! Try to be as explicit as possible. + if hasattr(backend, '__file__'): + # CPython + raise Exception("Version mismatch: this is the 'cffi' package version %s, located in %r. When we import the top-level '_cffi_backend' extension module, we get version %s, located in %r. The two versions should be equal; check your installation." % ( + __version__, __file__, + backend.__version__, backend.__file__)) + else: + # PyPy + raise Exception("Version mismatch: this is the 'cffi' package version %s, located in %r. This interpreter comes with a built-in '_cffi_backend' module, which is version %s. The two versions should be equal; check your installation." % ( + __version__, __file__, backend.__version__)) + # (If you insist you can also try to pass the option + # 'backend=backend_ctypes.CTypesBackend()', but don't + # rely on it! It's probably not going to work well.) + + from . import cparser + self._backend = backend + self._lock = allocate_lock() + self._parser = cparser.Parser() + self._cached_btypes = {} + self._parsed_types = types.ModuleType('parsed_types').__dict__ + self._new_types = types.ModuleType('new_types').__dict__ + self._function_caches = [] + self._libraries = [] + self._cdefsources = [] + self._included_ffis = [] + self._windows_unicode = None + self._init_once_cache = {} + self._cdef_version = None + self._embedding = None + self._typecache = model.get_typecache(backend) + if hasattr(backend, 'set_ffi'): + backend.set_ffi(self) + for name in list(backend.__dict__): + if name.startswith('RTLD_'): + setattr(self, name, getattr(backend, name)) + # + with self._lock: + self.BVoidP = self._get_cached_btype(model.voidp_type) + self.BCharA = self._get_cached_btype(model.char_array_type) + if isinstance(backend, types.ModuleType): + # _cffi_backend: attach these constants to the class + if not hasattr(FFI, 'NULL'): + FFI.NULL = self.cast(self.BVoidP, 0) + FFI.CData, FFI.CType = backend._get_types() + else: + # ctypes backend: attach these constants to the instance + self.NULL = self.cast(self.BVoidP, 0) + self.CData, self.CType = backend._get_types() + self.buffer = backend.buffer + + def cdef(self, csource, override=False, packed=False, pack=None): + """Parse the given C source. This registers all declared functions, + types, and global variables. The functions and global variables can + then be accessed via either 'ffi.dlopen()' or 'ffi.verify()'. + The types can be used in 'ffi.new()' and other functions. + If 'packed' is specified as True, all structs declared inside this + cdef are packed, i.e. laid out without any field alignment at all. + Alternatively, 'pack' can be a small integer, and requests for + alignment greater than that are ignored (pack=1 is equivalent to + packed=True). + """ + self._cdef(csource, override=override, packed=packed, pack=pack) + + def embedding_api(self, csource, packed=False, pack=None): + self._cdef(csource, packed=packed, pack=pack, dllexport=True) + if self._embedding is None: + self._embedding = '' + + def _cdef(self, csource, override=False, **options): + if not isinstance(csource, str): # unicode, on Python 2 + if not isinstance(csource, basestring): + raise TypeError("cdef() argument must be a string") + csource = csource.encode('ascii') + with self._lock: + self._cdef_version = object() + self._parser.parse(csource, override=override, **options) + self._cdefsources.append(csource) + if override: + for cache in self._function_caches: + cache.clear() + finishlist = self._parser._recomplete + if finishlist: + self._parser._recomplete = [] + for tp in finishlist: + tp.finish_backend_type(self, finishlist) + + def dlopen(self, name, flags=0): + """Load and return a dynamic library identified by 'name'. + The standard C library can be loaded by passing None. + Note that functions and types declared by 'ffi.cdef()' are not + linked to a particular library, just like C headers; in the + library we only look for the actual (untyped) symbols. + """ + if not (isinstance(name, basestring) or + name is None or + isinstance(name, self.CData)): + raise TypeError("dlopen(name): name must be a file name, None, " + "or an already-opened 'void *' handle") + with self._lock: + lib, function_cache = _make_ffi_library(self, name, flags) + self._function_caches.append(function_cache) + self._libraries.append(lib) + return lib + + def dlclose(self, lib): + """Close a library obtained with ffi.dlopen(). After this call, + access to functions or variables from the library will fail + (possibly with a segmentation fault). + """ + type(lib).__cffi_close__(lib) + + def _typeof_locked(self, cdecl): + # call me with the lock! + key = cdecl + if key in self._parsed_types: + return self._parsed_types[key] + # + if not isinstance(cdecl, str): # unicode, on Python 2 + cdecl = cdecl.encode('ascii') + # + type = self._parser.parse_type(cdecl) + really_a_function_type = type.is_raw_function + if really_a_function_type: + type = type.as_function_pointer() + btype = self._get_cached_btype(type) + result = btype, really_a_function_type + self._parsed_types[key] = result + return result + + def _typeof(self, cdecl, consider_function_as_funcptr=False): + # string -> ctype object + try: + result = self._parsed_types[cdecl] + except KeyError: + with self._lock: + result = self._typeof_locked(cdecl) + # + btype, really_a_function_type = result + if really_a_function_type and not consider_function_as_funcptr: + raise CDefError("the type %r is a function type, not a " + "pointer-to-function type" % (cdecl,)) + return btype + + def typeof(self, cdecl): + """Parse the C type given as a string and return the + corresponding object. + It can also be used on 'cdata' instance to get its C type. + """ + if isinstance(cdecl, basestring): + return self._typeof(cdecl) + if isinstance(cdecl, self.CData): + return self._backend.typeof(cdecl) + if isinstance(cdecl, types.BuiltinFunctionType): + res = _builtin_function_type(cdecl) + if res is not None: + return res + if (isinstance(cdecl, types.FunctionType) + and hasattr(cdecl, '_cffi_base_type')): + with self._lock: + return self._get_cached_btype(cdecl._cffi_base_type) + raise TypeError(type(cdecl)) + + def sizeof(self, cdecl): + """Return the size in bytes of the argument. It can be a + string naming a C type, or a 'cdata' instance. + """ + if isinstance(cdecl, basestring): + BType = self._typeof(cdecl) + return self._backend.sizeof(BType) + else: + return self._backend.sizeof(cdecl) + + def alignof(self, cdecl): + """Return the natural alignment size in bytes of the C type + given as a string. + """ + if isinstance(cdecl, basestring): + cdecl = self._typeof(cdecl) + return self._backend.alignof(cdecl) + + def offsetof(self, cdecl, *fields_or_indexes): + """Return the offset of the named field inside the given + structure or array, which must be given as a C type name. + You can give several field names in case of nested structures. + You can also give numeric values which correspond to array + items, in case of an array type. + """ + if isinstance(cdecl, basestring): + cdecl = self._typeof(cdecl) + return self._typeoffsetof(cdecl, *fields_or_indexes)[1] + + def new(self, cdecl, init=None): + """Allocate an instance according to the specified C type and + return a pointer to it. The specified C type must be either a + pointer or an array: ``new('X *')`` allocates an X and returns + a pointer to it, whereas ``new('X[n]')`` allocates an array of + n X'es and returns an array referencing it (which works + mostly like a pointer, like in C). You can also use + ``new('X[]', n)`` to allocate an array of a non-constant + length n. + + The memory is initialized following the rules of declaring a + global variable in C: by default it is zero-initialized, but + an explicit initializer can be given which can be used to + fill all or part of the memory. + + When the returned object goes out of scope, the memory + is freed. In other words the returned object has + ownership of the value of type 'cdecl' that it points to. This + means that the raw data can be used as long as this object is + kept alive, but must not be used for a longer time. Be careful + about that when copying the pointer to the memory somewhere + else, e.g. into another structure. + """ + if isinstance(cdecl, basestring): + cdecl = self._typeof(cdecl) + return self._backend.newp(cdecl, init) + + def new_allocator(self, alloc=None, free=None, + should_clear_after_alloc=True): + """Return a new allocator, i.e. a function that behaves like ffi.new() + but uses the provided low-level 'alloc' and 'free' functions. + + 'alloc' is called with the size as argument. If it returns NULL, a + MemoryError is raised. 'free' is called with the result of 'alloc' + as argument. Both can be either Python function or directly C + functions. If 'free' is None, then no free function is called. + If both 'alloc' and 'free' are None, the default is used. + + If 'should_clear_after_alloc' is set to False, then the memory + returned by 'alloc' is assumed to be already cleared (or you are + fine with garbage); otherwise CFFI will clear it. + """ + compiled_ffi = self._backend.FFI() + allocator = compiled_ffi.new_allocator(alloc, free, + should_clear_after_alloc) + def allocate(cdecl, init=None): + if isinstance(cdecl, basestring): + cdecl = self._typeof(cdecl) + return allocator(cdecl, init) + return allocate + + def cast(self, cdecl, source): + """Similar to a C cast: returns an instance of the named C + type initialized with the given 'source'. The source is + casted between integers or pointers of any type. + """ + if isinstance(cdecl, basestring): + cdecl = self._typeof(cdecl) + return self._backend.cast(cdecl, source) + + def string(self, cdata, maxlen=-1): + """Return a Python string (or unicode string) from the 'cdata'. + If 'cdata' is a pointer or array of characters or bytes, returns + the null-terminated string. The returned string extends until + the first null character, or at most 'maxlen' characters. If + 'cdata' is an array then 'maxlen' defaults to its length. + + If 'cdata' is a pointer or array of wchar_t, returns a unicode + string following the same rules. + + If 'cdata' is a single character or byte or a wchar_t, returns + it as a string or unicode string. + + If 'cdata' is an enum, returns the value of the enumerator as a + string, or 'NUMBER' if the value is out of range. + """ + return self._backend.string(cdata, maxlen) + + def unpack(self, cdata, length): + """Unpack an array of C data of the given length, + returning a Python string/unicode/list. + + If 'cdata' is a pointer to 'char', returns a byte string. + It does not stop at the first null. This is equivalent to: + ffi.buffer(cdata, length)[:] + + If 'cdata' is a pointer to 'wchar_t', returns a unicode string. + 'length' is measured in wchar_t's; it is not the size in bytes. + + If 'cdata' is a pointer to anything else, returns a list of + 'length' items. This is a faster equivalent to: + [cdata[i] for i in range(length)] + """ + return self._backend.unpack(cdata, length) + + #def buffer(self, cdata, size=-1): + # """Return a read-write buffer object that references the raw C data + # pointed to by the given 'cdata'. The 'cdata' must be a pointer or + # an array. Can be passed to functions expecting a buffer, or directly + # manipulated with: + # + # buf[:] get a copy of it in a regular string, or + # buf[idx] as a single character + # buf[:] = ... + # buf[idx] = ... change the content + # """ + # note that 'buffer' is a type, set on this instance by __init__ + + def from_buffer(self, cdecl, python_buffer=_unspecified, + require_writable=False): + """Return a cdata of the given type pointing to the data of the + given Python object, which must support the buffer interface. + Note that this is not meant to be used on the built-in types + str or unicode (you can build 'char[]' arrays explicitly) + but only on objects containing large quantities of raw data + in some other format, like 'array.array' or numpy arrays. + + The first argument is optional and default to 'char[]'. + """ + if python_buffer is _unspecified: + cdecl, python_buffer = self.BCharA, cdecl + elif isinstance(cdecl, basestring): + cdecl = self._typeof(cdecl) + return self._backend.from_buffer(cdecl, python_buffer, + require_writable) + + def memmove(self, dest, src, n): + """ffi.memmove(dest, src, n) copies n bytes of memory from src to dest. + + Like the C function memmove(), the memory areas may overlap; + apart from that it behaves like the C function memcpy(). + + 'src' can be any cdata ptr or array, or any Python buffer object. + 'dest' can be any cdata ptr or array, or a writable Python buffer + object. The size to copy, 'n', is always measured in bytes. + + Unlike other methods, this one supports all Python buffer including + byte strings and bytearrays---but it still does not support + non-contiguous buffers. + """ + return self._backend.memmove(dest, src, n) + + def callback(self, cdecl, python_callable=None, error=None, onerror=None): + """Return a callback object or a decorator making such a + callback object. 'cdecl' must name a C function pointer type. + The callback invokes the specified 'python_callable' (which may + be provided either directly or via a decorator). Important: the + callback object must be manually kept alive for as long as the + callback may be invoked from the C level. + """ + def callback_decorator_wrap(python_callable): + if not callable(python_callable): + raise TypeError("the 'python_callable' argument " + "is not callable") + return self._backend.callback(cdecl, python_callable, + error, onerror) + if isinstance(cdecl, basestring): + cdecl = self._typeof(cdecl, consider_function_as_funcptr=True) + if python_callable is None: + return callback_decorator_wrap # decorator mode + else: + return callback_decorator_wrap(python_callable) # direct mode + + def getctype(self, cdecl, replace_with=''): + """Return a string giving the C type 'cdecl', which may be itself + a string or a object. If 'replace_with' is given, it gives + extra text to append (or insert for more complicated C types), like + a variable name, or '*' to get actually the C type 'pointer-to-cdecl'. + """ + if isinstance(cdecl, basestring): + cdecl = self._typeof(cdecl) + replace_with = replace_with.strip() + if (replace_with.startswith('*') + and '&[' in self._backend.getcname(cdecl, '&')): + replace_with = '(%s)' % replace_with + elif replace_with and not replace_with[0] in '[(': + replace_with = ' ' + replace_with + return self._backend.getcname(cdecl, replace_with) + + def gc(self, cdata, destructor, size=0): + """Return a new cdata object that points to the same + data. Later, when this new cdata object is garbage-collected, + 'destructor(old_cdata_object)' will be called. + + The optional 'size' gives an estimate of the size, used to + trigger the garbage collection more eagerly. So far only used + on PyPy. It tells the GC that the returned object keeps alive + roughly 'size' bytes of external memory. + """ + return self._backend.gcp(cdata, destructor, size) + + def _get_cached_btype(self, type): + assert self._lock.acquire(False) is False + # call me with the lock! + try: + BType = self._cached_btypes[type] + except KeyError: + finishlist = [] + BType = type.get_cached_btype(self, finishlist) + for type in finishlist: + type.finish_backend_type(self, finishlist) + return BType + + def verify(self, source='', tmpdir=None, **kwargs): + """Verify that the current ffi signatures compile on this + machine, and return a dynamic library object. The dynamic + library can be used to call functions and access global + variables declared in this 'ffi'. The library is compiled + by the C compiler: it gives you C-level API compatibility + (including calling macros). This is unlike 'ffi.dlopen()', + which requires binary compatibility in the signatures. + """ + from .verifier import Verifier, _caller_dir_pycache + # + # If set_unicode(True) was called, insert the UNICODE and + # _UNICODE macro declarations + if self._windows_unicode: + self._apply_windows_unicode(kwargs) + # + # Set the tmpdir here, and not in Verifier.__init__: it picks + # up the caller's directory, which we want to be the caller of + # ffi.verify(), as opposed to the caller of Veritier(). + tmpdir = tmpdir or _caller_dir_pycache() + # + # Make a Verifier() and use it to load the library. + self.verifier = Verifier(self, source, tmpdir, **kwargs) + lib = self.verifier.load_library() + # + # Save the loaded library for keep-alive purposes, even + # if the caller doesn't keep it alive itself (it should). + self._libraries.append(lib) + return lib + + def _get_errno(self): + return self._backend.get_errno() + def _set_errno(self, errno): + self._backend.set_errno(errno) + errno = property(_get_errno, _set_errno, None, + "the value of 'errno' from/to the C calls") + + def getwinerror(self, code=-1): + return self._backend.getwinerror(code) + + def _pointer_to(self, ctype): + with self._lock: + return model.pointer_cache(self, ctype) + + def addressof(self, cdata, *fields_or_indexes): + """Return the address of a . + If 'fields_or_indexes' are given, returns the address of that + field or array item in the structure or array, recursively in + case of nested structures. + """ + try: + ctype = self._backend.typeof(cdata) + except TypeError: + if '__addressof__' in type(cdata).__dict__: + return type(cdata).__addressof__(cdata, *fields_or_indexes) + raise + if fields_or_indexes: + ctype, offset = self._typeoffsetof(ctype, *fields_or_indexes) + else: + if ctype.kind == "pointer": + raise TypeError("addressof(pointer)") + offset = 0 + ctypeptr = self._pointer_to(ctype) + return self._backend.rawaddressof(ctypeptr, cdata, offset) + + def _typeoffsetof(self, ctype, field_or_index, *fields_or_indexes): + ctype, offset = self._backend.typeoffsetof(ctype, field_or_index) + for field1 in fields_or_indexes: + ctype, offset1 = self._backend.typeoffsetof(ctype, field1, 1) + offset += offset1 + return ctype, offset + + def include(self, ffi_to_include): + """Includes the typedefs, structs, unions and enums defined + in another FFI instance. Usage is similar to a #include in C, + where a part of the program might include types defined in + another part for its own usage. Note that the include() + method has no effect on functions, constants and global + variables, which must anyway be accessed directly from the + lib object returned by the original FFI instance. + """ + if not isinstance(ffi_to_include, FFI): + raise TypeError("ffi.include() expects an argument that is also of" + " type cffi.FFI, not %r" % ( + type(ffi_to_include).__name__,)) + if ffi_to_include is self: + raise ValueError("self.include(self)") + with ffi_to_include._lock: + with self._lock: + self._parser.include(ffi_to_include._parser) + self._cdefsources.append('[') + self._cdefsources.extend(ffi_to_include._cdefsources) + self._cdefsources.append(']') + self._included_ffis.append(ffi_to_include) + + def new_handle(self, x): + return self._backend.newp_handle(self.BVoidP, x) + + def from_handle(self, x): + return self._backend.from_handle(x) + + def release(self, x): + self._backend.release(x) + + def set_unicode(self, enabled_flag): + """Windows: if 'enabled_flag' is True, enable the UNICODE and + _UNICODE defines in C, and declare the types like TCHAR and LPTCSTR + to be (pointers to) wchar_t. If 'enabled_flag' is False, + declare these types to be (pointers to) plain 8-bit characters. + This is mostly for backward compatibility; you usually want True. + """ + if self._windows_unicode is not None: + raise ValueError("set_unicode() can only be called once") + enabled_flag = bool(enabled_flag) + if enabled_flag: + self.cdef("typedef wchar_t TBYTE;" + "typedef wchar_t TCHAR;" + "typedef const wchar_t *LPCTSTR;" + "typedef const wchar_t *PCTSTR;" + "typedef wchar_t *LPTSTR;" + "typedef wchar_t *PTSTR;" + "typedef TBYTE *PTBYTE;" + "typedef TCHAR *PTCHAR;") + else: + self.cdef("typedef char TBYTE;" + "typedef char TCHAR;" + "typedef const char *LPCTSTR;" + "typedef const char *PCTSTR;" + "typedef char *LPTSTR;" + "typedef char *PTSTR;" + "typedef TBYTE *PTBYTE;" + "typedef TCHAR *PTCHAR;") + self._windows_unicode = enabled_flag + + def _apply_windows_unicode(self, kwds): + defmacros = kwds.get('define_macros', ()) + if not isinstance(defmacros, (list, tuple)): + raise TypeError("'define_macros' must be a list or tuple") + defmacros = list(defmacros) + [('UNICODE', '1'), + ('_UNICODE', '1')] + kwds['define_macros'] = defmacros + + def _apply_embedding_fix(self, kwds): + # must include an argument like "-lpython2.7" for the compiler + def ensure(key, value): + lst = kwds.setdefault(key, []) + if value not in lst: + lst.append(value) + # + if '__pypy__' in sys.builtin_module_names: + import os + if sys.platform == "win32": + # we need 'libpypy-c.lib'. Current distributions of + # pypy (>= 4.1) contain it as 'libs/python27.lib'. + pythonlib = "python{0[0]}{0[1]}".format(sys.version_info) + if hasattr(sys, 'prefix'): + ensure('library_dirs', os.path.join(sys.prefix, 'libs')) + else: + # we need 'libpypy-c.{so,dylib}', which should be by + # default located in 'sys.prefix/bin' for installed + # systems. + if sys.version_info < (3,): + pythonlib = "pypy-c" + else: + pythonlib = "pypy3-c" + if hasattr(sys, 'prefix'): + ensure('library_dirs', os.path.join(sys.prefix, 'bin')) + # On uninstalled pypy's, the libpypy-c is typically found in + # .../pypy/goal/. + if hasattr(sys, 'prefix'): + ensure('library_dirs', os.path.join(sys.prefix, 'pypy', 'goal')) + else: + if sys.platform == "win32": + template = "python%d%d" + if hasattr(sys, 'gettotalrefcount'): + template += '_d' + else: + try: + import sysconfig + except ImportError: # 2.6 + from cffi._shimmed_dist_utils import sysconfig + template = "python%d.%d" + if sysconfig.get_config_var('DEBUG_EXT'): + template += sysconfig.get_config_var('DEBUG_EXT') + pythonlib = (template % + (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff)) + if hasattr(sys, 'abiflags'): + pythonlib += sys.abiflags + ensure('libraries', pythonlib) + if sys.platform == "win32": + ensure('extra_link_args', '/MANIFEST') + + def set_source(self, module_name, source, source_extension='.c', **kwds): + import os + if hasattr(self, '_assigned_source'): + raise ValueError("set_source() cannot be called several times " + "per ffi object") + if not isinstance(module_name, basestring): + raise TypeError("'module_name' must be a string") + if os.sep in module_name or (os.altsep and os.altsep in module_name): + raise ValueError("'module_name' must not contain '/': use a dotted " + "name to make a 'package.module' location") + self._assigned_source = (str(module_name), source, + source_extension, kwds) + + def set_source_pkgconfig(self, module_name, pkgconfig_libs, source, + source_extension='.c', **kwds): + from . import pkgconfig + if not isinstance(pkgconfig_libs, list): + raise TypeError("the pkgconfig_libs argument must be a list " + "of package names") + kwds2 = pkgconfig.flags_from_pkgconfig(pkgconfig_libs) + pkgconfig.merge_flags(kwds, kwds2) + self.set_source(module_name, source, source_extension, **kwds) + + def distutils_extension(self, tmpdir='build', verbose=True): + from cffi._shimmed_dist_utils import mkpath + from .recompiler import recompile + # + if not hasattr(self, '_assigned_source'): + if hasattr(self, 'verifier'): # fallback, 'tmpdir' ignored + return self.verifier.get_extension() + raise ValueError("set_source() must be called before" + " distutils_extension()") + module_name, source, source_extension, kwds = self._assigned_source + if source is None: + raise TypeError("distutils_extension() is only for C extension " + "modules, not for dlopen()-style pure Python " + "modules") + mkpath(tmpdir) + ext, updated = recompile(self, module_name, + source, tmpdir=tmpdir, extradir=tmpdir, + source_extension=source_extension, + call_c_compiler=False, **kwds) + if verbose: + if updated: + sys.stderr.write("regenerated: %r\n" % (ext.sources[0],)) + else: + sys.stderr.write("not modified: %r\n" % (ext.sources[0],)) + return ext + + def emit_c_code(self, filename): + from .recompiler import recompile + # + if not hasattr(self, '_assigned_source'): + raise ValueError("set_source() must be called before emit_c_code()") + module_name, source, source_extension, kwds = self._assigned_source + if source is None: + raise TypeError("emit_c_code() is only for C extension modules, " + "not for dlopen()-style pure Python modules") + recompile(self, module_name, source, + c_file=filename, call_c_compiler=False, + uses_ffiplatform=False, **kwds) + + def emit_python_code(self, filename): + from .recompiler import recompile + # + if not hasattr(self, '_assigned_source'): + raise ValueError("set_source() must be called before emit_c_code()") + module_name, source, source_extension, kwds = self._assigned_source + if source is not None: + raise TypeError("emit_python_code() is only for dlopen()-style " + "pure Python modules, not for C extension modules") + recompile(self, module_name, source, + c_file=filename, call_c_compiler=False, + uses_ffiplatform=False, **kwds) + + def compile(self, tmpdir='.', verbose=0, target=None, debug=None): + """The 'target' argument gives the final file name of the + compiled DLL. Use '*' to force distutils' choice, suitable for + regular CPython C API modules. Use a file name ending in '.*' + to ask for the system's default extension for dynamic libraries + (.so/.dll/.dylib). + + The default is '*' when building a non-embedded C API extension, + and (module_name + '.*') when building an embedded library. + """ + from .recompiler import recompile + # + if not hasattr(self, '_assigned_source'): + raise ValueError("set_source() must be called before compile()") + module_name, source, source_extension, kwds = self._assigned_source + return recompile(self, module_name, source, tmpdir=tmpdir, + target=target, source_extension=source_extension, + compiler_verbose=verbose, debug=debug, **kwds) + + def init_once(self, func, tag): + # Read _init_once_cache[tag], which is either (False, lock) if + # we're calling the function now in some thread, or (True, result). + # Don't call setdefault() in most cases, to avoid allocating and + # immediately freeing a lock; but still use setdefaut() to avoid + # races. + try: + x = self._init_once_cache[tag] + except KeyError: + x = self._init_once_cache.setdefault(tag, (False, allocate_lock())) + # Common case: we got (True, result), so we return the result. + if x[0]: + return x[1] + # Else, it's a lock. Acquire it to serialize the following tests. + with x[1]: + # Read again from _init_once_cache the current status. + x = self._init_once_cache[tag] + if x[0]: + return x[1] + # Call the function and store the result back. + result = func() + self._init_once_cache[tag] = (True, result) + return result + + def embedding_init_code(self, pysource): + if self._embedding: + raise ValueError("embedding_init_code() can only be called once") + # fix 'pysource' before it gets dumped into the C file: + # - remove empty lines at the beginning, so it starts at "line 1" + # - dedent, if all non-empty lines are indented + # - check for SyntaxErrors + import re + match = re.match(r'\s*\n', pysource) + if match: + pysource = pysource[match.end():] + lines = pysource.splitlines() or [''] + prefix = re.match(r'\s*', lines[0]).group() + for i in range(1, len(lines)): + line = lines[i] + if line.rstrip(): + while not line.startswith(prefix): + prefix = prefix[:-1] + i = len(prefix) + lines = [line[i:]+'\n' for line in lines] + pysource = ''.join(lines) + # + compile(pysource, "cffi_init", "exec") + # + self._embedding = pysource + + def def_extern(self, *args, **kwds): + raise ValueError("ffi.def_extern() is only available on API-mode FFI " + "objects") + + def list_types(self): + """Returns the user type names known to this FFI instance. + This returns a tuple containing three lists of names: + (typedef_names, names_of_structs, names_of_unions) + """ + typedefs = [] + structs = [] + unions = [] + for key in self._parser._declarations: + if key.startswith('typedef '): + typedefs.append(key[8:]) + elif key.startswith('struct '): + structs.append(key[7:]) + elif key.startswith('union '): + unions.append(key[6:]) + typedefs.sort() + structs.sort() + unions.sort() + return (typedefs, structs, unions) + + +def _load_backend_lib(backend, name, flags): + import os + if not isinstance(name, basestring): + if sys.platform != "win32" or name is not None: + return backend.load_library(name, flags) + name = "c" # Windows: load_library(None) fails, but this works + # on Python 2 (backward compatibility hack only) + first_error = None + if '.' in name or '/' in name or os.sep in name: + try: + return backend.load_library(name, flags) + except OSError as e: + first_error = e + import ctypes.util + path = ctypes.util.find_library(name) + if path is None: + if name == "c" and sys.platform == "win32" and sys.version_info >= (3,): + raise OSError("dlopen(None) cannot work on Windows for Python 3 " + "(see http://bugs.python.org/issue23606)") + msg = ("ctypes.util.find_library() did not manage " + "to locate a library called %r" % (name,)) + if first_error is not None: + msg = "%s. Additionally, %s" % (first_error, msg) + raise OSError(msg) + return backend.load_library(path, flags) + +def _make_ffi_library(ffi, libname, flags): + backend = ffi._backend + backendlib = _load_backend_lib(backend, libname, flags) + # + def accessor_function(name): + key = 'function ' + name + tp, _ = ffi._parser._declarations[key] + BType = ffi._get_cached_btype(tp) + value = backendlib.load_function(BType, name) + library.__dict__[name] = value + # + def accessor_variable(name): + key = 'variable ' + name + tp, _ = ffi._parser._declarations[key] + BType = ffi._get_cached_btype(tp) + read_variable = backendlib.read_variable + write_variable = backendlib.write_variable + setattr(FFILibrary, name, property( + lambda self: read_variable(BType, name), + lambda self, value: write_variable(BType, name, value))) + # + def addressof_var(name): + try: + return addr_variables[name] + except KeyError: + with ffi._lock: + if name not in addr_variables: + key = 'variable ' + name + tp, _ = ffi._parser._declarations[key] + BType = ffi._get_cached_btype(tp) + if BType.kind != 'array': + BType = model.pointer_cache(ffi, BType) + p = backendlib.load_function(BType, name) + addr_variables[name] = p + return addr_variables[name] + # + def accessor_constant(name): + raise NotImplementedError("non-integer constant '%s' cannot be " + "accessed from a dlopen() library" % (name,)) + # + def accessor_int_constant(name): + library.__dict__[name] = ffi._parser._int_constants[name] + # + accessors = {} + accessors_version = [False] + addr_variables = {} + # + def update_accessors(): + if accessors_version[0] is ffi._cdef_version: + return + # + for key, (tp, _) in ffi._parser._declarations.items(): + if not isinstance(tp, model.EnumType): + tag, name = key.split(' ', 1) + if tag == 'function': + accessors[name] = accessor_function + elif tag == 'variable': + accessors[name] = accessor_variable + elif tag == 'constant': + accessors[name] = accessor_constant + else: + for i, enumname in enumerate(tp.enumerators): + def accessor_enum(name, tp=tp, i=i): + tp.check_not_partial() + library.__dict__[name] = tp.enumvalues[i] + accessors[enumname] = accessor_enum + for name in ffi._parser._int_constants: + accessors.setdefault(name, accessor_int_constant) + accessors_version[0] = ffi._cdef_version + # + def make_accessor(name): + with ffi._lock: + if name in library.__dict__ or name in FFILibrary.__dict__: + return # added by another thread while waiting for the lock + if name not in accessors: + update_accessors() + if name not in accessors: + raise AttributeError(name) + accessors[name](name) + # + class FFILibrary(object): + def __getattr__(self, name): + make_accessor(name) + return getattr(self, name) + def __setattr__(self, name, value): + try: + property = getattr(self.__class__, name) + except AttributeError: + make_accessor(name) + setattr(self, name, value) + else: + property.__set__(self, value) + def __dir__(self): + with ffi._lock: + update_accessors() + return accessors.keys() + def __addressof__(self, name): + if name in library.__dict__: + return library.__dict__[name] + if name in FFILibrary.__dict__: + return addressof_var(name) + make_accessor(name) + if name in library.__dict__: + return library.__dict__[name] + if name in FFILibrary.__dict__: + return addressof_var(name) + raise AttributeError("cffi library has no function or " + "global variable named '%s'" % (name,)) + def __cffi_close__(self): + backendlib.close_lib() + self.__dict__.clear() + # + if isinstance(libname, basestring): + try: + if not isinstance(libname, str): # unicode, on Python 2 + libname = libname.encode('utf-8') + FFILibrary.__name__ = 'FFILibrary_%s' % libname + except UnicodeError: + pass + library = FFILibrary() + return library, library.__dict__ + +def _builtin_function_type(func): + # a hack to make at least ffi.typeof(builtin_function) work, + # if the builtin function was obtained by 'vengine_cpy'. + import sys + try: + module = sys.modules[func.__module__] + ffi = module._cffi_original_ffi + types_of_builtin_funcs = module._cffi_types_of_builtin_funcs + tp = types_of_builtin_funcs[func] + except (KeyError, AttributeError, TypeError): + return None + else: + with ffi._lock: + return ffi._get_cached_btype(tp) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/backend_ctypes.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/backend_ctypes.py new file mode 100644 index 0000000000000000000000000000000000000000..e7956a79cfb1c3d28a2ad22a40b261ae7dbbbb5f --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/backend_ctypes.py @@ -0,0 +1,1121 @@ +import ctypes, ctypes.util, operator, sys +from . import model + +if sys.version_info < (3,): + bytechr = chr +else: + unicode = str + long = int + xrange = range + bytechr = lambda num: bytes([num]) + +class CTypesType(type): + pass + +class CTypesData(object): + __metaclass__ = CTypesType + __slots__ = ['__weakref__'] + __name__ = '' + + def __init__(self, *args): + raise TypeError("cannot instantiate %r" % (self.__class__,)) + + @classmethod + def _newp(cls, init): + raise TypeError("expected a pointer or array ctype, got '%s'" + % (cls._get_c_name(),)) + + @staticmethod + def _to_ctypes(value): + raise TypeError + + @classmethod + def _arg_to_ctypes(cls, *value): + try: + ctype = cls._ctype + except AttributeError: + raise TypeError("cannot create an instance of %r" % (cls,)) + if value: + res = cls._to_ctypes(*value) + if not isinstance(res, ctype): + res = cls._ctype(res) + else: + res = cls._ctype() + return res + + @classmethod + def _create_ctype_obj(cls, init): + if init is None: + return cls._arg_to_ctypes() + else: + return cls._arg_to_ctypes(init) + + @staticmethod + def _from_ctypes(ctypes_value): + raise TypeError + + @classmethod + def _get_c_name(cls, replace_with=''): + return cls._reftypename.replace(' &', replace_with) + + @classmethod + def _fix_class(cls): + cls.__name__ = 'CData<%s>' % (cls._get_c_name(),) + cls.__qualname__ = 'CData<%s>' % (cls._get_c_name(),) + cls.__module__ = 'ffi' + + def _get_own_repr(self): + raise NotImplementedError + + def _addr_repr(self, address): + if address == 0: + return 'NULL' + else: + if address < 0: + address += 1 << (8*ctypes.sizeof(ctypes.c_void_p)) + return '0x%x' % address + + def __repr__(self, c_name=None): + own = self._get_own_repr() + return '' % (c_name or self._get_c_name(), own) + + def _convert_to_address(self, BClass): + if BClass is None: + raise TypeError("cannot convert %r to an address" % ( + self._get_c_name(),)) + else: + raise TypeError("cannot convert %r to %r" % ( + self._get_c_name(), BClass._get_c_name())) + + @classmethod + def _get_size(cls): + return ctypes.sizeof(cls._ctype) + + def _get_size_of_instance(self): + return ctypes.sizeof(self._ctype) + + @classmethod + def _cast_from(cls, source): + raise TypeError("cannot cast to %r" % (cls._get_c_name(),)) + + def _cast_to_integer(self): + return self._convert_to_address(None) + + @classmethod + def _alignment(cls): + return ctypes.alignment(cls._ctype) + + def __iter__(self): + raise TypeError("cdata %r does not support iteration" % ( + self._get_c_name()),) + + def _make_cmp(name): + cmpfunc = getattr(operator, name) + def cmp(self, other): + v_is_ptr = not isinstance(self, CTypesGenericPrimitive) + w_is_ptr = (isinstance(other, CTypesData) and + not isinstance(other, CTypesGenericPrimitive)) + if v_is_ptr and w_is_ptr: + return cmpfunc(self._convert_to_address(None), + other._convert_to_address(None)) + elif v_is_ptr or w_is_ptr: + return NotImplemented + else: + if isinstance(self, CTypesGenericPrimitive): + self = self._value + if isinstance(other, CTypesGenericPrimitive): + other = other._value + return cmpfunc(self, other) + cmp.func_name = name + return cmp + + __eq__ = _make_cmp('__eq__') + __ne__ = _make_cmp('__ne__') + __lt__ = _make_cmp('__lt__') + __le__ = _make_cmp('__le__') + __gt__ = _make_cmp('__gt__') + __ge__ = _make_cmp('__ge__') + + def __hash__(self): + return hash(self._convert_to_address(None)) + + def _to_string(self, maxlen): + raise TypeError("string(): %r" % (self,)) + + +class CTypesGenericPrimitive(CTypesData): + __slots__ = [] + + def __hash__(self): + return hash(self._value) + + def _get_own_repr(self): + return repr(self._from_ctypes(self._value)) + + +class CTypesGenericArray(CTypesData): + __slots__ = [] + + @classmethod + def _newp(cls, init): + return cls(init) + + def __iter__(self): + for i in xrange(len(self)): + yield self[i] + + def _get_own_repr(self): + return self._addr_repr(ctypes.addressof(self._blob)) + + +class CTypesGenericPtr(CTypesData): + __slots__ = ['_address', '_as_ctype_ptr'] + _automatic_casts = False + kind = "pointer" + + @classmethod + def _newp(cls, init): + return cls(init) + + @classmethod + def _cast_from(cls, source): + if source is None: + address = 0 + elif isinstance(source, CTypesData): + address = source._cast_to_integer() + elif isinstance(source, (int, long)): + address = source + else: + raise TypeError("bad type for cast to %r: %r" % + (cls, type(source).__name__)) + return cls._new_pointer_at(address) + + @classmethod + def _new_pointer_at(cls, address): + self = cls.__new__(cls) + self._address = address + self._as_ctype_ptr = ctypes.cast(address, cls._ctype) + return self + + def _get_own_repr(self): + try: + return self._addr_repr(self._address) + except AttributeError: + return '???' + + def _cast_to_integer(self): + return self._address + + def __nonzero__(self): + return bool(self._address) + __bool__ = __nonzero__ + + @classmethod + def _to_ctypes(cls, value): + if not isinstance(value, CTypesData): + raise TypeError("unexpected %s object" % type(value).__name__) + address = value._convert_to_address(cls) + return ctypes.cast(address, cls._ctype) + + @classmethod + def _from_ctypes(cls, ctypes_ptr): + address = ctypes.cast(ctypes_ptr, ctypes.c_void_p).value or 0 + return cls._new_pointer_at(address) + + @classmethod + def _initialize(cls, ctypes_ptr, value): + if value: + ctypes_ptr.contents = cls._to_ctypes(value).contents + + def _convert_to_address(self, BClass): + if (BClass in (self.__class__, None) or BClass._automatic_casts + or self._automatic_casts): + return self._address + else: + return CTypesData._convert_to_address(self, BClass) + + +class CTypesBaseStructOrUnion(CTypesData): + __slots__ = ['_blob'] + + @classmethod + def _create_ctype_obj(cls, init): + # may be overridden + raise TypeError("cannot instantiate opaque type %s" % (cls,)) + + def _get_own_repr(self): + return self._addr_repr(ctypes.addressof(self._blob)) + + @classmethod + def _offsetof(cls, fieldname): + return getattr(cls._ctype, fieldname).offset + + def _convert_to_address(self, BClass): + if getattr(BClass, '_BItem', None) is self.__class__: + return ctypes.addressof(self._blob) + else: + return CTypesData._convert_to_address(self, BClass) + + @classmethod + def _from_ctypes(cls, ctypes_struct_or_union): + self = cls.__new__(cls) + self._blob = ctypes_struct_or_union + return self + + @classmethod + def _to_ctypes(cls, value): + return value._blob + + def __repr__(self, c_name=None): + return CTypesData.__repr__(self, c_name or self._get_c_name(' &')) + + +class CTypesBackend(object): + + PRIMITIVE_TYPES = { + 'char': ctypes.c_char, + 'short': ctypes.c_short, + 'int': ctypes.c_int, + 'long': ctypes.c_long, + 'long long': ctypes.c_longlong, + 'signed char': ctypes.c_byte, + 'unsigned char': ctypes.c_ubyte, + 'unsigned short': ctypes.c_ushort, + 'unsigned int': ctypes.c_uint, + 'unsigned long': ctypes.c_ulong, + 'unsigned long long': ctypes.c_ulonglong, + 'float': ctypes.c_float, + 'double': ctypes.c_double, + '_Bool': ctypes.c_bool, + } + + for _name in ['unsigned long long', 'unsigned long', + 'unsigned int', 'unsigned short', 'unsigned char']: + _size = ctypes.sizeof(PRIMITIVE_TYPES[_name]) + PRIMITIVE_TYPES['uint%d_t' % (8*_size)] = PRIMITIVE_TYPES[_name] + if _size == ctypes.sizeof(ctypes.c_void_p): + PRIMITIVE_TYPES['uintptr_t'] = PRIMITIVE_TYPES[_name] + if _size == ctypes.sizeof(ctypes.c_size_t): + PRIMITIVE_TYPES['size_t'] = PRIMITIVE_TYPES[_name] + + for _name in ['long long', 'long', 'int', 'short', 'signed char']: + _size = ctypes.sizeof(PRIMITIVE_TYPES[_name]) + PRIMITIVE_TYPES['int%d_t' % (8*_size)] = PRIMITIVE_TYPES[_name] + if _size == ctypes.sizeof(ctypes.c_void_p): + PRIMITIVE_TYPES['intptr_t'] = PRIMITIVE_TYPES[_name] + PRIMITIVE_TYPES['ptrdiff_t'] = PRIMITIVE_TYPES[_name] + if _size == ctypes.sizeof(ctypes.c_size_t): + PRIMITIVE_TYPES['ssize_t'] = PRIMITIVE_TYPES[_name] + + + def __init__(self): + self.RTLD_LAZY = 0 # not supported anyway by ctypes + self.RTLD_NOW = 0 + self.RTLD_GLOBAL = ctypes.RTLD_GLOBAL + self.RTLD_LOCAL = ctypes.RTLD_LOCAL + + def set_ffi(self, ffi): + self.ffi = ffi + + def _get_types(self): + return CTypesData, CTypesType + + def load_library(self, path, flags=0): + cdll = ctypes.CDLL(path, flags) + return CTypesLibrary(self, cdll) + + def new_void_type(self): + class CTypesVoid(CTypesData): + __slots__ = [] + _reftypename = 'void &' + @staticmethod + def _from_ctypes(novalue): + return None + @staticmethod + def _to_ctypes(novalue): + if novalue is not None: + raise TypeError("None expected, got %s object" % + (type(novalue).__name__,)) + return None + CTypesVoid._fix_class() + return CTypesVoid + + def new_primitive_type(self, name): + if name == 'wchar_t': + raise NotImplementedError(name) + ctype = self.PRIMITIVE_TYPES[name] + if name == 'char': + kind = 'char' + elif name in ('float', 'double'): + kind = 'float' + else: + if name in ('signed char', 'unsigned char'): + kind = 'byte' + elif name == '_Bool': + kind = 'bool' + else: + kind = 'int' + is_signed = (ctype(-1).value == -1) + # + def _cast_source_to_int(source): + if isinstance(source, (int, long, float)): + source = int(source) + elif isinstance(source, CTypesData): + source = source._cast_to_integer() + elif isinstance(source, bytes): + source = ord(source) + elif source is None: + source = 0 + else: + raise TypeError("bad type for cast to %r: %r" % + (CTypesPrimitive, type(source).__name__)) + return source + # + kind1 = kind + class CTypesPrimitive(CTypesGenericPrimitive): + __slots__ = ['_value'] + _ctype = ctype + _reftypename = '%s &' % name + kind = kind1 + + def __init__(self, value): + self._value = value + + @staticmethod + def _create_ctype_obj(init): + if init is None: + return ctype() + return ctype(CTypesPrimitive._to_ctypes(init)) + + if kind == 'int' or kind == 'byte': + @classmethod + def _cast_from(cls, source): + source = _cast_source_to_int(source) + source = ctype(source).value # cast within range + return cls(source) + def __int__(self): + return self._value + + if kind == 'bool': + @classmethod + def _cast_from(cls, source): + if not isinstance(source, (int, long, float)): + source = _cast_source_to_int(source) + return cls(bool(source)) + def __int__(self): + return int(self._value) + + if kind == 'char': + @classmethod + def _cast_from(cls, source): + source = _cast_source_to_int(source) + source = bytechr(source & 0xFF) + return cls(source) + def __int__(self): + return ord(self._value) + + if kind == 'float': + @classmethod + def _cast_from(cls, source): + if isinstance(source, float): + pass + elif isinstance(source, CTypesGenericPrimitive): + if hasattr(source, '__float__'): + source = float(source) + else: + source = int(source) + else: + source = _cast_source_to_int(source) + source = ctype(source).value # fix precision + return cls(source) + def __int__(self): + return int(self._value) + def __float__(self): + return self._value + + _cast_to_integer = __int__ + + if kind == 'int' or kind == 'byte' or kind == 'bool': + @staticmethod + def _to_ctypes(x): + if not isinstance(x, (int, long)): + if isinstance(x, CTypesData): + x = int(x) + else: + raise TypeError("integer expected, got %s" % + type(x).__name__) + if ctype(x).value != x: + if not is_signed and x < 0: + raise OverflowError("%s: negative integer" % name) + else: + raise OverflowError("%s: integer out of bounds" + % name) + return x + + if kind == 'char': + @staticmethod + def _to_ctypes(x): + if isinstance(x, bytes) and len(x) == 1: + return x + if isinstance(x, CTypesPrimitive): # > + return x._value + raise TypeError("character expected, got %s" % + type(x).__name__) + def __nonzero__(self): + return ord(self._value) != 0 + else: + def __nonzero__(self): + return self._value != 0 + __bool__ = __nonzero__ + + if kind == 'float': + @staticmethod + def _to_ctypes(x): + if not isinstance(x, (int, long, float, CTypesData)): + raise TypeError("float expected, got %s" % + type(x).__name__) + return ctype(x).value + + @staticmethod + def _from_ctypes(value): + return getattr(value, 'value', value) + + @staticmethod + def _initialize(blob, init): + blob.value = CTypesPrimitive._to_ctypes(init) + + if kind == 'char': + def _to_string(self, maxlen): + return self._value + if kind == 'byte': + def _to_string(self, maxlen): + return chr(self._value & 0xff) + # + CTypesPrimitive._fix_class() + return CTypesPrimitive + + def new_pointer_type(self, BItem): + getbtype = self.ffi._get_cached_btype + if BItem is getbtype(model.PrimitiveType('char')): + kind = 'charp' + elif BItem in (getbtype(model.PrimitiveType('signed char')), + getbtype(model.PrimitiveType('unsigned char'))): + kind = 'bytep' + elif BItem is getbtype(model.void_type): + kind = 'voidp' + else: + kind = 'generic' + # + class CTypesPtr(CTypesGenericPtr): + __slots__ = ['_own'] + if kind == 'charp': + __slots__ += ['__as_strbuf'] + _BItem = BItem + if hasattr(BItem, '_ctype'): + _ctype = ctypes.POINTER(BItem._ctype) + _bitem_size = ctypes.sizeof(BItem._ctype) + else: + _ctype = ctypes.c_void_p + if issubclass(BItem, CTypesGenericArray): + _reftypename = BItem._get_c_name('(* &)') + else: + _reftypename = BItem._get_c_name(' * &') + + def __init__(self, init): + ctypeobj = BItem._create_ctype_obj(init) + if kind == 'charp': + self.__as_strbuf = ctypes.create_string_buffer( + ctypeobj.value + b'\x00') + self._as_ctype_ptr = ctypes.cast( + self.__as_strbuf, self._ctype) + else: + self._as_ctype_ptr = ctypes.pointer(ctypeobj) + self._address = ctypes.cast(self._as_ctype_ptr, + ctypes.c_void_p).value + self._own = True + + def __add__(self, other): + if isinstance(other, (int, long)): + return self._new_pointer_at(self._address + + other * self._bitem_size) + else: + return NotImplemented + + def __sub__(self, other): + if isinstance(other, (int, long)): + return self._new_pointer_at(self._address - + other * self._bitem_size) + elif type(self) is type(other): + return (self._address - other._address) // self._bitem_size + else: + return NotImplemented + + def __getitem__(self, index): + if getattr(self, '_own', False) and index != 0: + raise IndexError + return BItem._from_ctypes(self._as_ctype_ptr[index]) + + def __setitem__(self, index, value): + self._as_ctype_ptr[index] = BItem._to_ctypes(value) + + if kind == 'charp' or kind == 'voidp': + @classmethod + def _arg_to_ctypes(cls, *value): + if value and isinstance(value[0], bytes): + return ctypes.c_char_p(value[0]) + else: + return super(CTypesPtr, cls)._arg_to_ctypes(*value) + + if kind == 'charp' or kind == 'bytep': + def _to_string(self, maxlen): + if maxlen < 0: + maxlen = sys.maxsize + p = ctypes.cast(self._as_ctype_ptr, + ctypes.POINTER(ctypes.c_char)) + n = 0 + while n < maxlen and p[n] != b'\x00': + n += 1 + return b''.join([p[i] for i in range(n)]) + + def _get_own_repr(self): + if getattr(self, '_own', False): + return 'owning %d bytes' % ( + ctypes.sizeof(self._as_ctype_ptr.contents),) + return super(CTypesPtr, self)._get_own_repr() + # + if (BItem is self.ffi._get_cached_btype(model.void_type) or + BItem is self.ffi._get_cached_btype(model.PrimitiveType('char'))): + CTypesPtr._automatic_casts = True + # + CTypesPtr._fix_class() + return CTypesPtr + + def new_array_type(self, CTypesPtr, length): + if length is None: + brackets = ' &[]' + else: + brackets = ' &[%d]' % length + BItem = CTypesPtr._BItem + getbtype = self.ffi._get_cached_btype + if BItem is getbtype(model.PrimitiveType('char')): + kind = 'char' + elif BItem in (getbtype(model.PrimitiveType('signed char')), + getbtype(model.PrimitiveType('unsigned char'))): + kind = 'byte' + else: + kind = 'generic' + # + class CTypesArray(CTypesGenericArray): + __slots__ = ['_blob', '_own'] + if length is not None: + _ctype = BItem._ctype * length + else: + __slots__.append('_ctype') + _reftypename = BItem._get_c_name(brackets) + _declared_length = length + _CTPtr = CTypesPtr + + def __init__(self, init): + if length is None: + if isinstance(init, (int, long)): + len1 = init + init = None + elif kind == 'char' and isinstance(init, bytes): + len1 = len(init) + 1 # extra null + else: + init = tuple(init) + len1 = len(init) + self._ctype = BItem._ctype * len1 + self._blob = self._ctype() + self._own = True + if init is not None: + self._initialize(self._blob, init) + + @staticmethod + def _initialize(blob, init): + if isinstance(init, bytes): + init = [init[i:i+1] for i in range(len(init))] + else: + if isinstance(init, CTypesGenericArray): + if (len(init) != len(blob) or + not isinstance(init, CTypesArray)): + raise TypeError("length/type mismatch: %s" % (init,)) + init = tuple(init) + if len(init) > len(blob): + raise IndexError("too many initializers") + addr = ctypes.cast(blob, ctypes.c_void_p).value + PTR = ctypes.POINTER(BItem._ctype) + itemsize = ctypes.sizeof(BItem._ctype) + for i, value in enumerate(init): + p = ctypes.cast(addr + i * itemsize, PTR) + BItem._initialize(p.contents, value) + + def __len__(self): + return len(self._blob) + + def __getitem__(self, index): + if not (0 <= index < len(self._blob)): + raise IndexError + return BItem._from_ctypes(self._blob[index]) + + def __setitem__(self, index, value): + if not (0 <= index < len(self._blob)): + raise IndexError + self._blob[index] = BItem._to_ctypes(value) + + if kind == 'char' or kind == 'byte': + def _to_string(self, maxlen): + if maxlen < 0: + maxlen = len(self._blob) + p = ctypes.cast(self._blob, + ctypes.POINTER(ctypes.c_char)) + n = 0 + while n < maxlen and p[n] != b'\x00': + n += 1 + return b''.join([p[i] for i in range(n)]) + + def _get_own_repr(self): + if getattr(self, '_own', False): + return 'owning %d bytes' % (ctypes.sizeof(self._blob),) + return super(CTypesArray, self)._get_own_repr() + + def _convert_to_address(self, BClass): + if BClass in (CTypesPtr, None) or BClass._automatic_casts: + return ctypes.addressof(self._blob) + else: + return CTypesData._convert_to_address(self, BClass) + + @staticmethod + def _from_ctypes(ctypes_array): + self = CTypesArray.__new__(CTypesArray) + self._blob = ctypes_array + return self + + @staticmethod + def _arg_to_ctypes(value): + return CTypesPtr._arg_to_ctypes(value) + + def __add__(self, other): + if isinstance(other, (int, long)): + return CTypesPtr._new_pointer_at( + ctypes.addressof(self._blob) + + other * ctypes.sizeof(BItem._ctype)) + else: + return NotImplemented + + @classmethod + def _cast_from(cls, source): + raise NotImplementedError("casting to %r" % ( + cls._get_c_name(),)) + # + CTypesArray._fix_class() + return CTypesArray + + def _new_struct_or_union(self, kind, name, base_ctypes_class): + # + class struct_or_union(base_ctypes_class): + pass + struct_or_union.__name__ = '%s_%s' % (kind, name) + kind1 = kind + # + class CTypesStructOrUnion(CTypesBaseStructOrUnion): + __slots__ = ['_blob'] + _ctype = struct_or_union + _reftypename = '%s &' % (name,) + _kind = kind = kind1 + # + CTypesStructOrUnion._fix_class() + return CTypesStructOrUnion + + def new_struct_type(self, name): + return self._new_struct_or_union('struct', name, ctypes.Structure) + + def new_union_type(self, name): + return self._new_struct_or_union('union', name, ctypes.Union) + + def complete_struct_or_union(self, CTypesStructOrUnion, fields, tp, + totalsize=-1, totalalignment=-1, sflags=0, + pack=0): + if totalsize >= 0 or totalalignment >= 0: + raise NotImplementedError("the ctypes backend of CFFI does not support " + "structures completed by verify(); please " + "compile and install the _cffi_backend module.") + struct_or_union = CTypesStructOrUnion._ctype + fnames = [fname for (fname, BField, bitsize) in fields] + btypes = [BField for (fname, BField, bitsize) in fields] + bitfields = [bitsize for (fname, BField, bitsize) in fields] + # + bfield_types = {} + cfields = [] + for (fname, BField, bitsize) in fields: + if bitsize < 0: + cfields.append((fname, BField._ctype)) + bfield_types[fname] = BField + else: + cfields.append((fname, BField._ctype, bitsize)) + bfield_types[fname] = Ellipsis + if sflags & 8: + struct_or_union._pack_ = 1 + elif pack: + struct_or_union._pack_ = pack + struct_or_union._fields_ = cfields + CTypesStructOrUnion._bfield_types = bfield_types + # + @staticmethod + def _create_ctype_obj(init): + result = struct_or_union() + if init is not None: + initialize(result, init) + return result + CTypesStructOrUnion._create_ctype_obj = _create_ctype_obj + # + def initialize(blob, init): + if is_union: + if len(init) > 1: + raise ValueError("union initializer: %d items given, but " + "only one supported (use a dict if needed)" + % (len(init),)) + if not isinstance(init, dict): + if isinstance(init, (bytes, unicode)): + raise TypeError("union initializer: got a str") + init = tuple(init) + if len(init) > len(fnames): + raise ValueError("too many values for %s initializer" % + CTypesStructOrUnion._get_c_name()) + init = dict(zip(fnames, init)) + addr = ctypes.addressof(blob) + for fname, value in init.items(): + BField, bitsize = name2fieldtype[fname] + assert bitsize < 0, \ + "not implemented: initializer with bit fields" + offset = CTypesStructOrUnion._offsetof(fname) + PTR = ctypes.POINTER(BField._ctype) + p = ctypes.cast(addr + offset, PTR) + BField._initialize(p.contents, value) + is_union = CTypesStructOrUnion._kind == 'union' + name2fieldtype = dict(zip(fnames, zip(btypes, bitfields))) + # + for fname, BField, bitsize in fields: + if fname == '': + raise NotImplementedError("nested anonymous structs/unions") + if hasattr(CTypesStructOrUnion, fname): + raise ValueError("the field name %r conflicts in " + "the ctypes backend" % fname) + if bitsize < 0: + def getter(self, fname=fname, BField=BField, + offset=CTypesStructOrUnion._offsetof(fname), + PTR=ctypes.POINTER(BField._ctype)): + addr = ctypes.addressof(self._blob) + p = ctypes.cast(addr + offset, PTR) + return BField._from_ctypes(p.contents) + def setter(self, value, fname=fname, BField=BField): + setattr(self._blob, fname, BField._to_ctypes(value)) + # + if issubclass(BField, CTypesGenericArray): + setter = None + if BField._declared_length == 0: + def getter(self, fname=fname, BFieldPtr=BField._CTPtr, + offset=CTypesStructOrUnion._offsetof(fname), + PTR=ctypes.POINTER(BField._ctype)): + addr = ctypes.addressof(self._blob) + p = ctypes.cast(addr + offset, PTR) + return BFieldPtr._from_ctypes(p) + # + else: + def getter(self, fname=fname, BField=BField): + return BField._from_ctypes(getattr(self._blob, fname)) + def setter(self, value, fname=fname, BField=BField): + # xxx obscure workaround + value = BField._to_ctypes(value) + oldvalue = getattr(self._blob, fname) + setattr(self._blob, fname, value) + if value != getattr(self._blob, fname): + setattr(self._blob, fname, oldvalue) + raise OverflowError("value too large for bitfield") + setattr(CTypesStructOrUnion, fname, property(getter, setter)) + # + CTypesPtr = self.ffi._get_cached_btype(model.PointerType(tp)) + for fname in fnames: + if hasattr(CTypesPtr, fname): + raise ValueError("the field name %r conflicts in " + "the ctypes backend" % fname) + def getter(self, fname=fname): + return getattr(self[0], fname) + def setter(self, value, fname=fname): + setattr(self[0], fname, value) + setattr(CTypesPtr, fname, property(getter, setter)) + + def new_function_type(self, BArgs, BResult, has_varargs): + nameargs = [BArg._get_c_name() for BArg in BArgs] + if has_varargs: + nameargs.append('...') + nameargs = ', '.join(nameargs) + # + class CTypesFunctionPtr(CTypesGenericPtr): + __slots__ = ['_own_callback', '_name'] + _ctype = ctypes.CFUNCTYPE(getattr(BResult, '_ctype', None), + *[BArg._ctype for BArg in BArgs], + use_errno=True) + _reftypename = BResult._get_c_name('(* &)(%s)' % (nameargs,)) + + def __init__(self, init, error=None): + # create a callback to the Python callable init() + import traceback + assert not has_varargs, "varargs not supported for callbacks" + if getattr(BResult, '_ctype', None) is not None: + error = BResult._from_ctypes( + BResult._create_ctype_obj(error)) + else: + error = None + def callback(*args): + args2 = [] + for arg, BArg in zip(args, BArgs): + args2.append(BArg._from_ctypes(arg)) + try: + res2 = init(*args2) + res2 = BResult._to_ctypes(res2) + except: + traceback.print_exc() + res2 = error + if issubclass(BResult, CTypesGenericPtr): + if res2: + res2 = ctypes.cast(res2, ctypes.c_void_p).value + # .value: http://bugs.python.org/issue1574593 + else: + res2 = None + #print repr(res2) + return res2 + if issubclass(BResult, CTypesGenericPtr): + # The only pointers callbacks can return are void*s: + # http://bugs.python.org/issue5710 + callback_ctype = ctypes.CFUNCTYPE( + ctypes.c_void_p, + *[BArg._ctype for BArg in BArgs], + use_errno=True) + else: + callback_ctype = CTypesFunctionPtr._ctype + self._as_ctype_ptr = callback_ctype(callback) + self._address = ctypes.cast(self._as_ctype_ptr, + ctypes.c_void_p).value + self._own_callback = init + + @staticmethod + def _initialize(ctypes_ptr, value): + if value: + raise NotImplementedError("ctypes backend: not supported: " + "initializers for function pointers") + + def __repr__(self): + c_name = getattr(self, '_name', None) + if c_name: + i = self._reftypename.index('(* &)') + if self._reftypename[i-1] not in ' )*': + c_name = ' ' + c_name + c_name = self._reftypename.replace('(* &)', c_name) + return CTypesData.__repr__(self, c_name) + + def _get_own_repr(self): + if getattr(self, '_own_callback', None) is not None: + return 'calling %r' % (self._own_callback,) + return super(CTypesFunctionPtr, self)._get_own_repr() + + def __call__(self, *args): + if has_varargs: + assert len(args) >= len(BArgs) + extraargs = args[len(BArgs):] + args = args[:len(BArgs)] + else: + assert len(args) == len(BArgs) + ctypes_args = [] + for arg, BArg in zip(args, BArgs): + ctypes_args.append(BArg._arg_to_ctypes(arg)) + if has_varargs: + for i, arg in enumerate(extraargs): + if arg is None: + ctypes_args.append(ctypes.c_void_p(0)) # NULL + continue + if not isinstance(arg, CTypesData): + raise TypeError( + "argument %d passed in the variadic part " + "needs to be a cdata object (got %s)" % + (1 + len(BArgs) + i, type(arg).__name__)) + ctypes_args.append(arg._arg_to_ctypes(arg)) + result = self._as_ctype_ptr(*ctypes_args) + return BResult._from_ctypes(result) + # + CTypesFunctionPtr._fix_class() + return CTypesFunctionPtr + + def new_enum_type(self, name, enumerators, enumvalues, CTypesInt): + assert isinstance(name, str) + reverse_mapping = dict(zip(reversed(enumvalues), + reversed(enumerators))) + # + class CTypesEnum(CTypesInt): + __slots__ = [] + _reftypename = '%s &' % name + + def _get_own_repr(self): + value = self._value + try: + return '%d: %s' % (value, reverse_mapping[value]) + except KeyError: + return str(value) + + def _to_string(self, maxlen): + value = self._value + try: + return reverse_mapping[value] + except KeyError: + return str(value) + # + CTypesEnum._fix_class() + return CTypesEnum + + def get_errno(self): + return ctypes.get_errno() + + def set_errno(self, value): + ctypes.set_errno(value) + + def string(self, b, maxlen=-1): + return b._to_string(maxlen) + + def buffer(self, bptr, size=-1): + raise NotImplementedError("buffer() with ctypes backend") + + def sizeof(self, cdata_or_BType): + if isinstance(cdata_or_BType, CTypesData): + return cdata_or_BType._get_size_of_instance() + else: + assert issubclass(cdata_or_BType, CTypesData) + return cdata_or_BType._get_size() + + def alignof(self, BType): + assert issubclass(BType, CTypesData) + return BType._alignment() + + def newp(self, BType, source): + if not issubclass(BType, CTypesData): + raise TypeError + return BType._newp(source) + + def cast(self, BType, source): + return BType._cast_from(source) + + def callback(self, BType, source, error, onerror): + assert onerror is None # XXX not implemented + return BType(source, error) + + _weakref_cache_ref = None + + def gcp(self, cdata, destructor, size=0): + if self._weakref_cache_ref is None: + import weakref + class MyRef(weakref.ref): + def __eq__(self, other): + myref = self() + return self is other or ( + myref is not None and myref is other()) + def __ne__(self, other): + return not (self == other) + def __hash__(self): + try: + return self._hash + except AttributeError: + self._hash = hash(self()) + return self._hash + self._weakref_cache_ref = {}, MyRef + weak_cache, MyRef = self._weakref_cache_ref + + if destructor is None: + try: + del weak_cache[MyRef(cdata)] + except KeyError: + raise TypeError("Can remove destructor only on a object " + "previously returned by ffi.gc()") + return None + + def remove(k): + cdata, destructor = weak_cache.pop(k, (None, None)) + if destructor is not None: + destructor(cdata) + + new_cdata = self.cast(self.typeof(cdata), cdata) + assert new_cdata is not cdata + weak_cache[MyRef(new_cdata, remove)] = (cdata, destructor) + return new_cdata + + typeof = type + + def getcname(self, BType, replace_with): + return BType._get_c_name(replace_with) + + def typeoffsetof(self, BType, fieldname, num=0): + if isinstance(fieldname, str): + if num == 0 and issubclass(BType, CTypesGenericPtr): + BType = BType._BItem + if not issubclass(BType, CTypesBaseStructOrUnion): + raise TypeError("expected a struct or union ctype") + BField = BType._bfield_types[fieldname] + if BField is Ellipsis: + raise TypeError("not supported for bitfields") + return (BField, BType._offsetof(fieldname)) + elif isinstance(fieldname, (int, long)): + if issubclass(BType, CTypesGenericArray): + BType = BType._CTPtr + if not issubclass(BType, CTypesGenericPtr): + raise TypeError("expected an array or ptr ctype") + BItem = BType._BItem + offset = BItem._get_size() * fieldname + if offset > sys.maxsize: + raise OverflowError + return (BItem, offset) + else: + raise TypeError(type(fieldname)) + + def rawaddressof(self, BTypePtr, cdata, offset=None): + if isinstance(cdata, CTypesBaseStructOrUnion): + ptr = ctypes.pointer(type(cdata)._to_ctypes(cdata)) + elif isinstance(cdata, CTypesGenericPtr): + if offset is None or not issubclass(type(cdata)._BItem, + CTypesBaseStructOrUnion): + raise TypeError("unexpected cdata type") + ptr = type(cdata)._to_ctypes(cdata) + elif isinstance(cdata, CTypesGenericArray): + ptr = type(cdata)._to_ctypes(cdata) + else: + raise TypeError("expected a ") + if offset: + ptr = ctypes.cast( + ctypes.c_void_p( + ctypes.cast(ptr, ctypes.c_void_p).value + offset), + type(ptr)) + return BTypePtr._from_ctypes(ptr) + + +class CTypesLibrary(object): + + def __init__(self, backend, cdll): + self.backend = backend + self.cdll = cdll + + def load_function(self, BType, name): + c_func = getattr(self.cdll, name) + funcobj = BType._from_ctypes(c_func) + funcobj._name = name + return funcobj + + def read_variable(self, BType, name): + try: + ctypes_obj = BType._ctype.in_dll(self.cdll, name) + except AttributeError as e: + raise NotImplementedError(e) + return BType._from_ctypes(ctypes_obj) + + def write_variable(self, BType, name, value): + new_ctypes_obj = BType._to_ctypes(value) + ctypes_obj = BType._ctype.in_dll(self.cdll, name) + ctypes.memmove(ctypes.addressof(ctypes_obj), + ctypes.addressof(new_ctypes_obj), + ctypes.sizeof(BType._ctype)) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/cffi_opcode.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/cffi_opcode.py new file mode 100644 index 0000000000000000000000000000000000000000..6421df62134ce43a10d72b3b404102681574abf3 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/cffi_opcode.py @@ -0,0 +1,187 @@ +from .error import VerificationError + +class CffiOp(object): + def __init__(self, op, arg): + self.op = op + self.arg = arg + + def as_c_expr(self): + if self.op is None: + assert isinstance(self.arg, str) + return '(_cffi_opcode_t)(%s)' % (self.arg,) + classname = CLASS_NAME[self.op] + return '_CFFI_OP(_CFFI_OP_%s, %s)' % (classname, self.arg) + + def as_python_bytes(self): + if self.op is None and self.arg.isdigit(): + value = int(self.arg) # non-negative: '-' not in self.arg + if value >= 2**31: + raise OverflowError("cannot emit %r: limited to 2**31-1" + % (self.arg,)) + return format_four_bytes(value) + if isinstance(self.arg, str): + raise VerificationError("cannot emit to Python: %r" % (self.arg,)) + return format_four_bytes((self.arg << 8) | self.op) + + def __str__(self): + classname = CLASS_NAME.get(self.op, self.op) + return '(%s %s)' % (classname, self.arg) + +def format_four_bytes(num): + return '\\x%02X\\x%02X\\x%02X\\x%02X' % ( + (num >> 24) & 0xFF, + (num >> 16) & 0xFF, + (num >> 8) & 0xFF, + (num ) & 0xFF) + +OP_PRIMITIVE = 1 +OP_POINTER = 3 +OP_ARRAY = 5 +OP_OPEN_ARRAY = 7 +OP_STRUCT_UNION = 9 +OP_ENUM = 11 +OP_FUNCTION = 13 +OP_FUNCTION_END = 15 +OP_NOOP = 17 +OP_BITFIELD = 19 +OP_TYPENAME = 21 +OP_CPYTHON_BLTN_V = 23 # varargs +OP_CPYTHON_BLTN_N = 25 # noargs +OP_CPYTHON_BLTN_O = 27 # O (i.e. a single arg) +OP_CONSTANT = 29 +OP_CONSTANT_INT = 31 +OP_GLOBAL_VAR = 33 +OP_DLOPEN_FUNC = 35 +OP_DLOPEN_CONST = 37 +OP_GLOBAL_VAR_F = 39 +OP_EXTERN_PYTHON = 41 + +PRIM_VOID = 0 +PRIM_BOOL = 1 +PRIM_CHAR = 2 +PRIM_SCHAR = 3 +PRIM_UCHAR = 4 +PRIM_SHORT = 5 +PRIM_USHORT = 6 +PRIM_INT = 7 +PRIM_UINT = 8 +PRIM_LONG = 9 +PRIM_ULONG = 10 +PRIM_LONGLONG = 11 +PRIM_ULONGLONG = 12 +PRIM_FLOAT = 13 +PRIM_DOUBLE = 14 +PRIM_LONGDOUBLE = 15 + +PRIM_WCHAR = 16 +PRIM_INT8 = 17 +PRIM_UINT8 = 18 +PRIM_INT16 = 19 +PRIM_UINT16 = 20 +PRIM_INT32 = 21 +PRIM_UINT32 = 22 +PRIM_INT64 = 23 +PRIM_UINT64 = 24 +PRIM_INTPTR = 25 +PRIM_UINTPTR = 26 +PRIM_PTRDIFF = 27 +PRIM_SIZE = 28 +PRIM_SSIZE = 29 +PRIM_INT_LEAST8 = 30 +PRIM_UINT_LEAST8 = 31 +PRIM_INT_LEAST16 = 32 +PRIM_UINT_LEAST16 = 33 +PRIM_INT_LEAST32 = 34 +PRIM_UINT_LEAST32 = 35 +PRIM_INT_LEAST64 = 36 +PRIM_UINT_LEAST64 = 37 +PRIM_INT_FAST8 = 38 +PRIM_UINT_FAST8 = 39 +PRIM_INT_FAST16 = 40 +PRIM_UINT_FAST16 = 41 +PRIM_INT_FAST32 = 42 +PRIM_UINT_FAST32 = 43 +PRIM_INT_FAST64 = 44 +PRIM_UINT_FAST64 = 45 +PRIM_INTMAX = 46 +PRIM_UINTMAX = 47 +PRIM_FLOATCOMPLEX = 48 +PRIM_DOUBLECOMPLEX = 49 +PRIM_CHAR16 = 50 +PRIM_CHAR32 = 51 + +_NUM_PRIM = 52 +_UNKNOWN_PRIM = -1 +_UNKNOWN_FLOAT_PRIM = -2 +_UNKNOWN_LONG_DOUBLE = -3 + +_IO_FILE_STRUCT = -1 + +PRIMITIVE_TO_INDEX = { + 'char': PRIM_CHAR, + 'short': PRIM_SHORT, + 'int': PRIM_INT, + 'long': PRIM_LONG, + 'long long': PRIM_LONGLONG, + 'signed char': PRIM_SCHAR, + 'unsigned char': PRIM_UCHAR, + 'unsigned short': PRIM_USHORT, + 'unsigned int': PRIM_UINT, + 'unsigned long': PRIM_ULONG, + 'unsigned long long': PRIM_ULONGLONG, + 'float': PRIM_FLOAT, + 'double': PRIM_DOUBLE, + 'long double': PRIM_LONGDOUBLE, + '_cffi_float_complex_t': PRIM_FLOATCOMPLEX, + '_cffi_double_complex_t': PRIM_DOUBLECOMPLEX, + '_Bool': PRIM_BOOL, + 'wchar_t': PRIM_WCHAR, + 'char16_t': PRIM_CHAR16, + 'char32_t': PRIM_CHAR32, + 'int8_t': PRIM_INT8, + 'uint8_t': PRIM_UINT8, + 'int16_t': PRIM_INT16, + 'uint16_t': PRIM_UINT16, + 'int32_t': PRIM_INT32, + 'uint32_t': PRIM_UINT32, + 'int64_t': PRIM_INT64, + 'uint64_t': PRIM_UINT64, + 'intptr_t': PRIM_INTPTR, + 'uintptr_t': PRIM_UINTPTR, + 'ptrdiff_t': PRIM_PTRDIFF, + 'size_t': PRIM_SIZE, + 'ssize_t': PRIM_SSIZE, + 'int_least8_t': PRIM_INT_LEAST8, + 'uint_least8_t': PRIM_UINT_LEAST8, + 'int_least16_t': PRIM_INT_LEAST16, + 'uint_least16_t': PRIM_UINT_LEAST16, + 'int_least32_t': PRIM_INT_LEAST32, + 'uint_least32_t': PRIM_UINT_LEAST32, + 'int_least64_t': PRIM_INT_LEAST64, + 'uint_least64_t': PRIM_UINT_LEAST64, + 'int_fast8_t': PRIM_INT_FAST8, + 'uint_fast8_t': PRIM_UINT_FAST8, + 'int_fast16_t': PRIM_INT_FAST16, + 'uint_fast16_t': PRIM_UINT_FAST16, + 'int_fast32_t': PRIM_INT_FAST32, + 'uint_fast32_t': PRIM_UINT_FAST32, + 'int_fast64_t': PRIM_INT_FAST64, + 'uint_fast64_t': PRIM_UINT_FAST64, + 'intmax_t': PRIM_INTMAX, + 'uintmax_t': PRIM_UINTMAX, + } + +F_UNION = 0x01 +F_CHECK_FIELDS = 0x02 +F_PACKED = 0x04 +F_EXTERNAL = 0x08 +F_OPAQUE = 0x10 + +G_FLAGS = dict([('_CFFI_' + _key, globals()[_key]) + for _key in ['F_UNION', 'F_CHECK_FIELDS', 'F_PACKED', + 'F_EXTERNAL', 'F_OPAQUE']]) + +CLASS_NAME = {} +for _name, _value in list(globals().items()): + if _name.startswith('OP_') and isinstance(_value, int): + CLASS_NAME[_value] = _name[3:] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/commontypes.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/commontypes.py new file mode 100644 index 0000000000000000000000000000000000000000..d4dae3517009fc3f7ccaf01d97d10df098700d06 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/commontypes.py @@ -0,0 +1,82 @@ +import sys +from . import model +from .error import FFIError + + +COMMON_TYPES = {} + +try: + # fetch "bool" and all simple Windows types + from _cffi_backend import _get_common_types + _get_common_types(COMMON_TYPES) +except ImportError: + pass + +COMMON_TYPES['FILE'] = model.unknown_type('FILE', '_IO_FILE') +COMMON_TYPES['bool'] = '_Bool' # in case we got ImportError above +COMMON_TYPES['float _Complex'] = '_cffi_float_complex_t' +COMMON_TYPES['double _Complex'] = '_cffi_double_complex_t' + +for _type in model.PrimitiveType.ALL_PRIMITIVE_TYPES: + if _type.endswith('_t'): + COMMON_TYPES[_type] = _type +del _type + +_CACHE = {} + +def resolve_common_type(parser, commontype): + try: + return _CACHE[commontype] + except KeyError: + cdecl = COMMON_TYPES.get(commontype, commontype) + if not isinstance(cdecl, str): + result, quals = cdecl, 0 # cdecl is already a BaseType + elif cdecl in model.PrimitiveType.ALL_PRIMITIVE_TYPES: + result, quals = model.PrimitiveType(cdecl), 0 + elif cdecl == 'set-unicode-needed': + raise FFIError("The Windows type %r is only available after " + "you call ffi.set_unicode()" % (commontype,)) + else: + if commontype == cdecl: + raise FFIError( + "Unsupported type: %r. Please look at " + "http://cffi.readthedocs.io/en/latest/cdef.html#ffi-cdef-limitations " + "and file an issue if you think this type should really " + "be supported." % (commontype,)) + result, quals = parser.parse_type_and_quals(cdecl) # recursive + + assert isinstance(result, model.BaseTypeByIdentity) + _CACHE[commontype] = result, quals + return result, quals + + +# ____________________________________________________________ +# extra types for Windows (most of them are in commontypes.c) + + +def win_common_types(): + return { + "UNICODE_STRING": model.StructType( + "_UNICODE_STRING", + ["Length", + "MaximumLength", + "Buffer"], + [model.PrimitiveType("unsigned short"), + model.PrimitiveType("unsigned short"), + model.PointerType(model.PrimitiveType("wchar_t"))], + [-1, -1, -1]), + "PUNICODE_STRING": "UNICODE_STRING *", + "PCUNICODE_STRING": "const UNICODE_STRING *", + + "TBYTE": "set-unicode-needed", + "TCHAR": "set-unicode-needed", + "LPCTSTR": "set-unicode-needed", + "PCTSTR": "set-unicode-needed", + "LPTSTR": "set-unicode-needed", + "PTSTR": "set-unicode-needed", + "PTBYTE": "set-unicode-needed", + "PTCHAR": "set-unicode-needed", + } + +if sys.platform == 'win32': + COMMON_TYPES.update(win_common_types()) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/cparser.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/cparser.py new file mode 100644 index 0000000000000000000000000000000000000000..dd590d8743d1828eb6139401b2269d173f487b6c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/cparser.py @@ -0,0 +1,1015 @@ +from . import model +from .commontypes import COMMON_TYPES, resolve_common_type +from .error import FFIError, CDefError +try: + from . import _pycparser as pycparser +except ImportError: + import pycparser +import weakref, re, sys + +try: + if sys.version_info < (3,): + import thread as _thread + else: + import _thread + lock = _thread.allocate_lock() +except ImportError: + lock = None + +def _workaround_for_static_import_finders(): + # Issue #392: packaging tools like cx_Freeze can not find these + # because pycparser uses exec dynamic import. This is an obscure + # workaround. This function is never called. + import pycparser.yacctab + import pycparser.lextab + +CDEF_SOURCE_STRING = "" +_r_comment = re.compile(r"/\*.*?\*/|//([^\n\\]|\\.)*?$", + re.DOTALL | re.MULTILINE) +_r_define = re.compile(r"^\s*#\s*define\s+([A-Za-z_][A-Za-z_0-9]*)" + r"\b((?:[^\n\\]|\\.)*?)$", + re.DOTALL | re.MULTILINE) +_r_line_directive = re.compile(r"^[ \t]*#[ \t]*(?:line|\d+)\b.*$", re.MULTILINE) +_r_partial_enum = re.compile(r"=\s*\.\.\.\s*[,}]|\.\.\.\s*\}") +_r_enum_dotdotdot = re.compile(r"__dotdotdot\d+__$") +_r_partial_array = re.compile(r"\[\s*\.\.\.\s*\]") +_r_words = re.compile(r"\w+|\S") +_parser_cache = None +_r_int_literal = re.compile(r"-?0?x?[0-9a-f]+[lu]*$", re.IGNORECASE) +_r_stdcall1 = re.compile(r"\b(__stdcall|WINAPI)\b") +_r_stdcall2 = re.compile(r"[(]\s*(__stdcall|WINAPI)\b") +_r_cdecl = re.compile(r"\b__cdecl\b") +_r_extern_python = re.compile(r'\bextern\s*"' + r'(Python|Python\s*\+\s*C|C\s*\+\s*Python)"\s*.') +_r_star_const_space = re.compile( # matches "* const " + r"[*]\s*((const|volatile|restrict)\b\s*)+") +_r_int_dotdotdot = re.compile(r"(\b(int|long|short|signed|unsigned|char)\s*)+" + r"\.\.\.") +_r_float_dotdotdot = re.compile(r"\b(double|float)\s*\.\.\.") + +def _get_parser(): + global _parser_cache + if _parser_cache is None: + _parser_cache = pycparser.CParser() + return _parser_cache + +def _workaround_for_old_pycparser(csource): + # Workaround for a pycparser issue (fixed between pycparser 2.10 and + # 2.14): "char*const***" gives us a wrong syntax tree, the same as + # for "char***(*const)". This means we can't tell the difference + # afterwards. But "char(*const(***))" gives us the right syntax + # tree. The issue only occurs if there are several stars in + # sequence with no parenthesis in between, just possibly qualifiers. + # Attempt to fix it by adding some parentheses in the source: each + # time we see "* const" or "* const *", we add an opening + # parenthesis before each star---the hard part is figuring out where + # to close them. + parts = [] + while True: + match = _r_star_const_space.search(csource) + if not match: + break + #print repr(''.join(parts)+csource), '=>', + parts.append(csource[:match.start()]) + parts.append('('); closing = ')' + parts.append(match.group()) # e.g. "* const " + endpos = match.end() + if csource.startswith('*', endpos): + parts.append('('); closing += ')' + level = 0 + i = endpos + while i < len(csource): + c = csource[i] + if c == '(': + level += 1 + elif c == ')': + if level == 0: + break + level -= 1 + elif c in ',;=': + if level == 0: + break + i += 1 + csource = csource[endpos:i] + closing + csource[i:] + #print repr(''.join(parts)+csource) + parts.append(csource) + return ''.join(parts) + +def _preprocess_extern_python(csource): + # input: `extern "Python" int foo(int);` or + # `extern "Python" { int foo(int); }` + # output: + # void __cffi_extern_python_start; + # int foo(int); + # void __cffi_extern_python_stop; + # + # input: `extern "Python+C" int foo(int);` + # output: + # void __cffi_extern_python_plus_c_start; + # int foo(int); + # void __cffi_extern_python_stop; + parts = [] + while True: + match = _r_extern_python.search(csource) + if not match: + break + endpos = match.end() - 1 + #print + #print ''.join(parts)+csource + #print '=>' + parts.append(csource[:match.start()]) + if 'C' in match.group(1): + parts.append('void __cffi_extern_python_plus_c_start; ') + else: + parts.append('void __cffi_extern_python_start; ') + if csource[endpos] == '{': + # grouping variant + closing = csource.find('}', endpos) + if closing < 0: + raise CDefError("'extern \"Python\" {': no '}' found") + if csource.find('{', endpos + 1, closing) >= 0: + raise NotImplementedError("cannot use { } inside a block " + "'extern \"Python\" { ... }'") + parts.append(csource[endpos+1:closing]) + csource = csource[closing+1:] + else: + # non-grouping variant + semicolon = csource.find(';', endpos) + if semicolon < 0: + raise CDefError("'extern \"Python\": no ';' found") + parts.append(csource[endpos:semicolon+1]) + csource = csource[semicolon+1:] + parts.append(' void __cffi_extern_python_stop;') + #print ''.join(parts)+csource + #print + parts.append(csource) + return ''.join(parts) + +def _warn_for_string_literal(csource): + if '"' not in csource: + return + for line in csource.splitlines(): + if '"' in line and not line.lstrip().startswith('#'): + import warnings + warnings.warn("String literal found in cdef() or type source. " + "String literals are ignored here, but you should " + "remove them anyway because some character sequences " + "confuse pre-parsing.") + break + +def _warn_for_non_extern_non_static_global_variable(decl): + if not decl.storage: + import warnings + warnings.warn("Global variable '%s' in cdef(): for consistency " + "with C it should have a storage class specifier " + "(usually 'extern')" % (decl.name,)) + +def _remove_line_directives(csource): + # _r_line_directive matches whole lines, without the final \n, if they + # start with '#line' with some spacing allowed, or '#NUMBER'. This + # function stores them away and replaces them with exactly the string + # '#line@N', where N is the index in the list 'line_directives'. + line_directives = [] + def replace(m): + i = len(line_directives) + line_directives.append(m.group()) + return '#line@%d' % i + csource = _r_line_directive.sub(replace, csource) + return csource, line_directives + +def _put_back_line_directives(csource, line_directives): + def replace(m): + s = m.group() + if not s.startswith('#line@'): + raise AssertionError("unexpected #line directive " + "(should have been processed and removed") + return line_directives[int(s[6:])] + return _r_line_directive.sub(replace, csource) + +def _preprocess(csource): + # First, remove the lines of the form '#line N "filename"' because + # the "filename" part could confuse the rest + csource, line_directives = _remove_line_directives(csource) + # Remove comments. NOTE: this only work because the cdef() section + # should not contain any string literals (except in line directives)! + def replace_keeping_newlines(m): + return ' ' + m.group().count('\n') * '\n' + csource = _r_comment.sub(replace_keeping_newlines, csource) + # Remove the "#define FOO x" lines + macros = {} + for match in _r_define.finditer(csource): + macroname, macrovalue = match.groups() + macrovalue = macrovalue.replace('\\\n', '').strip() + macros[macroname] = macrovalue + csource = _r_define.sub('', csource) + # + if pycparser.__version__ < '2.14': + csource = _workaround_for_old_pycparser(csource) + # + # BIG HACK: replace WINAPI or __stdcall with "volatile const". + # It doesn't make sense for the return type of a function to be + # "volatile volatile const", so we abuse it to detect __stdcall... + # Hack number 2 is that "int(volatile *fptr)();" is not valid C + # syntax, so we place the "volatile" before the opening parenthesis. + csource = _r_stdcall2.sub(' volatile volatile const(', csource) + csource = _r_stdcall1.sub(' volatile volatile const ', csource) + csource = _r_cdecl.sub(' ', csource) + # + # Replace `extern "Python"` with start/end markers + csource = _preprocess_extern_python(csource) + # + # Now there should not be any string literal left; warn if we get one + _warn_for_string_literal(csource) + # + # Replace "[...]" with "[__dotdotdotarray__]" + csource = _r_partial_array.sub('[__dotdotdotarray__]', csource) + # + # Replace "...}" with "__dotdotdotNUM__}". This construction should + # occur only at the end of enums; at the end of structs we have "...;}" + # and at the end of vararg functions "...);". Also replace "=...[,}]" + # with ",__dotdotdotNUM__[,}]": this occurs in the enums too, when + # giving an unknown value. + matches = list(_r_partial_enum.finditer(csource)) + for number, match in enumerate(reversed(matches)): + p = match.start() + if csource[p] == '=': + p2 = csource.find('...', p, match.end()) + assert p2 > p + csource = '%s,__dotdotdot%d__ %s' % (csource[:p], number, + csource[p2+3:]) + else: + assert csource[p:p+3] == '...' + csource = '%s __dotdotdot%d__ %s' % (csource[:p], number, + csource[p+3:]) + # Replace "int ..." or "unsigned long int..." with "__dotdotdotint__" + csource = _r_int_dotdotdot.sub(' __dotdotdotint__ ', csource) + # Replace "float ..." or "double..." with "__dotdotdotfloat__" + csource = _r_float_dotdotdot.sub(' __dotdotdotfloat__ ', csource) + # Replace all remaining "..." with the same name, "__dotdotdot__", + # which is declared with a typedef for the purpose of C parsing. + csource = csource.replace('...', ' __dotdotdot__ ') + # Finally, put back the line directives + csource = _put_back_line_directives(csource, line_directives) + return csource, macros + +def _common_type_names(csource): + # Look in the source for what looks like usages of types from the + # list of common types. A "usage" is approximated here as the + # appearance of the word, minus a "definition" of the type, which + # is the last word in a "typedef" statement. Approximative only + # but should be fine for all the common types. + look_for_words = set(COMMON_TYPES) + look_for_words.add(';') + look_for_words.add(',') + look_for_words.add('(') + look_for_words.add(')') + look_for_words.add('typedef') + words_used = set() + is_typedef = False + paren = 0 + previous_word = '' + for word in _r_words.findall(csource): + if word in look_for_words: + if word == ';': + if is_typedef: + words_used.discard(previous_word) + look_for_words.discard(previous_word) + is_typedef = False + elif word == 'typedef': + is_typedef = True + paren = 0 + elif word == '(': + paren += 1 + elif word == ')': + paren -= 1 + elif word == ',': + if is_typedef and paren == 0: + words_used.discard(previous_word) + look_for_words.discard(previous_word) + else: # word in COMMON_TYPES + words_used.add(word) + previous_word = word + return words_used + + +class Parser(object): + + def __init__(self): + self._declarations = {} + self._included_declarations = set() + self._anonymous_counter = 0 + self._structnode2type = weakref.WeakKeyDictionary() + self._options = {} + self._int_constants = {} + self._recomplete = [] + self._uses_new_feature = None + + def _parse(self, csource): + csource, macros = _preprocess(csource) + # XXX: for more efficiency we would need to poke into the + # internals of CParser... the following registers the + # typedefs, because their presence or absence influences the + # parsing itself (but what they are typedef'ed to plays no role) + ctn = _common_type_names(csource) + typenames = [] + for name in sorted(self._declarations): + if name.startswith('typedef '): + name = name[8:] + typenames.append(name) + ctn.discard(name) + typenames += sorted(ctn) + # + csourcelines = [] + csourcelines.append('# 1 ""') + for typename in typenames: + csourcelines.append('typedef int %s;' % typename) + csourcelines.append('typedef int __dotdotdotint__, __dotdotdotfloat__,' + ' __dotdotdot__;') + # this forces pycparser to consider the following in the file + # called from line 1 + csourcelines.append('# 1 "%s"' % (CDEF_SOURCE_STRING,)) + csourcelines.append(csource) + csourcelines.append('') # see test_missing_newline_bug + fullcsource = '\n'.join(csourcelines) + if lock is not None: + lock.acquire() # pycparser is not thread-safe... + try: + ast = _get_parser().parse(fullcsource) + except pycparser.c_parser.ParseError as e: + self.convert_pycparser_error(e, csource) + finally: + if lock is not None: + lock.release() + # csource will be used to find buggy source text + return ast, macros, csource + + def _convert_pycparser_error(self, e, csource): + # xxx look for ":NUM:" at the start of str(e) + # and interpret that as a line number. This will not work if + # the user gives explicit ``# NUM "FILE"`` directives. + line = None + msg = str(e) + match = re.match(r"%s:(\d+):" % (CDEF_SOURCE_STRING,), msg) + if match: + linenum = int(match.group(1), 10) + csourcelines = csource.splitlines() + if 1 <= linenum <= len(csourcelines): + line = csourcelines[linenum-1] + return line + + def convert_pycparser_error(self, e, csource): + line = self._convert_pycparser_error(e, csource) + + msg = str(e) + if line: + msg = 'cannot parse "%s"\n%s' % (line.strip(), msg) + else: + msg = 'parse error\n%s' % (msg,) + raise CDefError(msg) + + def parse(self, csource, override=False, packed=False, pack=None, + dllexport=False): + if packed: + if packed != True: + raise ValueError("'packed' should be False or True; use " + "'pack' to give another value") + if pack: + raise ValueError("cannot give both 'pack' and 'packed'") + pack = 1 + elif pack: + if pack & (pack - 1): + raise ValueError("'pack' must be a power of two, not %r" % + (pack,)) + else: + pack = 0 + prev_options = self._options + try: + self._options = {'override': override, + 'packed': pack, + 'dllexport': dllexport} + self._internal_parse(csource) + finally: + self._options = prev_options + + def _internal_parse(self, csource): + ast, macros, csource = self._parse(csource) + # add the macros + self._process_macros(macros) + # find the first "__dotdotdot__" and use that as a separator + # between the repeated typedefs and the real csource + iterator = iter(ast.ext) + for decl in iterator: + if decl.name == '__dotdotdot__': + break + else: + assert 0 + current_decl = None + # + try: + self._inside_extern_python = '__cffi_extern_python_stop' + for decl in iterator: + current_decl = decl + if isinstance(decl, pycparser.c_ast.Decl): + self._parse_decl(decl) + elif isinstance(decl, pycparser.c_ast.Typedef): + if not decl.name: + raise CDefError("typedef does not declare any name", + decl) + quals = 0 + if (isinstance(decl.type.type, pycparser.c_ast.IdentifierType) and + decl.type.type.names[-1].startswith('__dotdotdot')): + realtype = self._get_unknown_type(decl) + elif (isinstance(decl.type, pycparser.c_ast.PtrDecl) and + isinstance(decl.type.type, pycparser.c_ast.TypeDecl) and + isinstance(decl.type.type.type, + pycparser.c_ast.IdentifierType) and + decl.type.type.type.names[-1].startswith('__dotdotdot')): + realtype = self._get_unknown_ptr_type(decl) + else: + realtype, quals = self._get_type_and_quals( + decl.type, name=decl.name, partial_length_ok=True, + typedef_example="*(%s *)0" % (decl.name,)) + self._declare('typedef ' + decl.name, realtype, quals=quals) + elif decl.__class__.__name__ == 'Pragma': + # skip pragma, only in pycparser 2.15 + import warnings + warnings.warn( + "#pragma in cdef() are entirely ignored. " + "They should be removed for now, otherwise your " + "code might behave differently in a future version " + "of CFFI if #pragma support gets added. Note that " + "'#pragma pack' needs to be replaced with the " + "'packed' keyword argument to cdef().") + else: + raise CDefError("unexpected <%s>: this construct is valid " + "C but not valid in cdef()" % + decl.__class__.__name__, decl) + except CDefError as e: + if len(e.args) == 1: + e.args = e.args + (current_decl,) + raise + except FFIError as e: + msg = self._convert_pycparser_error(e, csource) + if msg: + e.args = (e.args[0] + "\n *** Err: %s" % msg,) + raise + + def _add_constants(self, key, val): + if key in self._int_constants: + if self._int_constants[key] == val: + return # ignore identical double declarations + raise FFIError( + "multiple declarations of constant: %s" % (key,)) + self._int_constants[key] = val + + def _add_integer_constant(self, name, int_str): + int_str = int_str.lower().rstrip("ul") + neg = int_str.startswith('-') + if neg: + int_str = int_str[1:] + # "010" is not valid oct in py3 + if (int_str.startswith("0") and int_str != '0' + and not int_str.startswith("0x")): + int_str = "0o" + int_str[1:] + pyvalue = int(int_str, 0) + if neg: + pyvalue = -pyvalue + self._add_constants(name, pyvalue) + self._declare('macro ' + name, pyvalue) + + def _process_macros(self, macros): + for key, value in macros.items(): + value = value.strip() + if _r_int_literal.match(value): + self._add_integer_constant(key, value) + elif value == '...': + self._declare('macro ' + key, value) + else: + raise CDefError( + 'only supports one of the following syntax:\n' + ' #define %s ... (literally dot-dot-dot)\n' + ' #define %s NUMBER (with NUMBER an integer' + ' constant, decimal/hex/octal)\n' + 'got:\n' + ' #define %s %s' + % (key, key, key, value)) + + def _declare_function(self, tp, quals, decl): + tp = self._get_type_pointer(tp, quals) + if self._options.get('dllexport'): + tag = 'dllexport_python ' + elif self._inside_extern_python == '__cffi_extern_python_start': + tag = 'extern_python ' + elif self._inside_extern_python == '__cffi_extern_python_plus_c_start': + tag = 'extern_python_plus_c ' + else: + tag = 'function ' + self._declare(tag + decl.name, tp) + + def _parse_decl(self, decl): + node = decl.type + if isinstance(node, pycparser.c_ast.FuncDecl): + tp, quals = self._get_type_and_quals(node, name=decl.name) + assert isinstance(tp, model.RawFunctionType) + self._declare_function(tp, quals, decl) + else: + if isinstance(node, pycparser.c_ast.Struct): + self._get_struct_union_enum_type('struct', node) + elif isinstance(node, pycparser.c_ast.Union): + self._get_struct_union_enum_type('union', node) + elif isinstance(node, pycparser.c_ast.Enum): + self._get_struct_union_enum_type('enum', node) + elif not decl.name: + raise CDefError("construct does not declare any variable", + decl) + # + if decl.name: + tp, quals = self._get_type_and_quals(node, + partial_length_ok=True) + if tp.is_raw_function: + self._declare_function(tp, quals, decl) + elif (tp.is_integer_type() and + hasattr(decl, 'init') and + hasattr(decl.init, 'value') and + _r_int_literal.match(decl.init.value)): + self._add_integer_constant(decl.name, decl.init.value) + elif (tp.is_integer_type() and + isinstance(decl.init, pycparser.c_ast.UnaryOp) and + decl.init.op == '-' and + hasattr(decl.init.expr, 'value') and + _r_int_literal.match(decl.init.expr.value)): + self._add_integer_constant(decl.name, + '-' + decl.init.expr.value) + elif (tp is model.void_type and + decl.name.startswith('__cffi_extern_python_')): + # hack: `extern "Python"` in the C source is replaced + # with "void __cffi_extern_python_start;" and + # "void __cffi_extern_python_stop;" + self._inside_extern_python = decl.name + else: + if self._inside_extern_python !='__cffi_extern_python_stop': + raise CDefError( + "cannot declare constants or " + "variables with 'extern \"Python\"'") + if (quals & model.Q_CONST) and not tp.is_array_type: + self._declare('constant ' + decl.name, tp, quals=quals) + else: + _warn_for_non_extern_non_static_global_variable(decl) + self._declare('variable ' + decl.name, tp, quals=quals) + + def parse_type(self, cdecl): + return self.parse_type_and_quals(cdecl)[0] + + def parse_type_and_quals(self, cdecl): + ast, macros = self._parse('void __dummy(\n%s\n);' % cdecl)[:2] + assert not macros + exprnode = ast.ext[-1].type.args.params[0] + if isinstance(exprnode, pycparser.c_ast.ID): + raise CDefError("unknown identifier '%s'" % (exprnode.name,)) + return self._get_type_and_quals(exprnode.type) + + def _declare(self, name, obj, included=False, quals=0): + if name in self._declarations: + prevobj, prevquals = self._declarations[name] + if prevobj is obj and prevquals == quals: + return + if not self._options.get('override'): + raise FFIError( + "multiple declarations of %s (for interactive usage, " + "try cdef(xx, override=True))" % (name,)) + assert '__dotdotdot__' not in name.split() + self._declarations[name] = (obj, quals) + if included: + self._included_declarations.add(obj) + + def _extract_quals(self, type): + quals = 0 + if isinstance(type, (pycparser.c_ast.TypeDecl, + pycparser.c_ast.PtrDecl)): + if 'const' in type.quals: + quals |= model.Q_CONST + if 'volatile' in type.quals: + quals |= model.Q_VOLATILE + if 'restrict' in type.quals: + quals |= model.Q_RESTRICT + return quals + + def _get_type_pointer(self, type, quals, declname=None): + if isinstance(type, model.RawFunctionType): + return type.as_function_pointer() + if (isinstance(type, model.StructOrUnionOrEnum) and + type.name.startswith('$') and type.name[1:].isdigit() and + type.forcename is None and declname is not None): + return model.NamedPointerType(type, declname, quals) + return model.PointerType(type, quals) + + def _get_type_and_quals(self, typenode, name=None, partial_length_ok=False, + typedef_example=None): + # first, dereference typedefs, if we have it already parsed, we're good + if (isinstance(typenode, pycparser.c_ast.TypeDecl) and + isinstance(typenode.type, pycparser.c_ast.IdentifierType) and + len(typenode.type.names) == 1 and + ('typedef ' + typenode.type.names[0]) in self._declarations): + tp, quals = self._declarations['typedef ' + typenode.type.names[0]] + quals |= self._extract_quals(typenode) + return tp, quals + # + if isinstance(typenode, pycparser.c_ast.ArrayDecl): + # array type + if typenode.dim is None: + length = None + else: + length = self._parse_constant( + typenode.dim, partial_length_ok=partial_length_ok) + # a hack: in 'typedef int foo_t[...][...];', don't use '...' as + # the length but use directly the C expression that would be + # generated by recompiler.py. This lets the typedef be used in + # many more places within recompiler.py + if typedef_example is not None: + if length == '...': + length = '_cffi_array_len(%s)' % (typedef_example,) + typedef_example = "*" + typedef_example + # + tp, quals = self._get_type_and_quals(typenode.type, + partial_length_ok=partial_length_ok, + typedef_example=typedef_example) + return model.ArrayType(tp, length), quals + # + if isinstance(typenode, pycparser.c_ast.PtrDecl): + # pointer type + itemtype, itemquals = self._get_type_and_quals(typenode.type) + tp = self._get_type_pointer(itemtype, itemquals, declname=name) + quals = self._extract_quals(typenode) + return tp, quals + # + if isinstance(typenode, pycparser.c_ast.TypeDecl): + quals = self._extract_quals(typenode) + type = typenode.type + if isinstance(type, pycparser.c_ast.IdentifierType): + # assume a primitive type. get it from .names, but reduce + # synonyms to a single chosen combination + names = list(type.names) + if names != ['signed', 'char']: # keep this unmodified + prefixes = {} + while names: + name = names[0] + if name in ('short', 'long', 'signed', 'unsigned'): + prefixes[name] = prefixes.get(name, 0) + 1 + del names[0] + else: + break + # ignore the 'signed' prefix below, and reorder the others + newnames = [] + for prefix in ('unsigned', 'short', 'long'): + for i in range(prefixes.get(prefix, 0)): + newnames.append(prefix) + if not names: + names = ['int'] # implicitly + if names == ['int']: # but kill it if 'short' or 'long' + if 'short' in prefixes or 'long' in prefixes: + names = [] + names = newnames + names + ident = ' '.join(names) + if ident == 'void': + return model.void_type, quals + if ident == '__dotdotdot__': + raise FFIError(':%d: bad usage of "..."' % + typenode.coord.line) + tp0, quals0 = resolve_common_type(self, ident) + return tp0, (quals | quals0) + # + if isinstance(type, pycparser.c_ast.Struct): + # 'struct foobar' + tp = self._get_struct_union_enum_type('struct', type, name) + return tp, quals + # + if isinstance(type, pycparser.c_ast.Union): + # 'union foobar' + tp = self._get_struct_union_enum_type('union', type, name) + return tp, quals + # + if isinstance(type, pycparser.c_ast.Enum): + # 'enum foobar' + tp = self._get_struct_union_enum_type('enum', type, name) + return tp, quals + # + if isinstance(typenode, pycparser.c_ast.FuncDecl): + # a function type + return self._parse_function_type(typenode, name), 0 + # + # nested anonymous structs or unions end up here + if isinstance(typenode, pycparser.c_ast.Struct): + return self._get_struct_union_enum_type('struct', typenode, name, + nested=True), 0 + if isinstance(typenode, pycparser.c_ast.Union): + return self._get_struct_union_enum_type('union', typenode, name, + nested=True), 0 + # + raise FFIError(":%d: bad or unsupported type declaration" % + typenode.coord.line) + + def _parse_function_type(self, typenode, funcname=None): + params = list(getattr(typenode.args, 'params', [])) + for i, arg in enumerate(params): + if not hasattr(arg, 'type'): + raise CDefError("%s arg %d: unknown type '%s'" + " (if you meant to use the old C syntax of giving" + " untyped arguments, it is not supported)" + % (funcname or 'in expression', i + 1, + getattr(arg, 'name', '?'))) + ellipsis = ( + len(params) > 0 and + isinstance(params[-1].type, pycparser.c_ast.TypeDecl) and + isinstance(params[-1].type.type, + pycparser.c_ast.IdentifierType) and + params[-1].type.type.names == ['__dotdotdot__']) + if ellipsis: + params.pop() + if not params: + raise CDefError( + "%s: a function with only '(...)' as argument" + " is not correct C" % (funcname or 'in expression')) + args = [self._as_func_arg(*self._get_type_and_quals(argdeclnode.type)) + for argdeclnode in params] + if not ellipsis and args == [model.void_type]: + args = [] + result, quals = self._get_type_and_quals(typenode.type) + # the 'quals' on the result type are ignored. HACK: we absure them + # to detect __stdcall functions: we textually replace "__stdcall" + # with "volatile volatile const" above. + abi = None + if hasattr(typenode.type, 'quals'): # else, probable syntax error anyway + if typenode.type.quals[-3:] == ['volatile', 'volatile', 'const']: + abi = '__stdcall' + return model.RawFunctionType(tuple(args), result, ellipsis, abi) + + def _as_func_arg(self, type, quals): + if isinstance(type, model.ArrayType): + return model.PointerType(type.item, quals) + elif isinstance(type, model.RawFunctionType): + return type.as_function_pointer() + else: + return type + + def _get_struct_union_enum_type(self, kind, type, name=None, nested=False): + # First, a level of caching on the exact 'type' node of the AST. + # This is obscure, but needed because pycparser "unrolls" declarations + # such as "typedef struct { } foo_t, *foo_p" and we end up with + # an AST that is not a tree, but a DAG, with the "type" node of the + # two branches foo_t and foo_p of the trees being the same node. + # It's a bit silly but detecting "DAG-ness" in the AST tree seems + # to be the only way to distinguish this case from two independent + # structs. See test_struct_with_two_usages. + try: + return self._structnode2type[type] + except KeyError: + pass + # + # Note that this must handle parsing "struct foo" any number of + # times and always return the same StructType object. Additionally, + # one of these times (not necessarily the first), the fields of + # the struct can be specified with "struct foo { ...fields... }". + # If no name is given, then we have to create a new anonymous struct + # with no caching; in this case, the fields are either specified + # right now or never. + # + force_name = name + name = type.name + # + # get the type or create it if needed + if name is None: + # 'force_name' is used to guess a more readable name for + # anonymous structs, for the common case "typedef struct { } foo". + if force_name is not None: + explicit_name = '$%s' % force_name + else: + self._anonymous_counter += 1 + explicit_name = '$%d' % self._anonymous_counter + tp = None + else: + explicit_name = name + key = '%s %s' % (kind, name) + tp, _ = self._declarations.get(key, (None, None)) + # + if tp is None: + if kind == 'struct': + tp = model.StructType(explicit_name, None, None, None) + elif kind == 'union': + tp = model.UnionType(explicit_name, None, None, None) + elif kind == 'enum': + if explicit_name == '__dotdotdot__': + raise CDefError("Enums cannot be declared with ...") + tp = self._build_enum_type(explicit_name, type.values) + else: + raise AssertionError("kind = %r" % (kind,)) + if name is not None: + self._declare(key, tp) + else: + if kind == 'enum' and type.values is not None: + raise NotImplementedError( + "enum %s: the '{}' declaration should appear on the first " + "time the enum is mentioned, not later" % explicit_name) + if not tp.forcename: + tp.force_the_name(force_name) + if tp.forcename and '$' in tp.name: + self._declare('anonymous %s' % tp.forcename, tp) + # + self._structnode2type[type] = tp + # + # enums: done here + if kind == 'enum': + return tp + # + # is there a 'type.decls'? If yes, then this is the place in the + # C sources that declare the fields. If no, then just return the + # existing type, possibly still incomplete. + if type.decls is None: + return tp + # + if tp.fldnames is not None: + raise CDefError("duplicate declaration of struct %s" % name) + fldnames = [] + fldtypes = [] + fldbitsize = [] + fldquals = [] + for decl in type.decls: + if (isinstance(decl.type, pycparser.c_ast.IdentifierType) and + ''.join(decl.type.names) == '__dotdotdot__'): + # XXX pycparser is inconsistent: 'names' should be a list + # of strings, but is sometimes just one string. Use + # str.join() as a way to cope with both. + self._make_partial(tp, nested) + continue + if decl.bitsize is None: + bitsize = -1 + else: + bitsize = self._parse_constant(decl.bitsize) + self._partial_length = False + type, fqual = self._get_type_and_quals(decl.type, + partial_length_ok=True) + if self._partial_length: + self._make_partial(tp, nested) + if isinstance(type, model.StructType) and type.partial: + self._make_partial(tp, nested) + fldnames.append(decl.name or '') + fldtypes.append(type) + fldbitsize.append(bitsize) + fldquals.append(fqual) + tp.fldnames = tuple(fldnames) + tp.fldtypes = tuple(fldtypes) + tp.fldbitsize = tuple(fldbitsize) + tp.fldquals = tuple(fldquals) + if fldbitsize != [-1] * len(fldbitsize): + if isinstance(tp, model.StructType) and tp.partial: + raise NotImplementedError("%s: using both bitfields and '...;'" + % (tp,)) + tp.packed = self._options.get('packed') + if tp.completed: # must be re-completed: it is not opaque any more + tp.completed = 0 + self._recomplete.append(tp) + return tp + + def _make_partial(self, tp, nested): + if not isinstance(tp, model.StructOrUnion): + raise CDefError("%s cannot be partial" % (tp,)) + if not tp.has_c_name() and not nested: + raise NotImplementedError("%s is partial but has no C name" %(tp,)) + tp.partial = True + + def _parse_constant(self, exprnode, partial_length_ok=False): + # for now, limited to expressions that are an immediate number + # or positive/negative number + if isinstance(exprnode, pycparser.c_ast.Constant): + s = exprnode.value + if '0' <= s[0] <= '9': + s = s.rstrip('uUlL') + try: + if s.startswith('0'): + return int(s, 8) + else: + return int(s, 10) + except ValueError: + if len(s) > 1: + if s.lower()[0:2] == '0x': + return int(s, 16) + elif s.lower()[0:2] == '0b': + return int(s, 2) + raise CDefError("invalid constant %r" % (s,)) + elif s[0] == "'" and s[-1] == "'" and ( + len(s) == 3 or (len(s) == 4 and s[1] == "\\")): + return ord(s[-2]) + else: + raise CDefError("invalid constant %r" % (s,)) + # + if (isinstance(exprnode, pycparser.c_ast.UnaryOp) and + exprnode.op == '+'): + return self._parse_constant(exprnode.expr) + # + if (isinstance(exprnode, pycparser.c_ast.UnaryOp) and + exprnode.op == '-'): + return -self._parse_constant(exprnode.expr) + # load previously defined int constant + if (isinstance(exprnode, pycparser.c_ast.ID) and + exprnode.name in self._int_constants): + return self._int_constants[exprnode.name] + # + if (isinstance(exprnode, pycparser.c_ast.ID) and + exprnode.name == '__dotdotdotarray__'): + if partial_length_ok: + self._partial_length = True + return '...' + raise FFIError(":%d: unsupported '[...]' here, cannot derive " + "the actual array length in this context" + % exprnode.coord.line) + # + if isinstance(exprnode, pycparser.c_ast.BinaryOp): + left = self._parse_constant(exprnode.left) + right = self._parse_constant(exprnode.right) + if exprnode.op == '+': + return left + right + elif exprnode.op == '-': + return left - right + elif exprnode.op == '*': + return left * right + elif exprnode.op == '/': + return self._c_div(left, right) + elif exprnode.op == '%': + return left - self._c_div(left, right) * right + elif exprnode.op == '<<': + return left << right + elif exprnode.op == '>>': + return left >> right + elif exprnode.op == '&': + return left & right + elif exprnode.op == '|': + return left | right + elif exprnode.op == '^': + return left ^ right + # + raise FFIError(":%d: unsupported expression: expected a " + "simple numeric constant" % exprnode.coord.line) + + def _c_div(self, a, b): + result = a // b + if ((a < 0) ^ (b < 0)) and (a % b) != 0: + result += 1 + return result + + def _build_enum_type(self, explicit_name, decls): + if decls is not None: + partial = False + enumerators = [] + enumvalues = [] + nextenumvalue = 0 + for enum in decls.enumerators: + if _r_enum_dotdotdot.match(enum.name): + partial = True + continue + if enum.value is not None: + nextenumvalue = self._parse_constant(enum.value) + enumerators.append(enum.name) + enumvalues.append(nextenumvalue) + self._add_constants(enum.name, nextenumvalue) + nextenumvalue += 1 + enumerators = tuple(enumerators) + enumvalues = tuple(enumvalues) + tp = model.EnumType(explicit_name, enumerators, enumvalues) + tp.partial = partial + else: # opaque enum + tp = model.EnumType(explicit_name, (), ()) + return tp + + def include(self, other): + for name, (tp, quals) in other._declarations.items(): + if name.startswith('anonymous $enum_$'): + continue # fix for test_anonymous_enum_include + kind = name.split(' ', 1)[0] + if kind in ('struct', 'union', 'enum', 'anonymous', 'typedef'): + self._declare(name, tp, included=True, quals=quals) + for k, v in other._int_constants.items(): + self._add_constants(k, v) + + def _get_unknown_type(self, decl): + typenames = decl.type.type.names + if typenames == ['__dotdotdot__']: + return model.unknown_type(decl.name) + + if typenames == ['__dotdotdotint__']: + if self._uses_new_feature is None: + self._uses_new_feature = "'typedef int... %s'" % decl.name + return model.UnknownIntegerType(decl.name) + + if typenames == ['__dotdotdotfloat__']: + # note: not for 'long double' so far + if self._uses_new_feature is None: + self._uses_new_feature = "'typedef float... %s'" % decl.name + return model.UnknownFloatType(decl.name) + + raise FFIError(':%d: unsupported usage of "..." in typedef' + % decl.coord.line) + + def _get_unknown_ptr_type(self, decl): + if decl.type.type.type.names == ['__dotdotdot__']: + return model.unknown_ptr_type(decl.name) + raise FFIError(':%d: unsupported usage of "..." in typedef' + % decl.coord.line) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/error.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/error.py new file mode 100644 index 0000000000000000000000000000000000000000..0a27247c32a381ab7cecedd0f985b781619c1ea5 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/error.py @@ -0,0 +1,31 @@ + +class FFIError(Exception): + __module__ = 'cffi' + +class CDefError(Exception): + __module__ = 'cffi' + def __str__(self): + try: + current_decl = self.args[1] + filename = current_decl.coord.file + linenum = current_decl.coord.line + prefix = '%s:%d: ' % (filename, linenum) + except (AttributeError, TypeError, IndexError): + prefix = '' + return '%s%s' % (prefix, self.args[0]) + +class VerificationError(Exception): + """ An error raised when verification fails + """ + __module__ = 'cffi' + +class VerificationMissing(Exception): + """ An error raised when incomplete structures are passed into + cdef, but no verification has been done + """ + __module__ = 'cffi' + +class PkgConfigError(Exception): + """ An error raised for missing modules in pkg-config + """ + __module__ = 'cffi' diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/ffiplatform.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/ffiplatform.py new file mode 100644 index 0000000000000000000000000000000000000000..adca28f1a480bb04a11977d26457fe8886139043 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/ffiplatform.py @@ -0,0 +1,113 @@ +import sys, os +from .error import VerificationError + + +LIST_OF_FILE_NAMES = ['sources', 'include_dirs', 'library_dirs', + 'extra_objects', 'depends'] + +def get_extension(srcfilename, modname, sources=(), **kwds): + from cffi._shimmed_dist_utils import Extension + allsources = [srcfilename] + for src in sources: + allsources.append(os.path.normpath(src)) + return Extension(name=modname, sources=allsources, **kwds) + +def compile(tmpdir, ext, compiler_verbose=0, debug=None): + """Compile a C extension module using distutils.""" + + saved_environ = os.environ.copy() + try: + outputfilename = _build(tmpdir, ext, compiler_verbose, debug) + outputfilename = os.path.abspath(outputfilename) + finally: + # workaround for a distutils bugs where some env vars can + # become longer and longer every time it is used + for key, value in saved_environ.items(): + if os.environ.get(key) != value: + os.environ[key] = value + return outputfilename + +def _build(tmpdir, ext, compiler_verbose=0, debug=None): + # XXX compact but horrible :-( + from cffi._shimmed_dist_utils import Distribution, CompileError, LinkError, set_threshold, set_verbosity + + dist = Distribution({'ext_modules': [ext]}) + dist.parse_config_files() + options = dist.get_option_dict('build_ext') + if debug is None: + debug = sys.flags.debug + options['debug'] = ('ffiplatform', debug) + options['force'] = ('ffiplatform', True) + options['build_lib'] = ('ffiplatform', tmpdir) + options['build_temp'] = ('ffiplatform', tmpdir) + # + try: + old_level = set_threshold(0) or 0 + try: + set_verbosity(compiler_verbose) + dist.run_command('build_ext') + cmd_obj = dist.get_command_obj('build_ext') + [soname] = cmd_obj.get_outputs() + finally: + set_threshold(old_level) + except (CompileError, LinkError) as e: + raise VerificationError('%s: %s' % (e.__class__.__name__, e)) + # + return soname + +try: + from os.path import samefile +except ImportError: + def samefile(f1, f2): + return os.path.abspath(f1) == os.path.abspath(f2) + +def maybe_relative_path(path): + if not os.path.isabs(path): + return path # already relative + dir = path + names = [] + while True: + prevdir = dir + dir, name = os.path.split(prevdir) + if dir == prevdir or not dir: + return path # failed to make it relative + names.append(name) + try: + if samefile(dir, os.curdir): + names.reverse() + return os.path.join(*names) + except OSError: + pass + +# ____________________________________________________________ + +try: + int_or_long = (int, long) + import cStringIO +except NameError: + int_or_long = int # Python 3 + import io as cStringIO + +def _flatten(x, f): + if isinstance(x, str): + f.write('%ds%s' % (len(x), x)) + elif isinstance(x, dict): + keys = sorted(x.keys()) + f.write('%dd' % len(keys)) + for key in keys: + _flatten(key, f) + _flatten(x[key], f) + elif isinstance(x, (list, tuple)): + f.write('%dl' % len(x)) + for value in x: + _flatten(value, f) + elif isinstance(x, int_or_long): + f.write('%di' % (x,)) + else: + raise TypeError( + "the keywords to verify() contains unsupported object %r" % (x,)) + +def flatten(x): + f = cStringIO.StringIO() + _flatten(x, f) + return f.getvalue() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/lock.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/lock.py new file mode 100644 index 0000000000000000000000000000000000000000..db91b7158c4ee9aa653462fe38e79ed1b553db87 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/lock.py @@ -0,0 +1,30 @@ +import sys + +if sys.version_info < (3,): + try: + from thread import allocate_lock + except ImportError: + from dummy_thread import allocate_lock +else: + try: + from _thread import allocate_lock + except ImportError: + from _dummy_thread import allocate_lock + + +##import sys +##l1 = allocate_lock + +##class allocate_lock(object): +## def __init__(self): +## self._real = l1() +## def __enter__(self): +## for i in range(4, 0, -1): +## print sys._getframe(i).f_code +## print +## return self._real.__enter__() +## def __exit__(self, *args): +## return self._real.__exit__(*args) +## def acquire(self, f): +## assert f is False +## return self._real.acquire(f) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/model.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/model.py new file mode 100644 index 0000000000000000000000000000000000000000..e5f4cae3e84c73cd09980dabd2ec571d455fe0c1 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/model.py @@ -0,0 +1,618 @@ +import types +import weakref + +from .lock import allocate_lock +from .error import CDefError, VerificationError, VerificationMissing + +# type qualifiers +Q_CONST = 0x01 +Q_RESTRICT = 0x02 +Q_VOLATILE = 0x04 + +def qualify(quals, replace_with): + if quals & Q_CONST: + replace_with = ' const ' + replace_with.lstrip() + if quals & Q_VOLATILE: + replace_with = ' volatile ' + replace_with.lstrip() + if quals & Q_RESTRICT: + # It seems that __restrict is supported by gcc and msvc. + # If you hit some different compiler, add a #define in + # _cffi_include.h for it (and in its copies, documented there) + replace_with = ' __restrict ' + replace_with.lstrip() + return replace_with + + +class BaseTypeByIdentity(object): + is_array_type = False + is_raw_function = False + + def get_c_name(self, replace_with='', context='a C file', quals=0): + result = self.c_name_with_marker + assert result.count('&') == 1 + # some logic duplication with ffi.getctype()... :-( + replace_with = replace_with.strip() + if replace_with: + if replace_with.startswith('*') and '&[' in result: + replace_with = '(%s)' % replace_with + elif not replace_with[0] in '[(': + replace_with = ' ' + replace_with + replace_with = qualify(quals, replace_with) + result = result.replace('&', replace_with) + if '$' in result: + raise VerificationError( + "cannot generate '%s' in %s: unknown type name" + % (self._get_c_name(), context)) + return result + + def _get_c_name(self): + return self.c_name_with_marker.replace('&', '') + + def has_c_name(self): + return '$' not in self._get_c_name() + + def is_integer_type(self): + return False + + def get_cached_btype(self, ffi, finishlist, can_delay=False): + try: + BType = ffi._cached_btypes[self] + except KeyError: + BType = self.build_backend_type(ffi, finishlist) + BType2 = ffi._cached_btypes.setdefault(self, BType) + assert BType2 is BType + return BType + + def __repr__(self): + return '<%s>' % (self._get_c_name(),) + + def _get_items(self): + return [(name, getattr(self, name)) for name in self._attrs_] + + +class BaseType(BaseTypeByIdentity): + + def __eq__(self, other): + return (self.__class__ == other.__class__ and + self._get_items() == other._get_items()) + + def __ne__(self, other): + return not self == other + + def __hash__(self): + return hash((self.__class__, tuple(self._get_items()))) + + +class VoidType(BaseType): + _attrs_ = () + + def __init__(self): + self.c_name_with_marker = 'void&' + + def build_backend_type(self, ffi, finishlist): + return global_cache(self, ffi, 'new_void_type') + +void_type = VoidType() + + +class BasePrimitiveType(BaseType): + def is_complex_type(self): + return False + + +class PrimitiveType(BasePrimitiveType): + _attrs_ = ('name',) + + ALL_PRIMITIVE_TYPES = { + 'char': 'c', + 'short': 'i', + 'int': 'i', + 'long': 'i', + 'long long': 'i', + 'signed char': 'i', + 'unsigned char': 'i', + 'unsigned short': 'i', + 'unsigned int': 'i', + 'unsigned long': 'i', + 'unsigned long long': 'i', + 'float': 'f', + 'double': 'f', + 'long double': 'f', + '_cffi_float_complex_t': 'j', + '_cffi_double_complex_t': 'j', + '_Bool': 'i', + # the following types are not primitive in the C sense + 'wchar_t': 'c', + 'char16_t': 'c', + 'char32_t': 'c', + 'int8_t': 'i', + 'uint8_t': 'i', + 'int16_t': 'i', + 'uint16_t': 'i', + 'int32_t': 'i', + 'uint32_t': 'i', + 'int64_t': 'i', + 'uint64_t': 'i', + 'int_least8_t': 'i', + 'uint_least8_t': 'i', + 'int_least16_t': 'i', + 'uint_least16_t': 'i', + 'int_least32_t': 'i', + 'uint_least32_t': 'i', + 'int_least64_t': 'i', + 'uint_least64_t': 'i', + 'int_fast8_t': 'i', + 'uint_fast8_t': 'i', + 'int_fast16_t': 'i', + 'uint_fast16_t': 'i', + 'int_fast32_t': 'i', + 'uint_fast32_t': 'i', + 'int_fast64_t': 'i', + 'uint_fast64_t': 'i', + 'intptr_t': 'i', + 'uintptr_t': 'i', + 'intmax_t': 'i', + 'uintmax_t': 'i', + 'ptrdiff_t': 'i', + 'size_t': 'i', + 'ssize_t': 'i', + } + + def __init__(self, name): + assert name in self.ALL_PRIMITIVE_TYPES + self.name = name + self.c_name_with_marker = name + '&' + + def is_char_type(self): + return self.ALL_PRIMITIVE_TYPES[self.name] == 'c' + def is_integer_type(self): + return self.ALL_PRIMITIVE_TYPES[self.name] == 'i' + def is_float_type(self): + return self.ALL_PRIMITIVE_TYPES[self.name] == 'f' + def is_complex_type(self): + return self.ALL_PRIMITIVE_TYPES[self.name] == 'j' + + def build_backend_type(self, ffi, finishlist): + return global_cache(self, ffi, 'new_primitive_type', self.name) + + +class UnknownIntegerType(BasePrimitiveType): + _attrs_ = ('name',) + + def __init__(self, name): + self.name = name + self.c_name_with_marker = name + '&' + + def is_integer_type(self): + return True + + def build_backend_type(self, ffi, finishlist): + raise NotImplementedError("integer type '%s' can only be used after " + "compilation" % self.name) + +class UnknownFloatType(BasePrimitiveType): + _attrs_ = ('name', ) + + def __init__(self, name): + self.name = name + self.c_name_with_marker = name + '&' + + def build_backend_type(self, ffi, finishlist): + raise NotImplementedError("float type '%s' can only be used after " + "compilation" % self.name) + + +class BaseFunctionType(BaseType): + _attrs_ = ('args', 'result', 'ellipsis', 'abi') + + def __init__(self, args, result, ellipsis, abi=None): + self.args = args + self.result = result + self.ellipsis = ellipsis + self.abi = abi + # + reprargs = [arg._get_c_name() for arg in self.args] + if self.ellipsis: + reprargs.append('...') + reprargs = reprargs or ['void'] + replace_with = self._base_pattern % (', '.join(reprargs),) + if abi is not None: + replace_with = replace_with[:1] + abi + ' ' + replace_with[1:] + self.c_name_with_marker = ( + self.result.c_name_with_marker.replace('&', replace_with)) + + +class RawFunctionType(BaseFunctionType): + # Corresponds to a C type like 'int(int)', which is the C type of + # a function, but not a pointer-to-function. The backend has no + # notion of such a type; it's used temporarily by parsing. + _base_pattern = '(&)(%s)' + is_raw_function = True + + def build_backend_type(self, ffi, finishlist): + raise CDefError("cannot render the type %r: it is a function " + "type, not a pointer-to-function type" % (self,)) + + def as_function_pointer(self): + return FunctionPtrType(self.args, self.result, self.ellipsis, self.abi) + + +class FunctionPtrType(BaseFunctionType): + _base_pattern = '(*&)(%s)' + + def build_backend_type(self, ffi, finishlist): + result = self.result.get_cached_btype(ffi, finishlist) + args = [] + for tp in self.args: + args.append(tp.get_cached_btype(ffi, finishlist)) + abi_args = () + if self.abi == "__stdcall": + if not self.ellipsis: # __stdcall ignored for variadic funcs + try: + abi_args = (ffi._backend.FFI_STDCALL,) + except AttributeError: + pass + return global_cache(self, ffi, 'new_function_type', + tuple(args), result, self.ellipsis, *abi_args) + + def as_raw_function(self): + return RawFunctionType(self.args, self.result, self.ellipsis, self.abi) + + +class PointerType(BaseType): + _attrs_ = ('totype', 'quals') + + def __init__(self, totype, quals=0): + self.totype = totype + self.quals = quals + extra = " *&" + if totype.is_array_type: + extra = "(%s)" % (extra.lstrip(),) + extra = qualify(quals, extra) + self.c_name_with_marker = totype.c_name_with_marker.replace('&', extra) + + def build_backend_type(self, ffi, finishlist): + BItem = self.totype.get_cached_btype(ffi, finishlist, can_delay=True) + return global_cache(self, ffi, 'new_pointer_type', BItem) + +voidp_type = PointerType(void_type) + +def ConstPointerType(totype): + return PointerType(totype, Q_CONST) + +const_voidp_type = ConstPointerType(void_type) + + +class NamedPointerType(PointerType): + _attrs_ = ('totype', 'name') + + def __init__(self, totype, name, quals=0): + PointerType.__init__(self, totype, quals) + self.name = name + self.c_name_with_marker = name + '&' + + +class ArrayType(BaseType): + _attrs_ = ('item', 'length') + is_array_type = True + + def __init__(self, item, length): + self.item = item + self.length = length + # + if length is None: + brackets = '&[]' + elif length == '...': + brackets = '&[/*...*/]' + else: + brackets = '&[%s]' % length + self.c_name_with_marker = ( + self.item.c_name_with_marker.replace('&', brackets)) + + def length_is_unknown(self): + return isinstance(self.length, str) + + def resolve_length(self, newlength): + return ArrayType(self.item, newlength) + + def build_backend_type(self, ffi, finishlist): + if self.length_is_unknown(): + raise CDefError("cannot render the type %r: unknown length" % + (self,)) + self.item.get_cached_btype(ffi, finishlist) # force the item BType + BPtrItem = PointerType(self.item).get_cached_btype(ffi, finishlist) + return global_cache(self, ffi, 'new_array_type', BPtrItem, self.length) + +char_array_type = ArrayType(PrimitiveType('char'), None) + + +class StructOrUnionOrEnum(BaseTypeByIdentity): + _attrs_ = ('name',) + forcename = None + + def build_c_name_with_marker(self): + name = self.forcename or '%s %s' % (self.kind, self.name) + self.c_name_with_marker = name + '&' + + def force_the_name(self, forcename): + self.forcename = forcename + self.build_c_name_with_marker() + + def get_official_name(self): + assert self.c_name_with_marker.endswith('&') + return self.c_name_with_marker[:-1] + + +class StructOrUnion(StructOrUnionOrEnum): + fixedlayout = None + completed = 0 + partial = False + packed = 0 + + def __init__(self, name, fldnames, fldtypes, fldbitsize, fldquals=None): + self.name = name + self.fldnames = fldnames + self.fldtypes = fldtypes + self.fldbitsize = fldbitsize + self.fldquals = fldquals + self.build_c_name_with_marker() + + def anonymous_struct_fields(self): + if self.fldtypes is not None: + for name, type in zip(self.fldnames, self.fldtypes): + if name == '' and isinstance(type, StructOrUnion): + yield type + + def enumfields(self, expand_anonymous_struct_union=True): + fldquals = self.fldquals + if fldquals is None: + fldquals = (0,) * len(self.fldnames) + for name, type, bitsize, quals in zip(self.fldnames, self.fldtypes, + self.fldbitsize, fldquals): + if (name == '' and isinstance(type, StructOrUnion) + and expand_anonymous_struct_union): + # nested anonymous struct/union + for result in type.enumfields(): + yield result + else: + yield (name, type, bitsize, quals) + + def force_flatten(self): + # force the struct or union to have a declaration that lists + # directly all fields returned by enumfields(), flattening + # nested anonymous structs/unions. + names = [] + types = [] + bitsizes = [] + fldquals = [] + for name, type, bitsize, quals in self.enumfields(): + names.append(name) + types.append(type) + bitsizes.append(bitsize) + fldquals.append(quals) + self.fldnames = tuple(names) + self.fldtypes = tuple(types) + self.fldbitsize = tuple(bitsizes) + self.fldquals = tuple(fldquals) + + def get_cached_btype(self, ffi, finishlist, can_delay=False): + BType = StructOrUnionOrEnum.get_cached_btype(self, ffi, finishlist, + can_delay) + if not can_delay: + self.finish_backend_type(ffi, finishlist) + return BType + + def finish_backend_type(self, ffi, finishlist): + if self.completed: + if self.completed != 2: + raise NotImplementedError("recursive structure declaration " + "for '%s'" % (self.name,)) + return + BType = ffi._cached_btypes[self] + # + self.completed = 1 + # + if self.fldtypes is None: + pass # not completing it: it's an opaque struct + # + elif self.fixedlayout is None: + fldtypes = [tp.get_cached_btype(ffi, finishlist) + for tp in self.fldtypes] + lst = list(zip(self.fldnames, fldtypes, self.fldbitsize)) + extra_flags = () + if self.packed: + if self.packed == 1: + extra_flags = (8,) # SF_PACKED + else: + extra_flags = (0, self.packed) + ffi._backend.complete_struct_or_union(BType, lst, self, + -1, -1, *extra_flags) + # + else: + fldtypes = [] + fieldofs, fieldsize, totalsize, totalalignment = self.fixedlayout + for i in range(len(self.fldnames)): + fsize = fieldsize[i] + ftype = self.fldtypes[i] + # + if isinstance(ftype, ArrayType) and ftype.length_is_unknown(): + # fix the length to match the total size + BItemType = ftype.item.get_cached_btype(ffi, finishlist) + nlen, nrest = divmod(fsize, ffi.sizeof(BItemType)) + if nrest != 0: + self._verification_error( + "field '%s.%s' has a bogus size?" % ( + self.name, self.fldnames[i] or '{}')) + ftype = ftype.resolve_length(nlen) + self.fldtypes = (self.fldtypes[:i] + (ftype,) + + self.fldtypes[i+1:]) + # + BFieldType = ftype.get_cached_btype(ffi, finishlist) + if isinstance(ftype, ArrayType) and ftype.length is None: + assert fsize == 0 + else: + bitemsize = ffi.sizeof(BFieldType) + if bitemsize != fsize: + self._verification_error( + "field '%s.%s' is declared as %d bytes, but is " + "really %d bytes" % (self.name, + self.fldnames[i] or '{}', + bitemsize, fsize)) + fldtypes.append(BFieldType) + # + lst = list(zip(self.fldnames, fldtypes, self.fldbitsize, fieldofs)) + ffi._backend.complete_struct_or_union(BType, lst, self, + totalsize, totalalignment) + self.completed = 2 + + def _verification_error(self, msg): + raise VerificationError(msg) + + def check_not_partial(self): + if self.partial and self.fixedlayout is None: + raise VerificationMissing(self._get_c_name()) + + def build_backend_type(self, ffi, finishlist): + self.check_not_partial() + finishlist.append(self) + # + return global_cache(self, ffi, 'new_%s_type' % self.kind, + self.get_official_name(), key=self) + + +class StructType(StructOrUnion): + kind = 'struct' + + +class UnionType(StructOrUnion): + kind = 'union' + + +class EnumType(StructOrUnionOrEnum): + kind = 'enum' + partial = False + partial_resolved = False + + def __init__(self, name, enumerators, enumvalues, baseinttype=None): + self.name = name + self.enumerators = enumerators + self.enumvalues = enumvalues + self.baseinttype = baseinttype + self.build_c_name_with_marker() + + def force_the_name(self, forcename): + StructOrUnionOrEnum.force_the_name(self, forcename) + if self.forcename is None: + name = self.get_official_name() + self.forcename = '$' + name.replace(' ', '_') + + def check_not_partial(self): + if self.partial and not self.partial_resolved: + raise VerificationMissing(self._get_c_name()) + + def build_backend_type(self, ffi, finishlist): + self.check_not_partial() + base_btype = self.build_baseinttype(ffi, finishlist) + return global_cache(self, ffi, 'new_enum_type', + self.get_official_name(), + self.enumerators, self.enumvalues, + base_btype, key=self) + + def build_baseinttype(self, ffi, finishlist): + if self.baseinttype is not None: + return self.baseinttype.get_cached_btype(ffi, finishlist) + # + if self.enumvalues: + smallest_value = min(self.enumvalues) + largest_value = max(self.enumvalues) + else: + import warnings + try: + # XXX! The goal is to ensure that the warnings.warn() + # will not suppress the warning. We want to get it + # several times if we reach this point several times. + __warningregistry__.clear() + except NameError: + pass + warnings.warn("%r has no values explicitly defined; " + "guessing that it is equivalent to 'unsigned int'" + % self._get_c_name()) + smallest_value = largest_value = 0 + if smallest_value < 0: # needs a signed type + sign = 1 + candidate1 = PrimitiveType("int") + candidate2 = PrimitiveType("long") + else: + sign = 0 + candidate1 = PrimitiveType("unsigned int") + candidate2 = PrimitiveType("unsigned long") + btype1 = candidate1.get_cached_btype(ffi, finishlist) + btype2 = candidate2.get_cached_btype(ffi, finishlist) + size1 = ffi.sizeof(btype1) + size2 = ffi.sizeof(btype2) + if (smallest_value >= ((-1) << (8*size1-1)) and + largest_value < (1 << (8*size1-sign))): + return btype1 + if (smallest_value >= ((-1) << (8*size2-1)) and + largest_value < (1 << (8*size2-sign))): + return btype2 + raise CDefError("%s values don't all fit into either 'long' " + "or 'unsigned long'" % self._get_c_name()) + +def unknown_type(name, structname=None): + if structname is None: + structname = '$%s' % name + tp = StructType(structname, None, None, None) + tp.force_the_name(name) + tp.origin = "unknown_type" + return tp + +def unknown_ptr_type(name, structname=None): + if structname is None: + structname = '$$%s' % name + tp = StructType(structname, None, None, None) + return NamedPointerType(tp, name) + + +global_lock = allocate_lock() +_typecache_cffi_backend = weakref.WeakValueDictionary() + +def get_typecache(backend): + # returns _typecache_cffi_backend if backend is the _cffi_backend + # module, or type(backend).__typecache if backend is an instance of + # CTypesBackend (or some FakeBackend class during tests) + if isinstance(backend, types.ModuleType): + return _typecache_cffi_backend + with global_lock: + if not hasattr(type(backend), '__typecache'): + type(backend).__typecache = weakref.WeakValueDictionary() + return type(backend).__typecache + +def global_cache(srctype, ffi, funcname, *args, **kwds): + key = kwds.pop('key', (funcname, args)) + assert not kwds + try: + return ffi._typecache[key] + except KeyError: + pass + try: + res = getattr(ffi._backend, funcname)(*args) + except NotImplementedError as e: + raise NotImplementedError("%s: %r: %s" % (funcname, srctype, e)) + # note that setdefault() on WeakValueDictionary is not atomic + # and contains a rare bug (http://bugs.python.org/issue19542); + # we have to use a lock and do it ourselves + cache = ffi._typecache + with global_lock: + res1 = cache.get(key) + if res1 is None: + cache[key] = res + return res + else: + return res1 + +def pointer_cache(ffi, BType): + return global_cache('?', ffi, 'new_pointer_type', BType) + +def attach_exception_info(e, name): + if e.args and type(e.args[0]) is str: + e.args = ('%s: %s' % (name, e.args[0]),) + e.args[1:] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/parse_c_type.h b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/parse_c_type.h new file mode 100644 index 0000000000000000000000000000000000000000..84e4ef85659eb63e6453d8af9f024f1866182342 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/parse_c_type.h @@ -0,0 +1,181 @@ + +/* This part is from file 'cffi/parse_c_type.h'. It is copied at the + beginning of C sources generated by CFFI's ffi.set_source(). */ + +typedef void *_cffi_opcode_t; + +#define _CFFI_OP(opcode, arg) (_cffi_opcode_t)(opcode | (((uintptr_t)(arg)) << 8)) +#define _CFFI_GETOP(cffi_opcode) ((unsigned char)(uintptr_t)cffi_opcode) +#define _CFFI_GETARG(cffi_opcode) (((intptr_t)cffi_opcode) >> 8) + +#define _CFFI_OP_PRIMITIVE 1 +#define _CFFI_OP_POINTER 3 +#define _CFFI_OP_ARRAY 5 +#define _CFFI_OP_OPEN_ARRAY 7 +#define _CFFI_OP_STRUCT_UNION 9 +#define _CFFI_OP_ENUM 11 +#define _CFFI_OP_FUNCTION 13 +#define _CFFI_OP_FUNCTION_END 15 +#define _CFFI_OP_NOOP 17 +#define _CFFI_OP_BITFIELD 19 +#define _CFFI_OP_TYPENAME 21 +#define _CFFI_OP_CPYTHON_BLTN_V 23 // varargs +#define _CFFI_OP_CPYTHON_BLTN_N 25 // noargs +#define _CFFI_OP_CPYTHON_BLTN_O 27 // O (i.e. a single arg) +#define _CFFI_OP_CONSTANT 29 +#define _CFFI_OP_CONSTANT_INT 31 +#define _CFFI_OP_GLOBAL_VAR 33 +#define _CFFI_OP_DLOPEN_FUNC 35 +#define _CFFI_OP_DLOPEN_CONST 37 +#define _CFFI_OP_GLOBAL_VAR_F 39 +#define _CFFI_OP_EXTERN_PYTHON 41 + +#define _CFFI_PRIM_VOID 0 +#define _CFFI_PRIM_BOOL 1 +#define _CFFI_PRIM_CHAR 2 +#define _CFFI_PRIM_SCHAR 3 +#define _CFFI_PRIM_UCHAR 4 +#define _CFFI_PRIM_SHORT 5 +#define _CFFI_PRIM_USHORT 6 +#define _CFFI_PRIM_INT 7 +#define _CFFI_PRIM_UINT 8 +#define _CFFI_PRIM_LONG 9 +#define _CFFI_PRIM_ULONG 10 +#define _CFFI_PRIM_LONGLONG 11 +#define _CFFI_PRIM_ULONGLONG 12 +#define _CFFI_PRIM_FLOAT 13 +#define _CFFI_PRIM_DOUBLE 14 +#define _CFFI_PRIM_LONGDOUBLE 15 + +#define _CFFI_PRIM_WCHAR 16 +#define _CFFI_PRIM_INT8 17 +#define _CFFI_PRIM_UINT8 18 +#define _CFFI_PRIM_INT16 19 +#define _CFFI_PRIM_UINT16 20 +#define _CFFI_PRIM_INT32 21 +#define _CFFI_PRIM_UINT32 22 +#define _CFFI_PRIM_INT64 23 +#define _CFFI_PRIM_UINT64 24 +#define _CFFI_PRIM_INTPTR 25 +#define _CFFI_PRIM_UINTPTR 26 +#define _CFFI_PRIM_PTRDIFF 27 +#define _CFFI_PRIM_SIZE 28 +#define _CFFI_PRIM_SSIZE 29 +#define _CFFI_PRIM_INT_LEAST8 30 +#define _CFFI_PRIM_UINT_LEAST8 31 +#define _CFFI_PRIM_INT_LEAST16 32 +#define _CFFI_PRIM_UINT_LEAST16 33 +#define _CFFI_PRIM_INT_LEAST32 34 +#define _CFFI_PRIM_UINT_LEAST32 35 +#define _CFFI_PRIM_INT_LEAST64 36 +#define _CFFI_PRIM_UINT_LEAST64 37 +#define _CFFI_PRIM_INT_FAST8 38 +#define _CFFI_PRIM_UINT_FAST8 39 +#define _CFFI_PRIM_INT_FAST16 40 +#define _CFFI_PRIM_UINT_FAST16 41 +#define _CFFI_PRIM_INT_FAST32 42 +#define _CFFI_PRIM_UINT_FAST32 43 +#define _CFFI_PRIM_INT_FAST64 44 +#define _CFFI_PRIM_UINT_FAST64 45 +#define _CFFI_PRIM_INTMAX 46 +#define _CFFI_PRIM_UINTMAX 47 +#define _CFFI_PRIM_FLOATCOMPLEX 48 +#define _CFFI_PRIM_DOUBLECOMPLEX 49 +#define _CFFI_PRIM_CHAR16 50 +#define _CFFI_PRIM_CHAR32 51 + +#define _CFFI__NUM_PRIM 52 +#define _CFFI__UNKNOWN_PRIM (-1) +#define _CFFI__UNKNOWN_FLOAT_PRIM (-2) +#define _CFFI__UNKNOWN_LONG_DOUBLE (-3) + +#define _CFFI__IO_FILE_STRUCT (-1) + + +struct _cffi_global_s { + const char *name; + void *address; + _cffi_opcode_t type_op; + void *size_or_direct_fn; // OP_GLOBAL_VAR: size, or 0 if unknown + // OP_CPYTHON_BLTN_*: addr of direct function +}; + +struct _cffi_getconst_s { + unsigned long long value; + const struct _cffi_type_context_s *ctx; + int gindex; +}; + +struct _cffi_struct_union_s { + const char *name; + int type_index; // -> _cffi_types, on a OP_STRUCT_UNION + int flags; // _CFFI_F_* flags below + size_t size; + int alignment; + int first_field_index; // -> _cffi_fields array + int num_fields; +}; +#define _CFFI_F_UNION 0x01 // is a union, not a struct +#define _CFFI_F_CHECK_FIELDS 0x02 // complain if fields are not in the + // "standard layout" or if some are missing +#define _CFFI_F_PACKED 0x04 // for CHECK_FIELDS, assume a packed struct +#define _CFFI_F_EXTERNAL 0x08 // in some other ffi.include() +#define _CFFI_F_OPAQUE 0x10 // opaque + +struct _cffi_field_s { + const char *name; + size_t field_offset; + size_t field_size; + _cffi_opcode_t field_type_op; +}; + +struct _cffi_enum_s { + const char *name; + int type_index; // -> _cffi_types, on a OP_ENUM + int type_prim; // _CFFI_PRIM_xxx + const char *enumerators; // comma-delimited string +}; + +struct _cffi_typename_s { + const char *name; + int type_index; /* if opaque, points to a possibly artificial + OP_STRUCT which is itself opaque */ +}; + +struct _cffi_type_context_s { + _cffi_opcode_t *types; + const struct _cffi_global_s *globals; + const struct _cffi_field_s *fields; + const struct _cffi_struct_union_s *struct_unions; + const struct _cffi_enum_s *enums; + const struct _cffi_typename_s *typenames; + int num_globals; + int num_struct_unions; + int num_enums; + int num_typenames; + const char *const *includes; + int num_types; + int flags; /* future extension */ +}; + +struct _cffi_parse_info_s { + const struct _cffi_type_context_s *ctx; + _cffi_opcode_t *output; + unsigned int output_size; + size_t error_location; + const char *error_message; +}; + +struct _cffi_externpy_s { + const char *name; + size_t size_of_result; + void *reserved1, *reserved2; +}; + +#ifdef _CFFI_INTERNAL +static int parse_c_type(struct _cffi_parse_info_s *info, const char *input); +static int search_in_globals(const struct _cffi_type_context_s *ctx, + const char *search, size_t search_len); +static int search_in_struct_unions(const struct _cffi_type_context_s *ctx, + const char *search, size_t search_len); +#endif diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/pkgconfig.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/pkgconfig.py new file mode 100644 index 0000000000000000000000000000000000000000..5c93f15a60e6f904b2dd108d6e22044a5890bcb4 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/pkgconfig.py @@ -0,0 +1,121 @@ +# pkg-config, https://www.freedesktop.org/wiki/Software/pkg-config/ integration for cffi +import sys, os, subprocess + +from .error import PkgConfigError + + +def merge_flags(cfg1, cfg2): + """Merge values from cffi config flags cfg2 to cf1 + + Example: + merge_flags({"libraries": ["one"]}, {"libraries": ["two"]}) + {"libraries": ["one", "two"]} + """ + for key, value in cfg2.items(): + if key not in cfg1: + cfg1[key] = value + else: + if not isinstance(cfg1[key], list): + raise TypeError("cfg1[%r] should be a list of strings" % (key,)) + if not isinstance(value, list): + raise TypeError("cfg2[%r] should be a list of strings" % (key,)) + cfg1[key].extend(value) + return cfg1 + + +def call(libname, flag, encoding=sys.getfilesystemencoding()): + """Calls pkg-config and returns the output if found + """ + a = ["pkg-config", "--print-errors"] + a.append(flag) + a.append(libname) + try: + pc = subprocess.Popen(a, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + except EnvironmentError as e: + raise PkgConfigError("cannot run pkg-config: %s" % (str(e).strip(),)) + + bout, berr = pc.communicate() + if pc.returncode != 0: + try: + berr = berr.decode(encoding) + except Exception: + pass + raise PkgConfigError(berr.strip()) + + if sys.version_info >= (3,) and not isinstance(bout, str): # Python 3.x + try: + bout = bout.decode(encoding) + except UnicodeDecodeError: + raise PkgConfigError("pkg-config %s %s returned bytes that cannot " + "be decoded with encoding %r:\n%r" % + (flag, libname, encoding, bout)) + + if os.altsep != '\\' and '\\' in bout: + raise PkgConfigError("pkg-config %s %s returned an unsupported " + "backslash-escaped output:\n%r" % + (flag, libname, bout)) + return bout + + +def flags_from_pkgconfig(libs): + r"""Return compiler line flags for FFI.set_source based on pkg-config output + + Usage + ... + ffibuilder.set_source("_foo", pkgconfig = ["libfoo", "libbar >= 1.8.3"]) + + If pkg-config is installed on build machine, then arguments include_dirs, + library_dirs, libraries, define_macros, extra_compile_args and + extra_link_args are extended with an output of pkg-config for libfoo and + libbar. + + Raises PkgConfigError in case the pkg-config call fails. + """ + + def get_include_dirs(string): + return [x[2:] for x in string.split() if x.startswith("-I")] + + def get_library_dirs(string): + return [x[2:] for x in string.split() if x.startswith("-L")] + + def get_libraries(string): + return [x[2:] for x in string.split() if x.startswith("-l")] + + # convert -Dfoo=bar to list of tuples [("foo", "bar")] expected by distutils + def get_macros(string): + def _macro(x): + x = x[2:] # drop "-D" + if '=' in x: + return tuple(x.split("=", 1)) # "-Dfoo=bar" => ("foo", "bar") + else: + return (x, None) # "-Dfoo" => ("foo", None) + return [_macro(x) for x in string.split() if x.startswith("-D")] + + def get_other_cflags(string): + return [x for x in string.split() if not x.startswith("-I") and + not x.startswith("-D")] + + def get_other_libs(string): + return [x for x in string.split() if not x.startswith("-L") and + not x.startswith("-l")] + + # return kwargs for given libname + def kwargs(libname): + fse = sys.getfilesystemencoding() + all_cflags = call(libname, "--cflags") + all_libs = call(libname, "--libs") + return { + "include_dirs": get_include_dirs(all_cflags), + "library_dirs": get_library_dirs(all_libs), + "libraries": get_libraries(all_libs), + "define_macros": get_macros(all_cflags), + "extra_compile_args": get_other_cflags(all_cflags), + "extra_link_args": get_other_libs(all_libs), + } + + # merge all arguments together + ret = {} + for libname in libs: + lib_flags = kwargs(libname) + merge_flags(ret, lib_flags) + return ret diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/recompiler.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/recompiler.py new file mode 100644 index 0000000000000000000000000000000000000000..7734a34863330766984a00d3ff496393471aebfd --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/recompiler.py @@ -0,0 +1,1598 @@ +import io, os, sys, sysconfig +from . import ffiplatform, model +from .error import VerificationError +from .cffi_opcode import * + +VERSION_BASE = 0x2601 +VERSION_EMBEDDED = 0x2701 +VERSION_CHAR16CHAR32 = 0x2801 + +USE_LIMITED_API = ((sys.platform != 'win32' or sys.version_info < (3, 0) or + sys.version_info >= (3, 5)) and + not sysconfig.get_config_var("Py_GIL_DISABLED")) # free-threaded doesn't yet support limited API + +class GlobalExpr: + def __init__(self, name, address, type_op, size=0, check_value=0): + self.name = name + self.address = address + self.type_op = type_op + self.size = size + self.check_value = check_value + + def as_c_expr(self): + return ' { "%s", (void *)%s, %s, (void *)%s },' % ( + self.name, self.address, self.type_op.as_c_expr(), self.size) + + def as_python_expr(self): + return "b'%s%s',%d" % (self.type_op.as_python_bytes(), self.name, + self.check_value) + +class FieldExpr: + def __init__(self, name, field_offset, field_size, fbitsize, field_type_op): + self.name = name + self.field_offset = field_offset + self.field_size = field_size + self.fbitsize = fbitsize + self.field_type_op = field_type_op + + def as_c_expr(self): + spaces = " " * len(self.name) + return (' { "%s", %s,\n' % (self.name, self.field_offset) + + ' %s %s,\n' % (spaces, self.field_size) + + ' %s %s },' % (spaces, self.field_type_op.as_c_expr())) + + def as_python_expr(self): + raise NotImplementedError + + def as_field_python_expr(self): + if self.field_type_op.op == OP_NOOP: + size_expr = '' + elif self.field_type_op.op == OP_BITFIELD: + size_expr = format_four_bytes(self.fbitsize) + else: + raise NotImplementedError + return "b'%s%s%s'" % (self.field_type_op.as_python_bytes(), + size_expr, + self.name) + +class StructUnionExpr: + def __init__(self, name, type_index, flags, size, alignment, comment, + first_field_index, c_fields): + self.name = name + self.type_index = type_index + self.flags = flags + self.size = size + self.alignment = alignment + self.comment = comment + self.first_field_index = first_field_index + self.c_fields = c_fields + + def as_c_expr(self): + return (' { "%s", %d, %s,' % (self.name, self.type_index, self.flags) + + '\n %s, %s, ' % (self.size, self.alignment) + + '%d, %d ' % (self.first_field_index, len(self.c_fields)) + + ('/* %s */ ' % self.comment if self.comment else '') + + '},') + + def as_python_expr(self): + flags = eval(self.flags, G_FLAGS) + fields_expr = [c_field.as_field_python_expr() + for c_field in self.c_fields] + return "(b'%s%s%s',%s)" % ( + format_four_bytes(self.type_index), + format_four_bytes(flags), + self.name, + ','.join(fields_expr)) + +class EnumExpr: + def __init__(self, name, type_index, size, signed, allenums): + self.name = name + self.type_index = type_index + self.size = size + self.signed = signed + self.allenums = allenums + + def as_c_expr(self): + return (' { "%s", %d, _cffi_prim_int(%s, %s),\n' + ' "%s" },' % (self.name, self.type_index, + self.size, self.signed, self.allenums)) + + def as_python_expr(self): + prim_index = { + (1, 0): PRIM_UINT8, (1, 1): PRIM_INT8, + (2, 0): PRIM_UINT16, (2, 1): PRIM_INT16, + (4, 0): PRIM_UINT32, (4, 1): PRIM_INT32, + (8, 0): PRIM_UINT64, (8, 1): PRIM_INT64, + }[self.size, self.signed] + return "b'%s%s%s\\x00%s'" % (format_four_bytes(self.type_index), + format_four_bytes(prim_index), + self.name, self.allenums) + +class TypenameExpr: + def __init__(self, name, type_index): + self.name = name + self.type_index = type_index + + def as_c_expr(self): + return ' { "%s", %d },' % (self.name, self.type_index) + + def as_python_expr(self): + return "b'%s%s'" % (format_four_bytes(self.type_index), self.name) + + +# ____________________________________________________________ + + +class Recompiler: + _num_externpy = 0 + + def __init__(self, ffi, module_name, target_is_python=False): + self.ffi = ffi + self.module_name = module_name + self.target_is_python = target_is_python + self._version = VERSION_BASE + + def needs_version(self, ver): + self._version = max(self._version, ver) + + def collect_type_table(self): + self._typesdict = {} + self._generate("collecttype") + # + all_decls = sorted(self._typesdict, key=str) + # + # prepare all FUNCTION bytecode sequences first + self.cffi_types = [] + for tp in all_decls: + if tp.is_raw_function: + assert self._typesdict[tp] is None + self._typesdict[tp] = len(self.cffi_types) + self.cffi_types.append(tp) # placeholder + for tp1 in tp.args: + assert isinstance(tp1, (model.VoidType, + model.BasePrimitiveType, + model.PointerType, + model.StructOrUnionOrEnum, + model.FunctionPtrType)) + if self._typesdict[tp1] is None: + self._typesdict[tp1] = len(self.cffi_types) + self.cffi_types.append(tp1) # placeholder + self.cffi_types.append('END') # placeholder + # + # prepare all OTHER bytecode sequences + for tp in all_decls: + if not tp.is_raw_function and self._typesdict[tp] is None: + self._typesdict[tp] = len(self.cffi_types) + self.cffi_types.append(tp) # placeholder + if tp.is_array_type and tp.length is not None: + self.cffi_types.append('LEN') # placeholder + assert None not in self._typesdict.values() + # + # collect all structs and unions and enums + self._struct_unions = {} + self._enums = {} + for tp in all_decls: + if isinstance(tp, model.StructOrUnion): + self._struct_unions[tp] = None + elif isinstance(tp, model.EnumType): + self._enums[tp] = None + for i, tp in enumerate(sorted(self._struct_unions, + key=lambda tp: tp.name)): + self._struct_unions[tp] = i + for i, tp in enumerate(sorted(self._enums, + key=lambda tp: tp.name)): + self._enums[tp] = i + # + # emit all bytecode sequences now + for tp in all_decls: + method = getattr(self, '_emit_bytecode_' + tp.__class__.__name__) + method(tp, self._typesdict[tp]) + # + # consistency check + for op in self.cffi_types: + assert isinstance(op, CffiOp) + self.cffi_types = tuple(self.cffi_types) # don't change any more + + def _enum_fields(self, tp): + # When producing C, expand all anonymous struct/union fields. + # That's necessary to have C code checking the offsets of the + # individual fields contained in them. When producing Python, + # don't do it and instead write it like it is, with the + # corresponding fields having an empty name. Empty names are + # recognized at runtime when we import the generated Python + # file. + expand_anonymous_struct_union = not self.target_is_python + return tp.enumfields(expand_anonymous_struct_union) + + def _do_collect_type(self, tp): + if not isinstance(tp, model.BaseTypeByIdentity): + if isinstance(tp, tuple): + for x in tp: + self._do_collect_type(x) + return + if tp not in self._typesdict: + self._typesdict[tp] = None + if isinstance(tp, model.FunctionPtrType): + self._do_collect_type(tp.as_raw_function()) + elif isinstance(tp, model.StructOrUnion): + if tp.fldtypes is not None and ( + tp not in self.ffi._parser._included_declarations): + for name1, tp1, _, _ in self._enum_fields(tp): + self._do_collect_type(self._field_type(tp, name1, tp1)) + else: + for _, x in tp._get_items(): + self._do_collect_type(x) + + def _generate(self, step_name): + lst = self.ffi._parser._declarations.items() + for name, (tp, quals) in sorted(lst): + kind, realname = name.split(' ', 1) + try: + method = getattr(self, '_generate_cpy_%s_%s' % (kind, + step_name)) + except AttributeError: + raise VerificationError( + "not implemented in recompile(): %r" % name) + try: + self._current_quals = quals + method(tp, realname) + except Exception as e: + model.attach_exception_info(e, name) + raise + + # ---------- + + ALL_STEPS = ["global", "field", "struct_union", "enum", "typename"] + + def collect_step_tables(self): + # collect the declarations for '_cffi_globals', '_cffi_typenames', etc. + self._lsts = {} + for step_name in self.ALL_STEPS: + self._lsts[step_name] = [] + self._seen_struct_unions = set() + self._generate("ctx") + self._add_missing_struct_unions() + # + for step_name in self.ALL_STEPS: + lst = self._lsts[step_name] + if step_name != "field": + lst.sort(key=lambda entry: entry.name) + self._lsts[step_name] = tuple(lst) # don't change any more + # + # check for a possible internal inconsistency: _cffi_struct_unions + # should have been generated with exactly self._struct_unions + lst = self._lsts["struct_union"] + for tp, i in self._struct_unions.items(): + assert i < len(lst) + assert lst[i].name == tp.name + assert len(lst) == len(self._struct_unions) + # same with enums + lst = self._lsts["enum"] + for tp, i in self._enums.items(): + assert i < len(lst) + assert lst[i].name == tp.name + assert len(lst) == len(self._enums) + + # ---------- + + def _prnt(self, what=''): + self._f.write(what + '\n') + + def write_source_to_f(self, f, preamble): + if self.target_is_python: + assert preamble is None + self.write_py_source_to_f(f) + else: + assert preamble is not None + self.write_c_source_to_f(f, preamble) + + def _rel_readlines(self, filename): + g = open(os.path.join(os.path.dirname(__file__), filename), 'r') + lines = g.readlines() + g.close() + return lines + + def write_c_source_to_f(self, f, preamble): + self._f = f + prnt = self._prnt + if self.ffi._embedding is not None: + prnt('#define _CFFI_USE_EMBEDDING') + if not USE_LIMITED_API: + prnt('#define _CFFI_NO_LIMITED_API') + # + # first the '#include' (actually done by inlining the file's content) + lines = self._rel_readlines('_cffi_include.h') + i = lines.index('#include "parse_c_type.h"\n') + lines[i:i+1] = self._rel_readlines('parse_c_type.h') + prnt(''.join(lines)) + # + # if we have ffi._embedding != None, we give it here as a macro + # and include an extra file + base_module_name = self.module_name.split('.')[-1] + if self.ffi._embedding is not None: + prnt('#define _CFFI_MODULE_NAME "%s"' % (self.module_name,)) + prnt('static const char _CFFI_PYTHON_STARTUP_CODE[] = {') + self._print_string_literal_in_array(self.ffi._embedding) + prnt('0 };') + prnt('#ifdef PYPY_VERSION') + prnt('# define _CFFI_PYTHON_STARTUP_FUNC _cffi_pypyinit_%s' % ( + base_module_name,)) + prnt('#elif PY_MAJOR_VERSION >= 3') + prnt('# define _CFFI_PYTHON_STARTUP_FUNC PyInit_%s' % ( + base_module_name,)) + prnt('#else') + prnt('# define _CFFI_PYTHON_STARTUP_FUNC init%s' % ( + base_module_name,)) + prnt('#endif') + lines = self._rel_readlines('_embedding.h') + i = lines.index('#include "_cffi_errors.h"\n') + lines[i:i+1] = self._rel_readlines('_cffi_errors.h') + prnt(''.join(lines)) + self.needs_version(VERSION_EMBEDDED) + # + # then paste the C source given by the user, verbatim. + prnt('/************************************************************/') + prnt() + prnt(preamble) + prnt() + prnt('/************************************************************/') + prnt() + # + # the declaration of '_cffi_types' + prnt('static void *_cffi_types[] = {') + typeindex2type = dict([(i, tp) for (tp, i) in self._typesdict.items()]) + for i, op in enumerate(self.cffi_types): + comment = '' + if i in typeindex2type: + comment = ' // ' + typeindex2type[i]._get_c_name() + prnt('/* %2d */ %s,%s' % (i, op.as_c_expr(), comment)) + if not self.cffi_types: + prnt(' 0') + prnt('};') + prnt() + # + # call generate_cpy_xxx_decl(), for every xxx found from + # ffi._parser._declarations. This generates all the functions. + self._seen_constants = set() + self._generate("decl") + # + # the declaration of '_cffi_globals' and '_cffi_typenames' + nums = {} + for step_name in self.ALL_STEPS: + lst = self._lsts[step_name] + nums[step_name] = len(lst) + if nums[step_name] > 0: + prnt('static const struct _cffi_%s_s _cffi_%ss[] = {' % ( + step_name, step_name)) + for entry in lst: + prnt(entry.as_c_expr()) + prnt('};') + prnt() + # + # the declaration of '_cffi_includes' + if self.ffi._included_ffis: + prnt('static const char * const _cffi_includes[] = {') + for ffi_to_include in self.ffi._included_ffis: + try: + included_module_name, included_source = ( + ffi_to_include._assigned_source[:2]) + except AttributeError: + raise VerificationError( + "ffi object %r includes %r, but the latter has not " + "been prepared with set_source()" % ( + self.ffi, ffi_to_include,)) + if included_source is None: + raise VerificationError( + "not implemented yet: ffi.include() of a Python-based " + "ffi inside a C-based ffi") + prnt(' "%s",' % (included_module_name,)) + prnt(' NULL') + prnt('};') + prnt() + # + # the declaration of '_cffi_type_context' + prnt('static const struct _cffi_type_context_s _cffi_type_context = {') + prnt(' _cffi_types,') + for step_name in self.ALL_STEPS: + if nums[step_name] > 0: + prnt(' _cffi_%ss,' % step_name) + else: + prnt(' NULL, /* no %ss */' % step_name) + for step_name in self.ALL_STEPS: + if step_name != "field": + prnt(' %d, /* num_%ss */' % (nums[step_name], step_name)) + if self.ffi._included_ffis: + prnt(' _cffi_includes,') + else: + prnt(' NULL, /* no includes */') + prnt(' %d, /* num_types */' % (len(self.cffi_types),)) + flags = 0 + if self._num_externpy > 0 or self.ffi._embedding is not None: + flags |= 1 # set to mean that we use extern "Python" + prnt(' %d, /* flags */' % flags) + prnt('};') + prnt() + # + # the init function + prnt('#ifdef __GNUC__') + prnt('# pragma GCC visibility push(default) /* for -fvisibility= */') + prnt('#endif') + prnt() + prnt('#ifdef PYPY_VERSION') + prnt('PyMODINIT_FUNC') + prnt('_cffi_pypyinit_%s(const void *p[])' % (base_module_name,)) + prnt('{') + if flags & 1: + prnt(' if (((intptr_t)p[0]) >= 0x0A03) {') + prnt(' _cffi_call_python_org = ' + '(void(*)(struct _cffi_externpy_s *, char *))p[1];') + prnt(' }') + prnt(' p[0] = (const void *)0x%x;' % self._version) + prnt(' p[1] = &_cffi_type_context;') + prnt('#if PY_MAJOR_VERSION >= 3') + prnt(' return NULL;') + prnt('#endif') + prnt('}') + # on Windows, distutils insists on putting init_cffi_xyz in + # 'export_symbols', so instead of fighting it, just give up and + # give it one + prnt('# ifdef _MSC_VER') + prnt(' PyMODINIT_FUNC') + prnt('# if PY_MAJOR_VERSION >= 3') + prnt(' PyInit_%s(void) { return NULL; }' % (base_module_name,)) + prnt('# else') + prnt(' init%s(void) { }' % (base_module_name,)) + prnt('# endif') + prnt('# endif') + prnt('#elif PY_MAJOR_VERSION >= 3') + prnt('PyMODINIT_FUNC') + prnt('PyInit_%s(void)' % (base_module_name,)) + prnt('{') + prnt(' return _cffi_init("%s", 0x%x, &_cffi_type_context);' % ( + self.module_name, self._version)) + prnt('}') + prnt('#else') + prnt('PyMODINIT_FUNC') + prnt('init%s(void)' % (base_module_name,)) + prnt('{') + prnt(' _cffi_init("%s", 0x%x, &_cffi_type_context);' % ( + self.module_name, self._version)) + prnt('}') + prnt('#endif') + prnt() + prnt('#ifdef __GNUC__') + prnt('# pragma GCC visibility pop') + prnt('#endif') + self._version = None + + def _to_py(self, x): + if isinstance(x, str): + return "b'%s'" % (x,) + if isinstance(x, (list, tuple)): + rep = [self._to_py(item) for item in x] + if len(rep) == 1: + rep.append('') + return "(%s)" % (','.join(rep),) + return x.as_python_expr() # Py2: unicode unexpected; Py3: bytes unexp. + + def write_py_source_to_f(self, f): + self._f = f + prnt = self._prnt + # + # header + prnt("# auto-generated file") + prnt("import _cffi_backend") + # + # the 'import' of the included ffis + num_includes = len(self.ffi._included_ffis or ()) + for i in range(num_includes): + ffi_to_include = self.ffi._included_ffis[i] + try: + included_module_name, included_source = ( + ffi_to_include._assigned_source[:2]) + except AttributeError: + raise VerificationError( + "ffi object %r includes %r, but the latter has not " + "been prepared with set_source()" % ( + self.ffi, ffi_to_include,)) + if included_source is not None: + raise VerificationError( + "not implemented yet: ffi.include() of a C-based " + "ffi inside a Python-based ffi") + prnt('from %s import ffi as _ffi%d' % (included_module_name, i)) + prnt() + prnt("ffi = _cffi_backend.FFI('%s'," % (self.module_name,)) + prnt(" _version = 0x%x," % (self._version,)) + self._version = None + # + # the '_types' keyword argument + self.cffi_types = tuple(self.cffi_types) # don't change any more + types_lst = [op.as_python_bytes() for op in self.cffi_types] + prnt(' _types = %s,' % (self._to_py(''.join(types_lst)),)) + typeindex2type = dict([(i, tp) for (tp, i) in self._typesdict.items()]) + # + # the keyword arguments from ALL_STEPS + for step_name in self.ALL_STEPS: + lst = self._lsts[step_name] + if len(lst) > 0 and step_name != "field": + prnt(' _%ss = %s,' % (step_name, self._to_py(lst))) + # + # the '_includes' keyword argument + if num_includes > 0: + prnt(' _includes = (%s,),' % ( + ', '.join(['_ffi%d' % i for i in range(num_includes)]),)) + # + # the footer + prnt(')') + + # ---------- + + def _gettypenum(self, type): + # a KeyError here is a bug. please report it! :-) + return self._typesdict[type] + + def _convert_funcarg_to_c(self, tp, fromvar, tovar, errcode): + extraarg = '' + if isinstance(tp, model.BasePrimitiveType) and not tp.is_complex_type(): + if tp.is_integer_type() and tp.name != '_Bool': + converter = '_cffi_to_c_int' + extraarg = ', %s' % tp.name + elif isinstance(tp, model.UnknownFloatType): + # don't check with is_float_type(): it may be a 'long + # double' here, and _cffi_to_c_double would loose precision + converter = '(%s)_cffi_to_c_double' % (tp.get_c_name(''),) + else: + cname = tp.get_c_name('') + converter = '(%s)_cffi_to_c_%s' % (cname, + tp.name.replace(' ', '_')) + if cname in ('char16_t', 'char32_t'): + self.needs_version(VERSION_CHAR16CHAR32) + errvalue = '-1' + # + elif isinstance(tp, model.PointerType): + self._convert_funcarg_to_c_ptr_or_array(tp, fromvar, + tovar, errcode) + return + # + elif (isinstance(tp, model.StructOrUnionOrEnum) or + isinstance(tp, model.BasePrimitiveType)): + # a struct (not a struct pointer) as a function argument; + # or, a complex (the same code works) + self._prnt(' if (_cffi_to_c((char *)&%s, _cffi_type(%d), %s) < 0)' + % (tovar, self._gettypenum(tp), fromvar)) + self._prnt(' %s;' % errcode) + return + # + elif isinstance(tp, model.FunctionPtrType): + converter = '(%s)_cffi_to_c_pointer' % tp.get_c_name('') + extraarg = ', _cffi_type(%d)' % self._gettypenum(tp) + errvalue = 'NULL' + # + else: + raise NotImplementedError(tp) + # + self._prnt(' %s = %s(%s%s);' % (tovar, converter, fromvar, extraarg)) + self._prnt(' if (%s == (%s)%s && PyErr_Occurred())' % ( + tovar, tp.get_c_name(''), errvalue)) + self._prnt(' %s;' % errcode) + + def _extra_local_variables(self, tp, localvars, freelines): + if isinstance(tp, model.PointerType): + localvars.add('Py_ssize_t datasize') + localvars.add('struct _cffi_freeme_s *large_args_free = NULL') + freelines.add('if (large_args_free != NULL)' + ' _cffi_free_array_arguments(large_args_free);') + + def _convert_funcarg_to_c_ptr_or_array(self, tp, fromvar, tovar, errcode): + self._prnt(' datasize = _cffi_prepare_pointer_call_argument(') + self._prnt(' _cffi_type(%d), %s, (char **)&%s);' % ( + self._gettypenum(tp), fromvar, tovar)) + self._prnt(' if (datasize != 0) {') + self._prnt(' %s = ((size_t)datasize) <= 640 ? ' + '(%s)alloca((size_t)datasize) : NULL;' % ( + tovar, tp.get_c_name(''))) + self._prnt(' if (_cffi_convert_array_argument(_cffi_type(%d), %s, ' + '(char **)&%s,' % (self._gettypenum(tp), fromvar, tovar)) + self._prnt(' datasize, &large_args_free) < 0)') + self._prnt(' %s;' % errcode) + self._prnt(' }') + + def _convert_expr_from_c(self, tp, var, context): + if isinstance(tp, model.BasePrimitiveType): + if tp.is_integer_type() and tp.name != '_Bool': + return '_cffi_from_c_int(%s, %s)' % (var, tp.name) + elif isinstance(tp, model.UnknownFloatType): + return '_cffi_from_c_double(%s)' % (var,) + elif tp.name != 'long double' and not tp.is_complex_type(): + cname = tp.name.replace(' ', '_') + if cname in ('char16_t', 'char32_t'): + self.needs_version(VERSION_CHAR16CHAR32) + return '_cffi_from_c_%s(%s)' % (cname, var) + else: + return '_cffi_from_c_deref((char *)&%s, _cffi_type(%d))' % ( + var, self._gettypenum(tp)) + elif isinstance(tp, (model.PointerType, model.FunctionPtrType)): + return '_cffi_from_c_pointer((char *)%s, _cffi_type(%d))' % ( + var, self._gettypenum(tp)) + elif isinstance(tp, model.ArrayType): + return '_cffi_from_c_pointer((char *)%s, _cffi_type(%d))' % ( + var, self._gettypenum(model.PointerType(tp.item))) + elif isinstance(tp, model.StructOrUnion): + if tp.fldnames is None: + raise TypeError("'%s' is used as %s, but is opaque" % ( + tp._get_c_name(), context)) + return '_cffi_from_c_struct((char *)&%s, _cffi_type(%d))' % ( + var, self._gettypenum(tp)) + elif isinstance(tp, model.EnumType): + return '_cffi_from_c_deref((char *)&%s, _cffi_type(%d))' % ( + var, self._gettypenum(tp)) + else: + raise NotImplementedError(tp) + + # ---------- + # typedefs + + def _typedef_type(self, tp, name): + return self._global_type(tp, "(*(%s *)0)" % (name,)) + + def _generate_cpy_typedef_collecttype(self, tp, name): + self._do_collect_type(self._typedef_type(tp, name)) + + def _generate_cpy_typedef_decl(self, tp, name): + pass + + def _typedef_ctx(self, tp, name): + type_index = self._typesdict[tp] + self._lsts["typename"].append(TypenameExpr(name, type_index)) + + def _generate_cpy_typedef_ctx(self, tp, name): + tp = self._typedef_type(tp, name) + self._typedef_ctx(tp, name) + if getattr(tp, "origin", None) == "unknown_type": + self._struct_ctx(tp, tp.name, approxname=None) + elif isinstance(tp, model.NamedPointerType): + self._struct_ctx(tp.totype, tp.totype.name, approxname=tp.name, + named_ptr=tp) + + # ---------- + # function declarations + + def _generate_cpy_function_collecttype(self, tp, name): + self._do_collect_type(tp.as_raw_function()) + if tp.ellipsis and not self.target_is_python: + self._do_collect_type(tp) + + def _generate_cpy_function_decl(self, tp, name): + assert not self.target_is_python + assert isinstance(tp, model.FunctionPtrType) + if tp.ellipsis: + # cannot support vararg functions better than this: check for its + # exact type (including the fixed arguments), and build it as a + # constant function pointer (no CPython wrapper) + self._generate_cpy_constant_decl(tp, name) + return + prnt = self._prnt + numargs = len(tp.args) + if numargs == 0: + argname = 'noarg' + elif numargs == 1: + argname = 'arg0' + else: + argname = 'args' + # + # ------------------------------ + # the 'd' version of the function, only for addressof(lib, 'func') + arguments = [] + call_arguments = [] + context = 'argument of %s' % name + for i, type in enumerate(tp.args): + arguments.append(type.get_c_name(' x%d' % i, context)) + call_arguments.append('x%d' % i) + repr_arguments = ', '.join(arguments) + repr_arguments = repr_arguments or 'void' + if tp.abi: + abi = tp.abi + ' ' + else: + abi = '' + name_and_arguments = '%s_cffi_d_%s(%s)' % (abi, name, repr_arguments) + prnt('static %s' % (tp.result.get_c_name(name_and_arguments),)) + prnt('{') + call_arguments = ', '.join(call_arguments) + result_code = 'return ' + if isinstance(tp.result, model.VoidType): + result_code = '' + prnt(' %s%s(%s);' % (result_code, name, call_arguments)) + prnt('}') + # + prnt('#ifndef PYPY_VERSION') # ------------------------------ + # + prnt('static PyObject *') + prnt('_cffi_f_%s(PyObject *self, PyObject *%s)' % (name, argname)) + prnt('{') + # + context = 'argument of %s' % name + for i, type in enumerate(tp.args): + arg = type.get_c_name(' x%d' % i, context) + prnt(' %s;' % arg) + # + localvars = set() + freelines = set() + for type in tp.args: + self._extra_local_variables(type, localvars, freelines) + for decl in sorted(localvars): + prnt(' %s;' % (decl,)) + # + if not isinstance(tp.result, model.VoidType): + result_code = 'result = ' + context = 'result of %s' % name + result_decl = ' %s;' % tp.result.get_c_name(' result', context) + prnt(result_decl) + prnt(' PyObject *pyresult;') + else: + result_decl = None + result_code = '' + # + if len(tp.args) > 1: + rng = range(len(tp.args)) + for i in rng: + prnt(' PyObject *arg%d;' % i) + prnt() + prnt(' if (!PyArg_UnpackTuple(args, "%s", %d, %d, %s))' % ( + name, len(rng), len(rng), + ', '.join(['&arg%d' % i for i in rng]))) + prnt(' return NULL;') + prnt() + # + for i, type in enumerate(tp.args): + self._convert_funcarg_to_c(type, 'arg%d' % i, 'x%d' % i, + 'return NULL') + prnt() + # + prnt(' Py_BEGIN_ALLOW_THREADS') + prnt(' _cffi_restore_errno();') + call_arguments = ['x%d' % i for i in range(len(tp.args))] + call_arguments = ', '.join(call_arguments) + prnt(' { %s%s(%s); }' % (result_code, name, call_arguments)) + prnt(' _cffi_save_errno();') + prnt(' Py_END_ALLOW_THREADS') + prnt() + # + prnt(' (void)self; /* unused */') + if numargs == 0: + prnt(' (void)noarg; /* unused */') + if result_code: + prnt(' pyresult = %s;' % + self._convert_expr_from_c(tp.result, 'result', 'result type')) + for freeline in freelines: + prnt(' ' + freeline) + prnt(' return pyresult;') + else: + for freeline in freelines: + prnt(' ' + freeline) + prnt(' Py_INCREF(Py_None);') + prnt(' return Py_None;') + prnt('}') + # + prnt('#else') # ------------------------------ + # + # the PyPy version: need to replace struct/union arguments with + # pointers, and if the result is a struct/union, insert a first + # arg that is a pointer to the result. We also do that for + # complex args and return type. + def need_indirection(type): + return (isinstance(type, model.StructOrUnion) or + (isinstance(type, model.PrimitiveType) and + type.is_complex_type())) + difference = False + arguments = [] + call_arguments = [] + context = 'argument of %s' % name + for i, type in enumerate(tp.args): + indirection = '' + if need_indirection(type): + indirection = '*' + difference = True + arg = type.get_c_name(' %sx%d' % (indirection, i), context) + arguments.append(arg) + call_arguments.append('%sx%d' % (indirection, i)) + tp_result = tp.result + if need_indirection(tp_result): + context = 'result of %s' % name + arg = tp_result.get_c_name(' *result', context) + arguments.insert(0, arg) + tp_result = model.void_type + result_decl = None + result_code = '*result = ' + difference = True + if difference: + repr_arguments = ', '.join(arguments) + repr_arguments = repr_arguments or 'void' + name_and_arguments = '%s_cffi_f_%s(%s)' % (abi, name, + repr_arguments) + prnt('static %s' % (tp_result.get_c_name(name_and_arguments),)) + prnt('{') + if result_decl: + prnt(result_decl) + call_arguments = ', '.join(call_arguments) + prnt(' { %s%s(%s); }' % (result_code, name, call_arguments)) + if result_decl: + prnt(' return result;') + prnt('}') + else: + prnt('# define _cffi_f_%s _cffi_d_%s' % (name, name)) + # + prnt('#endif') # ------------------------------ + prnt() + + def _generate_cpy_function_ctx(self, tp, name): + if tp.ellipsis and not self.target_is_python: + self._generate_cpy_constant_ctx(tp, name) + return + type_index = self._typesdict[tp.as_raw_function()] + numargs = len(tp.args) + if self.target_is_python: + meth_kind = OP_DLOPEN_FUNC + elif numargs == 0: + meth_kind = OP_CPYTHON_BLTN_N # 'METH_NOARGS' + elif numargs == 1: + meth_kind = OP_CPYTHON_BLTN_O # 'METH_O' + else: + meth_kind = OP_CPYTHON_BLTN_V # 'METH_VARARGS' + self._lsts["global"].append( + GlobalExpr(name, '_cffi_f_%s' % name, + CffiOp(meth_kind, type_index), + size='_cffi_d_%s' % name)) + + # ---------- + # named structs or unions + + def _field_type(self, tp_struct, field_name, tp_field): + if isinstance(tp_field, model.ArrayType): + actual_length = tp_field.length + if actual_length == '...': + ptr_struct_name = tp_struct.get_c_name('*') + actual_length = '_cffi_array_len(((%s)0)->%s)' % ( + ptr_struct_name, field_name) + tp_item = self._field_type(tp_struct, '%s[0]' % field_name, + tp_field.item) + tp_field = model.ArrayType(tp_item, actual_length) + return tp_field + + def _struct_collecttype(self, tp): + self._do_collect_type(tp) + if self.target_is_python: + # also requires nested anon struct/unions in ABI mode, recursively + for fldtype in tp.anonymous_struct_fields(): + self._struct_collecttype(fldtype) + + def _struct_decl(self, tp, cname, approxname): + if tp.fldtypes is None: + return + prnt = self._prnt + checkfuncname = '_cffi_checkfld_%s' % (approxname,) + prnt('_CFFI_UNUSED_FN') + prnt('static void %s(%s *p)' % (checkfuncname, cname)) + prnt('{') + prnt(' /* only to generate compile-time warnings or errors */') + prnt(' (void)p;') + for fname, ftype, fbitsize, fqual in self._enum_fields(tp): + try: + if ftype.is_integer_type() or fbitsize >= 0: + # accept all integers, but complain on float or double + if fname != '': + prnt(" (void)((p->%s) | 0); /* check that '%s.%s' is " + "an integer */" % (fname, cname, fname)) + continue + # only accept exactly the type declared, except that '[]' + # is interpreted as a '*' and so will match any array length. + # (It would also match '*', but that's harder to detect...) + while (isinstance(ftype, model.ArrayType) + and (ftype.length is None or ftype.length == '...')): + ftype = ftype.item + fname = fname + '[0]' + prnt(' { %s = &p->%s; (void)tmp; }' % ( + ftype.get_c_name('*tmp', 'field %r'%fname, quals=fqual), + fname)) + except VerificationError as e: + prnt(' /* %s */' % str(e)) # cannot verify it, ignore + prnt('}') + prnt('struct _cffi_align_%s { char x; %s y; };' % (approxname, cname)) + prnt() + + def _struct_ctx(self, tp, cname, approxname, named_ptr=None): + type_index = self._typesdict[tp] + reason_for_not_expanding = None + flags = [] + if isinstance(tp, model.UnionType): + flags.append("_CFFI_F_UNION") + if tp.fldtypes is None: + flags.append("_CFFI_F_OPAQUE") + reason_for_not_expanding = "opaque" + if (tp not in self.ffi._parser._included_declarations and + (named_ptr is None or + named_ptr not in self.ffi._parser._included_declarations)): + if tp.fldtypes is None: + pass # opaque + elif tp.partial or any(tp.anonymous_struct_fields()): + pass # field layout obtained silently from the C compiler + else: + flags.append("_CFFI_F_CHECK_FIELDS") + if tp.packed: + if tp.packed > 1: + raise NotImplementedError( + "%r is declared with 'pack=%r'; only 0 or 1 are " + "supported in API mode (try to use \"...;\", which " + "does not require a 'pack' declaration)" % + (tp, tp.packed)) + flags.append("_CFFI_F_PACKED") + else: + flags.append("_CFFI_F_EXTERNAL") + reason_for_not_expanding = "external" + flags = '|'.join(flags) or '0' + c_fields = [] + if reason_for_not_expanding is None: + enumfields = list(self._enum_fields(tp)) + for fldname, fldtype, fbitsize, fqual in enumfields: + fldtype = self._field_type(tp, fldname, fldtype) + self._check_not_opaque(fldtype, + "field '%s.%s'" % (tp.name, fldname)) + # cname is None for _add_missing_struct_unions() only + op = OP_NOOP + if fbitsize >= 0: + op = OP_BITFIELD + size = '%d /* bits */' % fbitsize + elif cname is None or ( + isinstance(fldtype, model.ArrayType) and + fldtype.length is None): + size = '(size_t)-1' + else: + size = 'sizeof(((%s)0)->%s)' % ( + tp.get_c_name('*') if named_ptr is None + else named_ptr.name, + fldname) + if cname is None or fbitsize >= 0: + offset = '(size_t)-1' + elif named_ptr is not None: + offset = '(size_t)(((char *)&((%s)4096)->%s) - (char *)4096)' % ( + named_ptr.name, fldname) + else: + offset = 'offsetof(%s, %s)' % (tp.get_c_name(''), fldname) + c_fields.append( + FieldExpr(fldname, offset, size, fbitsize, + CffiOp(op, self._typesdict[fldtype]))) + first_field_index = len(self._lsts["field"]) + self._lsts["field"].extend(c_fields) + # + if cname is None: # unknown name, for _add_missing_struct_unions + size = '(size_t)-2' + align = -2 + comment = "unnamed" + else: + if named_ptr is not None: + size = 'sizeof(*(%s)0)' % (named_ptr.name,) + align = '-1 /* unknown alignment */' + else: + size = 'sizeof(%s)' % (cname,) + align = 'offsetof(struct _cffi_align_%s, y)' % (approxname,) + comment = None + else: + size = '(size_t)-1' + align = -1 + first_field_index = -1 + comment = reason_for_not_expanding + self._lsts["struct_union"].append( + StructUnionExpr(tp.name, type_index, flags, size, align, comment, + first_field_index, c_fields)) + self._seen_struct_unions.add(tp) + + def _check_not_opaque(self, tp, location): + while isinstance(tp, model.ArrayType): + tp = tp.item + if isinstance(tp, model.StructOrUnion) and tp.fldtypes is None: + raise TypeError( + "%s is of an opaque type (not declared in cdef())" % location) + + def _add_missing_struct_unions(self): + # not very nice, but some struct declarations might be missing + # because they don't have any known C name. Check that they are + # not partial (we can't complete or verify them!) and emit them + # anonymously. + lst = list(self._struct_unions.items()) + lst.sort(key=lambda tp_order: tp_order[1]) + for tp, order in lst: + if tp not in self._seen_struct_unions: + if tp.partial: + raise NotImplementedError("internal inconsistency: %r is " + "partial but was not seen at " + "this point" % (tp,)) + if tp.name.startswith('$') and tp.name[1:].isdigit(): + approxname = tp.name[1:] + elif tp.name == '_IO_FILE' and tp.forcename == 'FILE': + approxname = 'FILE' + self._typedef_ctx(tp, 'FILE') + else: + raise NotImplementedError("internal inconsistency: %r" % + (tp,)) + self._struct_ctx(tp, None, approxname) + + def _generate_cpy_struct_collecttype(self, tp, name): + self._struct_collecttype(tp) + _generate_cpy_union_collecttype = _generate_cpy_struct_collecttype + + def _struct_names(self, tp): + cname = tp.get_c_name('') + if ' ' in cname: + return cname, cname.replace(' ', '_') + else: + return cname, '_' + cname + + def _generate_cpy_struct_decl(self, tp, name): + self._struct_decl(tp, *self._struct_names(tp)) + _generate_cpy_union_decl = _generate_cpy_struct_decl + + def _generate_cpy_struct_ctx(self, tp, name): + self._struct_ctx(tp, *self._struct_names(tp)) + _generate_cpy_union_ctx = _generate_cpy_struct_ctx + + # ---------- + # 'anonymous' declarations. These are produced for anonymous structs + # or unions; the 'name' is obtained by a typedef. + + def _generate_cpy_anonymous_collecttype(self, tp, name): + if isinstance(tp, model.EnumType): + self._generate_cpy_enum_collecttype(tp, name) + else: + self._struct_collecttype(tp) + + def _generate_cpy_anonymous_decl(self, tp, name): + if isinstance(tp, model.EnumType): + self._generate_cpy_enum_decl(tp) + else: + self._struct_decl(tp, name, 'typedef_' + name) + + def _generate_cpy_anonymous_ctx(self, tp, name): + if isinstance(tp, model.EnumType): + self._enum_ctx(tp, name) + else: + self._struct_ctx(tp, name, 'typedef_' + name) + + # ---------- + # constants, declared with "static const ..." + + def _generate_cpy_const(self, is_int, name, tp=None, category='const', + check_value=None): + if (category, name) in self._seen_constants: + raise VerificationError( + "duplicate declaration of %s '%s'" % (category, name)) + self._seen_constants.add((category, name)) + # + prnt = self._prnt + funcname = '_cffi_%s_%s' % (category, name) + if is_int: + prnt('static int %s(unsigned long long *o)' % funcname) + prnt('{') + prnt(' int n = (%s) <= 0;' % (name,)) + prnt(' *o = (unsigned long long)((%s) | 0);' + ' /* check that %s is an integer */' % (name, name)) + if check_value is not None: + if check_value > 0: + check_value = '%dU' % (check_value,) + prnt(' if (!_cffi_check_int(*o, n, %s))' % (check_value,)) + prnt(' n |= 2;') + prnt(' return n;') + prnt('}') + else: + assert check_value is None + prnt('static void %s(char *o)' % funcname) + prnt('{') + prnt(' *(%s)o = %s;' % (tp.get_c_name('*'), name)) + prnt('}') + prnt() + + def _generate_cpy_constant_collecttype(self, tp, name): + is_int = tp.is_integer_type() + if not is_int or self.target_is_python: + self._do_collect_type(tp) + + def _generate_cpy_constant_decl(self, tp, name): + is_int = tp.is_integer_type() + self._generate_cpy_const(is_int, name, tp) + + def _generate_cpy_constant_ctx(self, tp, name): + if not self.target_is_python and tp.is_integer_type(): + type_op = CffiOp(OP_CONSTANT_INT, -1) + else: + if self.target_is_python: + const_kind = OP_DLOPEN_CONST + else: + const_kind = OP_CONSTANT + type_index = self._typesdict[tp] + type_op = CffiOp(const_kind, type_index) + self._lsts["global"].append( + GlobalExpr(name, '_cffi_const_%s' % name, type_op)) + + # ---------- + # enums + + def _generate_cpy_enum_collecttype(self, tp, name): + self._do_collect_type(tp) + + def _generate_cpy_enum_decl(self, tp, name=None): + for enumerator in tp.enumerators: + self._generate_cpy_const(True, enumerator) + + def _enum_ctx(self, tp, cname): + type_index = self._typesdict[tp] + type_op = CffiOp(OP_ENUM, -1) + if self.target_is_python: + tp.check_not_partial() + for enumerator, enumvalue in zip(tp.enumerators, tp.enumvalues): + self._lsts["global"].append( + GlobalExpr(enumerator, '_cffi_const_%s' % enumerator, type_op, + check_value=enumvalue)) + # + if cname is not None and '$' not in cname and not self.target_is_python: + size = "sizeof(%s)" % cname + signed = "((%s)-1) <= 0" % cname + else: + basetp = tp.build_baseinttype(self.ffi, []) + size = self.ffi.sizeof(basetp) + signed = int(int(self.ffi.cast(basetp, -1)) < 0) + allenums = ",".join(tp.enumerators) + self._lsts["enum"].append( + EnumExpr(tp.name, type_index, size, signed, allenums)) + + def _generate_cpy_enum_ctx(self, tp, name): + self._enum_ctx(tp, tp._get_c_name()) + + # ---------- + # macros: for now only for integers + + def _generate_cpy_macro_collecttype(self, tp, name): + pass + + def _generate_cpy_macro_decl(self, tp, name): + if tp == '...': + check_value = None + else: + check_value = tp # an integer + self._generate_cpy_const(True, name, check_value=check_value) + + def _generate_cpy_macro_ctx(self, tp, name): + if tp == '...': + if self.target_is_python: + raise VerificationError( + "cannot use the syntax '...' in '#define %s ...' when " + "using the ABI mode" % (name,)) + check_value = None + else: + check_value = tp # an integer + type_op = CffiOp(OP_CONSTANT_INT, -1) + self._lsts["global"].append( + GlobalExpr(name, '_cffi_const_%s' % name, type_op, + check_value=check_value)) + + # ---------- + # global variables + + def _global_type(self, tp, global_name): + if isinstance(tp, model.ArrayType): + actual_length = tp.length + if actual_length == '...': + actual_length = '_cffi_array_len(%s)' % (global_name,) + tp_item = self._global_type(tp.item, '%s[0]' % global_name) + tp = model.ArrayType(tp_item, actual_length) + return tp + + def _generate_cpy_variable_collecttype(self, tp, name): + self._do_collect_type(self._global_type(tp, name)) + + def _generate_cpy_variable_decl(self, tp, name): + prnt = self._prnt + tp = self._global_type(tp, name) + if isinstance(tp, model.ArrayType) and tp.length is None: + tp = tp.item + ampersand = '' + else: + ampersand = '&' + # This code assumes that casts from "tp *" to "void *" is a + # no-op, i.e. a function that returns a "tp *" can be called + # as if it returned a "void *". This should be generally true + # on any modern machine. The only exception to that rule (on + # uncommon architectures, and as far as I can tell) might be + # if 'tp' were a function type, but that is not possible here. + # (If 'tp' is a function _pointer_ type, then casts from "fn_t + # **" to "void *" are again no-ops, as far as I can tell.) + decl = '*_cffi_var_%s(void)' % (name,) + prnt('static ' + tp.get_c_name(decl, quals=self._current_quals)) + prnt('{') + prnt(' return %s(%s);' % (ampersand, name)) + prnt('}') + prnt() + + def _generate_cpy_variable_ctx(self, tp, name): + tp = self._global_type(tp, name) + type_index = self._typesdict[tp] + if self.target_is_python: + op = OP_GLOBAL_VAR + else: + op = OP_GLOBAL_VAR_F + self._lsts["global"].append( + GlobalExpr(name, '_cffi_var_%s' % name, CffiOp(op, type_index))) + + # ---------- + # extern "Python" + + def _generate_cpy_extern_python_collecttype(self, tp, name): + assert isinstance(tp, model.FunctionPtrType) + self._do_collect_type(tp) + _generate_cpy_dllexport_python_collecttype = \ + _generate_cpy_extern_python_plus_c_collecttype = \ + _generate_cpy_extern_python_collecttype + + def _extern_python_decl(self, tp, name, tag_and_space): + prnt = self._prnt + if isinstance(tp.result, model.VoidType): + size_of_result = '0' + else: + context = 'result of %s' % name + size_of_result = '(int)sizeof(%s)' % ( + tp.result.get_c_name('', context),) + prnt('static struct _cffi_externpy_s _cffi_externpy__%s =' % name) + prnt(' { "%s.%s", %s, 0, 0 };' % ( + self.module_name, name, size_of_result)) + prnt() + # + arguments = [] + context = 'argument of %s' % name + for i, type in enumerate(tp.args): + arg = type.get_c_name(' a%d' % i, context) + arguments.append(arg) + # + repr_arguments = ', '.join(arguments) + repr_arguments = repr_arguments or 'void' + name_and_arguments = '%s(%s)' % (name, repr_arguments) + if tp.abi == "__stdcall": + name_and_arguments = '_cffi_stdcall ' + name_and_arguments + # + def may_need_128_bits(tp): + return (isinstance(tp, model.PrimitiveType) and + tp.name == 'long double') + # + size_of_a = max(len(tp.args)*8, 8) + if may_need_128_bits(tp.result): + size_of_a = max(size_of_a, 16) + if isinstance(tp.result, model.StructOrUnion): + size_of_a = 'sizeof(%s) > %d ? sizeof(%s) : %d' % ( + tp.result.get_c_name(''), size_of_a, + tp.result.get_c_name(''), size_of_a) + prnt('%s%s' % (tag_and_space, tp.result.get_c_name(name_and_arguments))) + prnt('{') + prnt(' char a[%s];' % size_of_a) + prnt(' char *p = a;') + for i, type in enumerate(tp.args): + arg = 'a%d' % i + if (isinstance(type, model.StructOrUnion) or + may_need_128_bits(type)): + arg = '&' + arg + type = model.PointerType(type) + prnt(' *(%s)(p + %d) = %s;' % (type.get_c_name('*'), i*8, arg)) + prnt(' _cffi_call_python(&_cffi_externpy__%s, p);' % name) + if not isinstance(tp.result, model.VoidType): + prnt(' return *(%s)p;' % (tp.result.get_c_name('*'),)) + prnt('}') + prnt() + self._num_externpy += 1 + + def _generate_cpy_extern_python_decl(self, tp, name): + self._extern_python_decl(tp, name, 'static ') + + def _generate_cpy_dllexport_python_decl(self, tp, name): + self._extern_python_decl(tp, name, 'CFFI_DLLEXPORT ') + + def _generate_cpy_extern_python_plus_c_decl(self, tp, name): + self._extern_python_decl(tp, name, '') + + def _generate_cpy_extern_python_ctx(self, tp, name): + if self.target_is_python: + raise VerificationError( + "cannot use 'extern \"Python\"' in the ABI mode") + if tp.ellipsis: + raise NotImplementedError("a vararg function is extern \"Python\"") + type_index = self._typesdict[tp] + type_op = CffiOp(OP_EXTERN_PYTHON, type_index) + self._lsts["global"].append( + GlobalExpr(name, '&_cffi_externpy__%s' % name, type_op, name)) + + _generate_cpy_dllexport_python_ctx = \ + _generate_cpy_extern_python_plus_c_ctx = \ + _generate_cpy_extern_python_ctx + + def _print_string_literal_in_array(self, s): + prnt = self._prnt + prnt('// # NB. this is not a string because of a size limit in MSVC') + if not isinstance(s, bytes): # unicode + s = s.encode('utf-8') # -> bytes + else: + s.decode('utf-8') # got bytes, check for valid utf-8 + try: + s.decode('ascii') + except UnicodeDecodeError: + s = b'# -*- encoding: utf8 -*-\n' + s + for line in s.splitlines(True): + comment = line + if type('//') is bytes: # python2 + line = map(ord, line) # make a list of integers + else: # python3 + # type(line) is bytes, which enumerates like a list of integers + comment = ascii(comment)[1:-1] + prnt(('// ' + comment).rstrip()) + printed_line = '' + for c in line: + if len(printed_line) >= 76: + prnt(printed_line) + printed_line = '' + printed_line += '%d,' % (c,) + prnt(printed_line) + + # ---------- + # emitting the opcodes for individual types + + def _emit_bytecode_VoidType(self, tp, index): + self.cffi_types[index] = CffiOp(OP_PRIMITIVE, PRIM_VOID) + + def _emit_bytecode_PrimitiveType(self, tp, index): + prim_index = PRIMITIVE_TO_INDEX[tp.name] + self.cffi_types[index] = CffiOp(OP_PRIMITIVE, prim_index) + + def _emit_bytecode_UnknownIntegerType(self, tp, index): + s = ('_cffi_prim_int(sizeof(%s), (\n' + ' ((%s)-1) | 0 /* check that %s is an integer type */\n' + ' ) <= 0)' % (tp.name, tp.name, tp.name)) + self.cffi_types[index] = CffiOp(OP_PRIMITIVE, s) + + def _emit_bytecode_UnknownFloatType(self, tp, index): + s = ('_cffi_prim_float(sizeof(%s) *\n' + ' (((%s)1) / 2) * 2 /* integer => 0, float => 1 */\n' + ' )' % (tp.name, tp.name)) + self.cffi_types[index] = CffiOp(OP_PRIMITIVE, s) + + def _emit_bytecode_RawFunctionType(self, tp, index): + self.cffi_types[index] = CffiOp(OP_FUNCTION, self._typesdict[tp.result]) + index += 1 + for tp1 in tp.args: + realindex = self._typesdict[tp1] + if index != realindex: + if isinstance(tp1, model.PrimitiveType): + self._emit_bytecode_PrimitiveType(tp1, index) + else: + self.cffi_types[index] = CffiOp(OP_NOOP, realindex) + index += 1 + flags = int(tp.ellipsis) + if tp.abi is not None: + if tp.abi == '__stdcall': + flags |= 2 + else: + raise NotImplementedError("abi=%r" % (tp.abi,)) + self.cffi_types[index] = CffiOp(OP_FUNCTION_END, flags) + + def _emit_bytecode_PointerType(self, tp, index): + self.cffi_types[index] = CffiOp(OP_POINTER, self._typesdict[tp.totype]) + + _emit_bytecode_ConstPointerType = _emit_bytecode_PointerType + _emit_bytecode_NamedPointerType = _emit_bytecode_PointerType + + def _emit_bytecode_FunctionPtrType(self, tp, index): + raw = tp.as_raw_function() + self.cffi_types[index] = CffiOp(OP_POINTER, self._typesdict[raw]) + + def _emit_bytecode_ArrayType(self, tp, index): + item_index = self._typesdict[tp.item] + if tp.length is None: + self.cffi_types[index] = CffiOp(OP_OPEN_ARRAY, item_index) + elif tp.length == '...': + raise VerificationError( + "type %s badly placed: the '...' array length can only be " + "used on global arrays or on fields of structures" % ( + str(tp).replace('/*...*/', '...'),)) + else: + assert self.cffi_types[index + 1] == 'LEN' + self.cffi_types[index] = CffiOp(OP_ARRAY, item_index) + self.cffi_types[index + 1] = CffiOp(None, str(tp.length)) + + def _emit_bytecode_StructType(self, tp, index): + struct_index = self._struct_unions[tp] + self.cffi_types[index] = CffiOp(OP_STRUCT_UNION, struct_index) + _emit_bytecode_UnionType = _emit_bytecode_StructType + + def _emit_bytecode_EnumType(self, tp, index): + enum_index = self._enums[tp] + self.cffi_types[index] = CffiOp(OP_ENUM, enum_index) + + +if sys.version_info >= (3,): + NativeIO = io.StringIO +else: + class NativeIO(io.BytesIO): + def write(self, s): + if isinstance(s, unicode): + s = s.encode('ascii') + super(NativeIO, self).write(s) + +def _is_file_like(maybefile): + # compare to xml.etree.ElementTree._get_writer + return hasattr(maybefile, 'write') + +def _make_c_or_py_source(ffi, module_name, preamble, target_file, verbose): + if verbose: + print("generating %s" % (target_file,)) + recompiler = Recompiler(ffi, module_name, + target_is_python=(preamble is None)) + recompiler.collect_type_table() + recompiler.collect_step_tables() + if _is_file_like(target_file): + recompiler.write_source_to_f(target_file, preamble) + return True + f = NativeIO() + recompiler.write_source_to_f(f, preamble) + output = f.getvalue() + try: + with open(target_file, 'r') as f1: + if f1.read(len(output) + 1) != output: + raise IOError + if verbose: + print("(already up-to-date)") + return False # already up-to-date + except IOError: + tmp_file = '%s.~%d' % (target_file, os.getpid()) + with open(tmp_file, 'w') as f1: + f1.write(output) + try: + os.rename(tmp_file, target_file) + except OSError: + os.unlink(target_file) + os.rename(tmp_file, target_file) + return True + +def make_c_source(ffi, module_name, preamble, target_c_file, verbose=False): + assert preamble is not None + return _make_c_or_py_source(ffi, module_name, preamble, target_c_file, + verbose) + +def make_py_source(ffi, module_name, target_py_file, verbose=False): + return _make_c_or_py_source(ffi, module_name, None, target_py_file, + verbose) + +def _modname_to_file(outputdir, modname, extension): + parts = modname.split('.') + try: + os.makedirs(os.path.join(outputdir, *parts[:-1])) + except OSError: + pass + parts[-1] += extension + return os.path.join(outputdir, *parts), parts + + +# Aaargh. Distutils is not tested at all for the purpose of compiling +# DLLs that are not extension modules. Here are some hacks to work +# around that, in the _patch_for_*() functions... + +def _patch_meth(patchlist, cls, name, new_meth): + old = getattr(cls, name) + patchlist.append((cls, name, old)) + setattr(cls, name, new_meth) + return old + +def _unpatch_meths(patchlist): + for cls, name, old_meth in reversed(patchlist): + setattr(cls, name, old_meth) + +def _patch_for_embedding(patchlist): + if sys.platform == 'win32': + # we must not remove the manifest when building for embedding! + # FUTURE: this module was removed in setuptools 74; this is likely dead code and should be removed, + # since the toolchain it supports (VS2005-2008) is also long dead. + from cffi._shimmed_dist_utils import MSVCCompiler + if MSVCCompiler is not None: + _patch_meth(patchlist, MSVCCompiler, '_remove_visual_c_ref', + lambda self, manifest_file: manifest_file) + + if sys.platform == 'darwin': + # we must not make a '-bundle', but a '-dynamiclib' instead + from cffi._shimmed_dist_utils import CCompiler + def my_link_shared_object(self, *args, **kwds): + if '-bundle' in self.linker_so: + self.linker_so = list(self.linker_so) + i = self.linker_so.index('-bundle') + self.linker_so[i] = '-dynamiclib' + return old_link_shared_object(self, *args, **kwds) + old_link_shared_object = _patch_meth(patchlist, CCompiler, + 'link_shared_object', + my_link_shared_object) + +def _patch_for_target(patchlist, target): + from cffi._shimmed_dist_utils import build_ext + # if 'target' is different from '*', we need to patch some internal + # method to just return this 'target' value, instead of having it + # built from module_name + if target.endswith('.*'): + target = target[:-2] + if sys.platform == 'win32': + target += '.dll' + elif sys.platform == 'darwin': + target += '.dylib' + else: + target += '.so' + _patch_meth(patchlist, build_ext, 'get_ext_filename', + lambda self, ext_name: target) + + +def recompile(ffi, module_name, preamble, tmpdir='.', call_c_compiler=True, + c_file=None, source_extension='.c', extradir=None, + compiler_verbose=1, target=None, debug=None, + uses_ffiplatform=True, **kwds): + if not isinstance(module_name, str): + module_name = module_name.encode('ascii') + if ffi._windows_unicode: + ffi._apply_windows_unicode(kwds) + if preamble is not None: + if call_c_compiler and _is_file_like(c_file): + raise TypeError("Writing to file-like objects is not supported " + "with call_c_compiler=True") + embedding = (ffi._embedding is not None) + if embedding: + ffi._apply_embedding_fix(kwds) + if c_file is None: + c_file, parts = _modname_to_file(tmpdir, module_name, + source_extension) + if extradir: + parts = [extradir] + parts + ext_c_file = os.path.join(*parts) + else: + ext_c_file = c_file + # + if target is None: + if embedding: + target = '%s.*' % module_name + else: + target = '*' + # + if uses_ffiplatform: + ext = ffiplatform.get_extension(ext_c_file, module_name, **kwds) + else: + ext = None + updated = make_c_source(ffi, module_name, preamble, c_file, + verbose=compiler_verbose) + if call_c_compiler: + patchlist = [] + cwd = os.getcwd() + try: + if embedding: + _patch_for_embedding(patchlist) + if target != '*': + _patch_for_target(patchlist, target) + if compiler_verbose: + if tmpdir == '.': + msg = 'the current directory is' + else: + msg = 'setting the current directory to' + print('%s %r' % (msg, os.path.abspath(tmpdir))) + os.chdir(tmpdir) + outputfilename = ffiplatform.compile('.', ext, + compiler_verbose, debug) + finally: + os.chdir(cwd) + _unpatch_meths(patchlist) + return outputfilename + else: + return ext, updated + else: + if c_file is None: + c_file, _ = _modname_to_file(tmpdir, module_name, '.py') + updated = make_py_source(ffi, module_name, c_file, + verbose=compiler_verbose) + if call_c_compiler: + return c_file + else: + return None, updated + diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/setuptools_ext.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/setuptools_ext.py new file mode 100644 index 0000000000000000000000000000000000000000..5cdd246fb4dfb808dc8b09df5724a68386fa4bc3 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/setuptools_ext.py @@ -0,0 +1,229 @@ +import os +import sys +import sysconfig + +try: + basestring +except NameError: + # Python 3.x + basestring = str + +def error(msg): + from cffi._shimmed_dist_utils import DistutilsSetupError + raise DistutilsSetupError(msg) + + +def execfile(filename, glob): + # We use execfile() (here rewritten for Python 3) instead of + # __import__() to load the build script. The problem with + # a normal import is that in some packages, the intermediate + # __init__.py files may already try to import the file that + # we are generating. + with open(filename) as f: + src = f.read() + src += '\n' # Python 2.6 compatibility + code = compile(src, filename, 'exec') + exec(code, glob, glob) + + +def add_cffi_module(dist, mod_spec): + from cffi.api import FFI + + if not isinstance(mod_spec, basestring): + error("argument to 'cffi_modules=...' must be a str or a list of str," + " not %r" % (type(mod_spec).__name__,)) + mod_spec = str(mod_spec) + try: + build_file_name, ffi_var_name = mod_spec.split(':') + except ValueError: + error("%r must be of the form 'path/build.py:ffi_variable'" % + (mod_spec,)) + if not os.path.exists(build_file_name): + ext = '' + rewritten = build_file_name.replace('.', '/') + '.py' + if os.path.exists(rewritten): + ext = ' (rewrite cffi_modules to [%r])' % ( + rewritten + ':' + ffi_var_name,) + error("%r does not name an existing file%s" % (build_file_name, ext)) + + mod_vars = {'__name__': '__cffi__', '__file__': build_file_name} + execfile(build_file_name, mod_vars) + + try: + ffi = mod_vars[ffi_var_name] + except KeyError: + error("%r: object %r not found in module" % (mod_spec, + ffi_var_name)) + if not isinstance(ffi, FFI): + ffi = ffi() # maybe it's a function instead of directly an ffi + if not isinstance(ffi, FFI): + error("%r is not an FFI instance (got %r)" % (mod_spec, + type(ffi).__name__)) + if not hasattr(ffi, '_assigned_source'): + error("%r: the set_source() method was not called" % (mod_spec,)) + module_name, source, source_extension, kwds = ffi._assigned_source + if ffi._windows_unicode: + kwds = kwds.copy() + ffi._apply_windows_unicode(kwds) + + if source is None: + _add_py_module(dist, ffi, module_name) + else: + _add_c_module(dist, ffi, module_name, source, source_extension, kwds) + +def _set_py_limited_api(Extension, kwds): + """ + Add py_limited_api to kwds if setuptools >= 26 is in use. + Do not alter the setting if it already exists. + Setuptools takes care of ignoring the flag on Python 2 and PyPy. + + CPython itself should ignore the flag in a debugging version + (by not listing .abi3.so in the extensions it supports), but + it doesn't so far, creating troubles. That's why we check + for "not hasattr(sys, 'gettotalrefcount')" (the 2.7 compatible equivalent + of 'd' not in sys.abiflags). (http://bugs.python.org/issue28401) + + On Windows, with CPython <= 3.4, it's better not to use py_limited_api + because virtualenv *still* doesn't copy PYTHON3.DLL on these versions. + Recently (2020) we started shipping only >= 3.5 wheels, though. So + we'll give it another try and set py_limited_api on Windows >= 3.5. + """ + from cffi._shimmed_dist_utils import log + from cffi import recompiler + + if ('py_limited_api' not in kwds and not hasattr(sys, 'gettotalrefcount') + and recompiler.USE_LIMITED_API): + import setuptools + try: + setuptools_major_version = int(setuptools.__version__.partition('.')[0]) + if setuptools_major_version >= 26: + kwds['py_limited_api'] = True + except ValueError: # certain development versions of setuptools + # If we don't know the version number of setuptools, we + # try to set 'py_limited_api' anyway. At worst, we get a + # warning. + kwds['py_limited_api'] = True + + if sysconfig.get_config_var("Py_GIL_DISABLED"): + if kwds.get('py_limited_api'): + log.info("Ignoring py_limited_api=True for free-threaded build.") + + kwds['py_limited_api'] = False + + if kwds.get('py_limited_api') is False: + # avoid setting Py_LIMITED_API if py_limited_api=False + # which _cffi_include.h does unless _CFFI_NO_LIMITED_API is defined + kwds.setdefault("define_macros", []).append(("_CFFI_NO_LIMITED_API", None)) + return kwds + +def _add_c_module(dist, ffi, module_name, source, source_extension, kwds): + # We are a setuptools extension. Need this build_ext for py_limited_api. + from setuptools.command.build_ext import build_ext + from cffi._shimmed_dist_utils import Extension, log, mkpath + from cffi import recompiler + + allsources = ['$PLACEHOLDER'] + allsources.extend(kwds.pop('sources', [])) + kwds = _set_py_limited_api(Extension, kwds) + ext = Extension(name=module_name, sources=allsources, **kwds) + + def make_mod(tmpdir, pre_run=None): + c_file = os.path.join(tmpdir, module_name + source_extension) + log.info("generating cffi module %r" % c_file) + mkpath(tmpdir) + # a setuptools-only, API-only hook: called with the "ext" and "ffi" + # arguments just before we turn the ffi into C code. To use it, + # subclass the 'distutils.command.build_ext.build_ext' class and + # add a method 'def pre_run(self, ext, ffi)'. + if pre_run is not None: + pre_run(ext, ffi) + updated = recompiler.make_c_source(ffi, module_name, source, c_file) + if not updated: + log.info("already up-to-date") + return c_file + + if dist.ext_modules is None: + dist.ext_modules = [] + dist.ext_modules.append(ext) + + base_class = dist.cmdclass.get('build_ext', build_ext) + class build_ext_make_mod(base_class): + def run(self): + if ext.sources[0] == '$PLACEHOLDER': + pre_run = getattr(self, 'pre_run', None) + ext.sources[0] = make_mod(self.build_temp, pre_run) + base_class.run(self) + dist.cmdclass['build_ext'] = build_ext_make_mod + # NB. multiple runs here will create multiple 'build_ext_make_mod' + # classes. Even in this case the 'build_ext' command should be + # run once; but just in case, the logic above does nothing if + # called again. + + +def _add_py_module(dist, ffi, module_name): + from setuptools.command.build_py import build_py + from setuptools.command.build_ext import build_ext + from cffi._shimmed_dist_utils import log, mkpath + from cffi import recompiler + + def generate_mod(py_file): + log.info("generating cffi module %r" % py_file) + mkpath(os.path.dirname(py_file)) + updated = recompiler.make_py_source(ffi, module_name, py_file) + if not updated: + log.info("already up-to-date") + + base_class = dist.cmdclass.get('build_py', build_py) + class build_py_make_mod(base_class): + def run(self): + base_class.run(self) + module_path = module_name.split('.') + module_path[-1] += '.py' + generate_mod(os.path.join(self.build_lib, *module_path)) + def get_source_files(self): + # This is called from 'setup.py sdist' only. Exclude + # the generate .py module in this case. + saved_py_modules = self.py_modules + try: + if saved_py_modules: + self.py_modules = [m for m in saved_py_modules + if m != module_name] + return base_class.get_source_files(self) + finally: + self.py_modules = saved_py_modules + dist.cmdclass['build_py'] = build_py_make_mod + + # distutils and setuptools have no notion I could find of a + # generated python module. If we don't add module_name to + # dist.py_modules, then things mostly work but there are some + # combination of options (--root and --record) that will miss + # the module. So we add it here, which gives a few apparently + # harmless warnings about not finding the file outside the + # build directory. + # Then we need to hack more in get_source_files(); see above. + if dist.py_modules is None: + dist.py_modules = [] + dist.py_modules.append(module_name) + + # the following is only for "build_ext -i" + base_class_2 = dist.cmdclass.get('build_ext', build_ext) + class build_ext_make_mod(base_class_2): + def run(self): + base_class_2.run(self) + if self.inplace: + # from get_ext_fullpath() in distutils/command/build_ext.py + module_path = module_name.split('.') + package = '.'.join(module_path[:-1]) + build_py = self.get_finalized_command('build_py') + package_dir = build_py.get_package_dir(package) + file_name = module_path[-1] + '.py' + generate_mod(os.path.join(package_dir, file_name)) + dist.cmdclass['build_ext'] = build_ext_make_mod + +def cffi_modules(dist, attr, value): + assert attr == 'cffi_modules' + if isinstance(value, basestring): + value = [value] + + for cffi_module in value: + add_cffi_module(dist, cffi_module) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/vengine_cpy.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/vengine_cpy.py new file mode 100644 index 0000000000000000000000000000000000000000..02e6a471d04e4cbf45eb7698aecd3355ecd32546 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/vengine_cpy.py @@ -0,0 +1,1087 @@ +# +# DEPRECATED: implementation for ffi.verify() +# +import sys +from . import model +from .error import VerificationError +from . import _imp_emulation as imp + + +class VCPythonEngine(object): + _class_key = 'x' + _gen_python_module = True + + def __init__(self, verifier): + self.verifier = verifier + self.ffi = verifier.ffi + self._struct_pending_verification = {} + self._types_of_builtin_functions = {} + + def patch_extension_kwds(self, kwds): + pass + + def find_module(self, module_name, path, so_suffixes): + try: + f, filename, descr = imp.find_module(module_name, path) + except ImportError: + return None + if f is not None: + f.close() + # Note that after a setuptools installation, there are both .py + # and .so files with the same basename. The code here relies on + # imp.find_module() locating the .so in priority. + if descr[0] not in so_suffixes: + return None + return filename + + def collect_types(self): + self._typesdict = {} + self._generate("collecttype") + + def _prnt(self, what=''): + self._f.write(what + '\n') + + def _gettypenum(self, type): + # a KeyError here is a bug. please report it! :-) + return self._typesdict[type] + + def _do_collect_type(self, tp): + if ((not isinstance(tp, model.PrimitiveType) + or tp.name == 'long double') + and tp not in self._typesdict): + num = len(self._typesdict) + self._typesdict[tp] = num + + def write_source_to_f(self): + self.collect_types() + # + # The new module will have a _cffi_setup() function that receives + # objects from the ffi world, and that calls some setup code in + # the module. This setup code is split in several independent + # functions, e.g. one per constant. The functions are "chained" + # by ending in a tail call to each other. + # + # This is further split in two chained lists, depending on if we + # can do it at import-time or if we must wait for _cffi_setup() to + # provide us with the objects. This is needed because we + # need the values of the enum constants in order to build the + # that we may have to pass to _cffi_setup(). + # + # The following two 'chained_list_constants' items contains + # the head of these two chained lists, as a string that gives the + # call to do, if any. + self._chained_list_constants = ['((void)lib,0)', '((void)lib,0)'] + # + prnt = self._prnt + # first paste some standard set of lines that are mostly '#define' + prnt(cffimod_header) + prnt() + # then paste the C source given by the user, verbatim. + prnt(self.verifier.preamble) + prnt() + # + # call generate_cpy_xxx_decl(), for every xxx found from + # ffi._parser._declarations. This generates all the functions. + self._generate("decl") + # + # implement the function _cffi_setup_custom() as calling the + # head of the chained list. + self._generate_setup_custom() + prnt() + # + # produce the method table, including the entries for the + # generated Python->C function wrappers, which are done + # by generate_cpy_function_method(). + prnt('static PyMethodDef _cffi_methods[] = {') + self._generate("method") + prnt(' {"_cffi_setup", _cffi_setup, METH_VARARGS, NULL},') + prnt(' {NULL, NULL, 0, NULL} /* Sentinel */') + prnt('};') + prnt() + # + # standard init. + modname = self.verifier.get_module_name() + constants = self._chained_list_constants[False] + prnt('#if PY_MAJOR_VERSION >= 3') + prnt() + prnt('static struct PyModuleDef _cffi_module_def = {') + prnt(' PyModuleDef_HEAD_INIT,') + prnt(' "%s",' % modname) + prnt(' NULL,') + prnt(' -1,') + prnt(' _cffi_methods,') + prnt(' NULL, NULL, NULL, NULL') + prnt('};') + prnt() + prnt('PyMODINIT_FUNC') + prnt('PyInit_%s(void)' % modname) + prnt('{') + prnt(' PyObject *lib;') + prnt(' lib = PyModule_Create(&_cffi_module_def);') + prnt(' if (lib == NULL)') + prnt(' return NULL;') + prnt(' if (%s < 0 || _cffi_init() < 0) {' % (constants,)) + prnt(' Py_DECREF(lib);') + prnt(' return NULL;') + prnt(' }') + prnt('#if Py_GIL_DISABLED') + prnt(' PyUnstable_Module_SetGIL(lib, Py_MOD_GIL_NOT_USED);') + prnt('#endif') + prnt(' return lib;') + prnt('}') + prnt() + prnt('#else') + prnt() + prnt('PyMODINIT_FUNC') + prnt('init%s(void)' % modname) + prnt('{') + prnt(' PyObject *lib;') + prnt(' lib = Py_InitModule("%s", _cffi_methods);' % modname) + prnt(' if (lib == NULL)') + prnt(' return;') + prnt(' if (%s < 0 || _cffi_init() < 0)' % (constants,)) + prnt(' return;') + prnt(' return;') + prnt('}') + prnt() + prnt('#endif') + + def load_library(self, flags=None): + # XXX review all usages of 'self' here! + # import it as a new extension module + imp.acquire_lock() + try: + if hasattr(sys, "getdlopenflags"): + previous_flags = sys.getdlopenflags() + try: + if hasattr(sys, "setdlopenflags") and flags is not None: + sys.setdlopenflags(flags) + module = imp.load_dynamic(self.verifier.get_module_name(), + self.verifier.modulefilename) + except ImportError as e: + error = "importing %r: %s" % (self.verifier.modulefilename, e) + raise VerificationError(error) + finally: + if hasattr(sys, "setdlopenflags"): + sys.setdlopenflags(previous_flags) + finally: + imp.release_lock() + # + # call loading_cpy_struct() to get the struct layout inferred by + # the C compiler + self._load(module, 'loading') + # + # the C code will need the objects. Collect them in + # order in a list. + revmapping = dict([(value, key) + for (key, value) in self._typesdict.items()]) + lst = [revmapping[i] for i in range(len(revmapping))] + lst = list(map(self.ffi._get_cached_btype, lst)) + # + # build the FFILibrary class and instance and call _cffi_setup(). + # this will set up some fields like '_cffi_types', and only then + # it will invoke the chained list of functions that will really + # build (notably) the constant objects, as if they are + # pointers, and store them as attributes on the 'library' object. + class FFILibrary(object): + _cffi_python_module = module + _cffi_ffi = self.ffi + _cffi_dir = [] + def __dir__(self): + return FFILibrary._cffi_dir + list(self.__dict__) + library = FFILibrary() + if module._cffi_setup(lst, VerificationError, library): + import warnings + warnings.warn("reimporting %r might overwrite older definitions" + % (self.verifier.get_module_name())) + # + # finally, call the loaded_cpy_xxx() functions. This will perform + # the final adjustments, like copying the Python->C wrapper + # functions from the module to the 'library' object, and setting + # up the FFILibrary class with properties for the global C variables. + self._load(module, 'loaded', library=library) + module._cffi_original_ffi = self.ffi + module._cffi_types_of_builtin_funcs = self._types_of_builtin_functions + return library + + def _get_declarations(self): + lst = [(key, tp) for (key, (tp, qual)) in + self.ffi._parser._declarations.items()] + lst.sort() + return lst + + def _generate(self, step_name): + for name, tp in self._get_declarations(): + kind, realname = name.split(' ', 1) + try: + method = getattr(self, '_generate_cpy_%s_%s' % (kind, + step_name)) + except AttributeError: + raise VerificationError( + "not implemented in verify(): %r" % name) + try: + method(tp, realname) + except Exception as e: + model.attach_exception_info(e, name) + raise + + def _load(self, module, step_name, **kwds): + for name, tp in self._get_declarations(): + kind, realname = name.split(' ', 1) + method = getattr(self, '_%s_cpy_%s' % (step_name, kind)) + try: + method(tp, realname, module, **kwds) + except Exception as e: + model.attach_exception_info(e, name) + raise + + def _generate_nothing(self, tp, name): + pass + + def _loaded_noop(self, tp, name, module, **kwds): + pass + + # ---------- + + def _convert_funcarg_to_c(self, tp, fromvar, tovar, errcode): + extraarg = '' + if isinstance(tp, model.PrimitiveType): + if tp.is_integer_type() and tp.name != '_Bool': + converter = '_cffi_to_c_int' + extraarg = ', %s' % tp.name + elif tp.is_complex_type(): + raise VerificationError( + "not implemented in verify(): complex types") + else: + converter = '(%s)_cffi_to_c_%s' % (tp.get_c_name(''), + tp.name.replace(' ', '_')) + errvalue = '-1' + # + elif isinstance(tp, model.PointerType): + self._convert_funcarg_to_c_ptr_or_array(tp, fromvar, + tovar, errcode) + return + # + elif isinstance(tp, (model.StructOrUnion, model.EnumType)): + # a struct (not a struct pointer) as a function argument + self._prnt(' if (_cffi_to_c((char *)&%s, _cffi_type(%d), %s) < 0)' + % (tovar, self._gettypenum(tp), fromvar)) + self._prnt(' %s;' % errcode) + return + # + elif isinstance(tp, model.FunctionPtrType): + converter = '(%s)_cffi_to_c_pointer' % tp.get_c_name('') + extraarg = ', _cffi_type(%d)' % self._gettypenum(tp) + errvalue = 'NULL' + # + else: + raise NotImplementedError(tp) + # + self._prnt(' %s = %s(%s%s);' % (tovar, converter, fromvar, extraarg)) + self._prnt(' if (%s == (%s)%s && PyErr_Occurred())' % ( + tovar, tp.get_c_name(''), errvalue)) + self._prnt(' %s;' % errcode) + + def _extra_local_variables(self, tp, localvars, freelines): + if isinstance(tp, model.PointerType): + localvars.add('Py_ssize_t datasize') + localvars.add('struct _cffi_freeme_s *large_args_free = NULL') + freelines.add('if (large_args_free != NULL)' + ' _cffi_free_array_arguments(large_args_free);') + + def _convert_funcarg_to_c_ptr_or_array(self, tp, fromvar, tovar, errcode): + self._prnt(' datasize = _cffi_prepare_pointer_call_argument(') + self._prnt(' _cffi_type(%d), %s, (char **)&%s);' % ( + self._gettypenum(tp), fromvar, tovar)) + self._prnt(' if (datasize != 0) {') + self._prnt(' %s = ((size_t)datasize) <= 640 ? ' + 'alloca((size_t)datasize) : NULL;' % (tovar,)) + self._prnt(' if (_cffi_convert_array_argument(_cffi_type(%d), %s, ' + '(char **)&%s,' % (self._gettypenum(tp), fromvar, tovar)) + self._prnt(' datasize, &large_args_free) < 0)') + self._prnt(' %s;' % errcode) + self._prnt(' }') + + def _convert_expr_from_c(self, tp, var, context): + if isinstance(tp, model.PrimitiveType): + if tp.is_integer_type() and tp.name != '_Bool': + return '_cffi_from_c_int(%s, %s)' % (var, tp.name) + elif tp.name != 'long double': + return '_cffi_from_c_%s(%s)' % (tp.name.replace(' ', '_'), var) + else: + return '_cffi_from_c_deref((char *)&%s, _cffi_type(%d))' % ( + var, self._gettypenum(tp)) + elif isinstance(tp, (model.PointerType, model.FunctionPtrType)): + return '_cffi_from_c_pointer((char *)%s, _cffi_type(%d))' % ( + var, self._gettypenum(tp)) + elif isinstance(tp, model.ArrayType): + return '_cffi_from_c_pointer((char *)%s, _cffi_type(%d))' % ( + var, self._gettypenum(model.PointerType(tp.item))) + elif isinstance(tp, model.StructOrUnion): + if tp.fldnames is None: + raise TypeError("'%s' is used as %s, but is opaque" % ( + tp._get_c_name(), context)) + return '_cffi_from_c_struct((char *)&%s, _cffi_type(%d))' % ( + var, self._gettypenum(tp)) + elif isinstance(tp, model.EnumType): + return '_cffi_from_c_deref((char *)&%s, _cffi_type(%d))' % ( + var, self._gettypenum(tp)) + else: + raise NotImplementedError(tp) + + # ---------- + # typedefs: generates no code so far + + _generate_cpy_typedef_collecttype = _generate_nothing + _generate_cpy_typedef_decl = _generate_nothing + _generate_cpy_typedef_method = _generate_nothing + _loading_cpy_typedef = _loaded_noop + _loaded_cpy_typedef = _loaded_noop + + # ---------- + # function declarations + + def _generate_cpy_function_collecttype(self, tp, name): + assert isinstance(tp, model.FunctionPtrType) + if tp.ellipsis: + self._do_collect_type(tp) + else: + # don't call _do_collect_type(tp) in this common case, + # otherwise test_autofilled_struct_as_argument fails + for type in tp.args: + self._do_collect_type(type) + self._do_collect_type(tp.result) + + def _generate_cpy_function_decl(self, tp, name): + assert isinstance(tp, model.FunctionPtrType) + if tp.ellipsis: + # cannot support vararg functions better than this: check for its + # exact type (including the fixed arguments), and build it as a + # constant function pointer (no CPython wrapper) + self._generate_cpy_const(False, name, tp) + return + prnt = self._prnt + numargs = len(tp.args) + if numargs == 0: + argname = 'noarg' + elif numargs == 1: + argname = 'arg0' + else: + argname = 'args' + prnt('static PyObject *') + prnt('_cffi_f_%s(PyObject *self, PyObject *%s)' % (name, argname)) + prnt('{') + # + context = 'argument of %s' % name + for i, type in enumerate(tp.args): + prnt(' %s;' % type.get_c_name(' x%d' % i, context)) + # + localvars = set() + freelines = set() + for type in tp.args: + self._extra_local_variables(type, localvars, freelines) + for decl in sorted(localvars): + prnt(' %s;' % (decl,)) + # + if not isinstance(tp.result, model.VoidType): + result_code = 'result = ' + context = 'result of %s' % name + prnt(' %s;' % tp.result.get_c_name(' result', context)) + prnt(' PyObject *pyresult;') + else: + result_code = '' + # + if len(tp.args) > 1: + rng = range(len(tp.args)) + for i in rng: + prnt(' PyObject *arg%d;' % i) + prnt() + prnt(' if (!PyArg_ParseTuple(args, "%s:%s", %s))' % ( + 'O' * numargs, name, ', '.join(['&arg%d' % i for i in rng]))) + prnt(' return NULL;') + prnt() + # + for i, type in enumerate(tp.args): + self._convert_funcarg_to_c(type, 'arg%d' % i, 'x%d' % i, + 'return NULL') + prnt() + # + prnt(' Py_BEGIN_ALLOW_THREADS') + prnt(' _cffi_restore_errno();') + prnt(' { %s%s(%s); }' % ( + result_code, name, + ', '.join(['x%d' % i for i in range(len(tp.args))]))) + prnt(' _cffi_save_errno();') + prnt(' Py_END_ALLOW_THREADS') + prnt() + # + prnt(' (void)self; /* unused */') + if numargs == 0: + prnt(' (void)noarg; /* unused */') + if result_code: + prnt(' pyresult = %s;' % + self._convert_expr_from_c(tp.result, 'result', 'result type')) + for freeline in freelines: + prnt(' ' + freeline) + prnt(' return pyresult;') + else: + for freeline in freelines: + prnt(' ' + freeline) + prnt(' Py_INCREF(Py_None);') + prnt(' return Py_None;') + prnt('}') + prnt() + + def _generate_cpy_function_method(self, tp, name): + if tp.ellipsis: + return + numargs = len(tp.args) + if numargs == 0: + meth = 'METH_NOARGS' + elif numargs == 1: + meth = 'METH_O' + else: + meth = 'METH_VARARGS' + self._prnt(' {"%s", _cffi_f_%s, %s, NULL},' % (name, name, meth)) + + _loading_cpy_function = _loaded_noop + + def _loaded_cpy_function(self, tp, name, module, library): + if tp.ellipsis: + return + func = getattr(module, name) + setattr(library, name, func) + self._types_of_builtin_functions[func] = tp + + # ---------- + # named structs + + _generate_cpy_struct_collecttype = _generate_nothing + def _generate_cpy_struct_decl(self, tp, name): + assert name == tp.name + self._generate_struct_or_union_decl(tp, 'struct', name) + def _generate_cpy_struct_method(self, tp, name): + self._generate_struct_or_union_method(tp, 'struct', name) + def _loading_cpy_struct(self, tp, name, module): + self._loading_struct_or_union(tp, 'struct', name, module) + def _loaded_cpy_struct(self, tp, name, module, **kwds): + self._loaded_struct_or_union(tp) + + _generate_cpy_union_collecttype = _generate_nothing + def _generate_cpy_union_decl(self, tp, name): + assert name == tp.name + self._generate_struct_or_union_decl(tp, 'union', name) + def _generate_cpy_union_method(self, tp, name): + self._generate_struct_or_union_method(tp, 'union', name) + def _loading_cpy_union(self, tp, name, module): + self._loading_struct_or_union(tp, 'union', name, module) + def _loaded_cpy_union(self, tp, name, module, **kwds): + self._loaded_struct_or_union(tp) + + def _generate_struct_or_union_decl(self, tp, prefix, name): + if tp.fldnames is None: + return # nothing to do with opaque structs + checkfuncname = '_cffi_check_%s_%s' % (prefix, name) + layoutfuncname = '_cffi_layout_%s_%s' % (prefix, name) + cname = ('%s %s' % (prefix, name)).strip() + # + prnt = self._prnt + prnt('static void %s(%s *p)' % (checkfuncname, cname)) + prnt('{') + prnt(' /* only to generate compile-time warnings or errors */') + prnt(' (void)p;') + for fname, ftype, fbitsize, fqual in tp.enumfields(): + if (isinstance(ftype, model.PrimitiveType) + and ftype.is_integer_type()) or fbitsize >= 0: + # accept all integers, but complain on float or double + prnt(' (void)((p->%s) << 1);' % fname) + else: + # only accept exactly the type declared. + try: + prnt(' { %s = &p->%s; (void)tmp; }' % ( + ftype.get_c_name('*tmp', 'field %r'%fname, quals=fqual), + fname)) + except VerificationError as e: + prnt(' /* %s */' % str(e)) # cannot verify it, ignore + prnt('}') + prnt('static PyObject *') + prnt('%s(PyObject *self, PyObject *noarg)' % (layoutfuncname,)) + prnt('{') + prnt(' struct _cffi_aligncheck { char x; %s y; };' % cname) + prnt(' static Py_ssize_t nums[] = {') + prnt(' sizeof(%s),' % cname) + prnt(' offsetof(struct _cffi_aligncheck, y),') + for fname, ftype, fbitsize, fqual in tp.enumfields(): + if fbitsize >= 0: + continue # xxx ignore fbitsize for now + prnt(' offsetof(%s, %s),' % (cname, fname)) + if isinstance(ftype, model.ArrayType) and ftype.length is None: + prnt(' 0, /* %s */' % ftype._get_c_name()) + else: + prnt(' sizeof(((%s *)0)->%s),' % (cname, fname)) + prnt(' -1') + prnt(' };') + prnt(' (void)self; /* unused */') + prnt(' (void)noarg; /* unused */') + prnt(' return _cffi_get_struct_layout(nums);') + prnt(' /* the next line is not executed, but compiled */') + prnt(' %s(0);' % (checkfuncname,)) + prnt('}') + prnt() + + def _generate_struct_or_union_method(self, tp, prefix, name): + if tp.fldnames is None: + return # nothing to do with opaque structs + layoutfuncname = '_cffi_layout_%s_%s' % (prefix, name) + self._prnt(' {"%s", %s, METH_NOARGS, NULL},' % (layoutfuncname, + layoutfuncname)) + + def _loading_struct_or_union(self, tp, prefix, name, module): + if tp.fldnames is None: + return # nothing to do with opaque structs + layoutfuncname = '_cffi_layout_%s_%s' % (prefix, name) + # + function = getattr(module, layoutfuncname) + layout = function() + if isinstance(tp, model.StructOrUnion) and tp.partial: + # use the function()'s sizes and offsets to guide the + # layout of the struct + totalsize = layout[0] + totalalignment = layout[1] + fieldofs = layout[2::2] + fieldsize = layout[3::2] + tp.force_flatten() + assert len(fieldofs) == len(fieldsize) == len(tp.fldnames) + tp.fixedlayout = fieldofs, fieldsize, totalsize, totalalignment + else: + cname = ('%s %s' % (prefix, name)).strip() + self._struct_pending_verification[tp] = layout, cname + + def _loaded_struct_or_union(self, tp): + if tp.fldnames is None: + return # nothing to do with opaque structs + self.ffi._get_cached_btype(tp) # force 'fixedlayout' to be considered + + if tp in self._struct_pending_verification: + # check that the layout sizes and offsets match the real ones + def check(realvalue, expectedvalue, msg): + if realvalue != expectedvalue: + raise VerificationError( + "%s (we have %d, but C compiler says %d)" + % (msg, expectedvalue, realvalue)) + ffi = self.ffi + BStruct = ffi._get_cached_btype(tp) + layout, cname = self._struct_pending_verification.pop(tp) + check(layout[0], ffi.sizeof(BStruct), "wrong total size") + check(layout[1], ffi.alignof(BStruct), "wrong total alignment") + i = 2 + for fname, ftype, fbitsize, fqual in tp.enumfields(): + if fbitsize >= 0: + continue # xxx ignore fbitsize for now + check(layout[i], ffi.offsetof(BStruct, fname), + "wrong offset for field %r" % (fname,)) + if layout[i+1] != 0: + BField = ffi._get_cached_btype(ftype) + check(layout[i+1], ffi.sizeof(BField), + "wrong size for field %r" % (fname,)) + i += 2 + assert i == len(layout) + + # ---------- + # 'anonymous' declarations. These are produced for anonymous structs + # or unions; the 'name' is obtained by a typedef. + + _generate_cpy_anonymous_collecttype = _generate_nothing + + def _generate_cpy_anonymous_decl(self, tp, name): + if isinstance(tp, model.EnumType): + self._generate_cpy_enum_decl(tp, name, '') + else: + self._generate_struct_or_union_decl(tp, '', name) + + def _generate_cpy_anonymous_method(self, tp, name): + if not isinstance(tp, model.EnumType): + self._generate_struct_or_union_method(tp, '', name) + + def _loading_cpy_anonymous(self, tp, name, module): + if isinstance(tp, model.EnumType): + self._loading_cpy_enum(tp, name, module) + else: + self._loading_struct_or_union(tp, '', name, module) + + def _loaded_cpy_anonymous(self, tp, name, module, **kwds): + if isinstance(tp, model.EnumType): + self._loaded_cpy_enum(tp, name, module, **kwds) + else: + self._loaded_struct_or_union(tp) + + # ---------- + # constants, likely declared with '#define' + + def _generate_cpy_const(self, is_int, name, tp=None, category='const', + vartp=None, delayed=True, size_too=False, + check_value=None): + prnt = self._prnt + funcname = '_cffi_%s_%s' % (category, name) + prnt('static int %s(PyObject *lib)' % funcname) + prnt('{') + prnt(' PyObject *o;') + prnt(' int res;') + if not is_int: + prnt(' %s;' % (vartp or tp).get_c_name(' i', name)) + else: + assert category == 'const' + # + if check_value is not None: + self._check_int_constant_value(name, check_value) + # + if not is_int: + if category == 'var': + realexpr = '&' + name + else: + realexpr = name + prnt(' i = (%s);' % (realexpr,)) + prnt(' o = %s;' % (self._convert_expr_from_c(tp, 'i', + 'variable type'),)) + assert delayed + else: + prnt(' o = _cffi_from_c_int_const(%s);' % name) + prnt(' if (o == NULL)') + prnt(' return -1;') + if size_too: + prnt(' {') + prnt(' PyObject *o1 = o;') + prnt(' o = Py_BuildValue("On", o1, (Py_ssize_t)sizeof(%s));' + % (name,)) + prnt(' Py_DECREF(o1);') + prnt(' if (o == NULL)') + prnt(' return -1;') + prnt(' }') + prnt(' res = PyObject_SetAttrString(lib, "%s", o);' % name) + prnt(' Py_DECREF(o);') + prnt(' if (res < 0)') + prnt(' return -1;') + prnt(' return %s;' % self._chained_list_constants[delayed]) + self._chained_list_constants[delayed] = funcname + '(lib)' + prnt('}') + prnt() + + def _generate_cpy_constant_collecttype(self, tp, name): + is_int = isinstance(tp, model.PrimitiveType) and tp.is_integer_type() + if not is_int: + self._do_collect_type(tp) + + def _generate_cpy_constant_decl(self, tp, name): + is_int = isinstance(tp, model.PrimitiveType) and tp.is_integer_type() + self._generate_cpy_const(is_int, name, tp) + + _generate_cpy_constant_method = _generate_nothing + _loading_cpy_constant = _loaded_noop + _loaded_cpy_constant = _loaded_noop + + # ---------- + # enums + + def _check_int_constant_value(self, name, value, err_prefix=''): + prnt = self._prnt + if value <= 0: + prnt(' if ((%s) > 0 || (long)(%s) != %dL) {' % ( + name, name, value)) + else: + prnt(' if ((%s) <= 0 || (unsigned long)(%s) != %dUL) {' % ( + name, name, value)) + prnt(' char buf[64];') + prnt(' if ((%s) <= 0)' % name) + prnt(' snprintf(buf, 63, "%%ld", (long)(%s));' % name) + prnt(' else') + prnt(' snprintf(buf, 63, "%%lu", (unsigned long)(%s));' % + name) + prnt(' PyErr_Format(_cffi_VerificationError,') + prnt(' "%s%s has the real value %s, not %s",') + prnt(' "%s", "%s", buf, "%d");' % ( + err_prefix, name, value)) + prnt(' return -1;') + prnt(' }') + + def _enum_funcname(self, prefix, name): + # "$enum_$1" => "___D_enum____D_1" + name = name.replace('$', '___D_') + return '_cffi_e_%s_%s' % (prefix, name) + + def _generate_cpy_enum_decl(self, tp, name, prefix='enum'): + if tp.partial: + for enumerator in tp.enumerators: + self._generate_cpy_const(True, enumerator, delayed=False) + return + # + funcname = self._enum_funcname(prefix, name) + prnt = self._prnt + prnt('static int %s(PyObject *lib)' % funcname) + prnt('{') + for enumerator, enumvalue in zip(tp.enumerators, tp.enumvalues): + self._check_int_constant_value(enumerator, enumvalue, + "enum %s: " % name) + prnt(' return %s;' % self._chained_list_constants[True]) + self._chained_list_constants[True] = funcname + '(lib)' + prnt('}') + prnt() + + _generate_cpy_enum_collecttype = _generate_nothing + _generate_cpy_enum_method = _generate_nothing + + def _loading_cpy_enum(self, tp, name, module): + if tp.partial: + enumvalues = [getattr(module, enumerator) + for enumerator in tp.enumerators] + tp.enumvalues = tuple(enumvalues) + tp.partial_resolved = True + + def _loaded_cpy_enum(self, tp, name, module, library): + for enumerator, enumvalue in zip(tp.enumerators, tp.enumvalues): + setattr(library, enumerator, enumvalue) + + # ---------- + # macros: for now only for integers + + def _generate_cpy_macro_decl(self, tp, name): + if tp == '...': + check_value = None + else: + check_value = tp # an integer + self._generate_cpy_const(True, name, check_value=check_value) + + _generate_cpy_macro_collecttype = _generate_nothing + _generate_cpy_macro_method = _generate_nothing + _loading_cpy_macro = _loaded_noop + _loaded_cpy_macro = _loaded_noop + + # ---------- + # global variables + + def _generate_cpy_variable_collecttype(self, tp, name): + if isinstance(tp, model.ArrayType): + tp_ptr = model.PointerType(tp.item) + else: + tp_ptr = model.PointerType(tp) + self._do_collect_type(tp_ptr) + + def _generate_cpy_variable_decl(self, tp, name): + if isinstance(tp, model.ArrayType): + tp_ptr = model.PointerType(tp.item) + self._generate_cpy_const(False, name, tp, vartp=tp_ptr, + size_too = tp.length_is_unknown()) + else: + tp_ptr = model.PointerType(tp) + self._generate_cpy_const(False, name, tp_ptr, category='var') + + _generate_cpy_variable_method = _generate_nothing + _loading_cpy_variable = _loaded_noop + + def _loaded_cpy_variable(self, tp, name, module, library): + value = getattr(library, name) + if isinstance(tp, model.ArrayType): # int a[5] is "constant" in the + # sense that "a=..." is forbidden + if tp.length_is_unknown(): + assert isinstance(value, tuple) + (value, size) = value + BItemType = self.ffi._get_cached_btype(tp.item) + length, rest = divmod(size, self.ffi.sizeof(BItemType)) + if rest != 0: + raise VerificationError( + "bad size: %r does not seem to be an array of %s" % + (name, tp.item)) + tp = tp.resolve_length(length) + # 'value' is a which we have to replace with + # a if the N is actually known + if tp.length is not None: + BArray = self.ffi._get_cached_btype(tp) + value = self.ffi.cast(BArray, value) + setattr(library, name, value) + return + # remove ptr= from the library instance, and replace + # it by a property on the class, which reads/writes into ptr[0]. + ptr = value + delattr(library, name) + def getter(library): + return ptr[0] + def setter(library, value): + ptr[0] = value + setattr(type(library), name, property(getter, setter)) + type(library)._cffi_dir.append(name) + + # ---------- + + def _generate_setup_custom(self): + prnt = self._prnt + prnt('static int _cffi_setup_custom(PyObject *lib)') + prnt('{') + prnt(' return %s;' % self._chained_list_constants[True]) + prnt('}') + +cffimod_header = r''' +#include +#include + +/* this block of #ifs should be kept exactly identical between + c/_cffi_backend.c, cffi/vengine_cpy.py, cffi/vengine_gen.py + and cffi/_cffi_include.h */ +#if defined(_MSC_VER) +# include /* for alloca() */ +# if _MSC_VER < 1600 /* MSVC < 2010 */ + typedef __int8 int8_t; + typedef __int16 int16_t; + typedef __int32 int32_t; + typedef __int64 int64_t; + typedef unsigned __int8 uint8_t; + typedef unsigned __int16 uint16_t; + typedef unsigned __int32 uint32_t; + typedef unsigned __int64 uint64_t; + typedef __int8 int_least8_t; + typedef __int16 int_least16_t; + typedef __int32 int_least32_t; + typedef __int64 int_least64_t; + typedef unsigned __int8 uint_least8_t; + typedef unsigned __int16 uint_least16_t; + typedef unsigned __int32 uint_least32_t; + typedef unsigned __int64 uint_least64_t; + typedef __int8 int_fast8_t; + typedef __int16 int_fast16_t; + typedef __int32 int_fast32_t; + typedef __int64 int_fast64_t; + typedef unsigned __int8 uint_fast8_t; + typedef unsigned __int16 uint_fast16_t; + typedef unsigned __int32 uint_fast32_t; + typedef unsigned __int64 uint_fast64_t; + typedef __int64 intmax_t; + typedef unsigned __int64 uintmax_t; +# else +# include +# endif +# if _MSC_VER < 1800 /* MSVC < 2013 */ +# ifndef __cplusplus + typedef unsigned char _Bool; +# endif +# endif +# define _cffi_float_complex_t _Fcomplex /* include for it */ +# define _cffi_double_complex_t _Dcomplex /* include for it */ +#else +# include +# if (defined (__SVR4) && defined (__sun)) || defined(_AIX) || defined(__hpux) +# include +# endif +# define _cffi_float_complex_t float _Complex +# define _cffi_double_complex_t double _Complex +#endif + +#if PY_MAJOR_VERSION < 3 +# undef PyCapsule_CheckExact +# undef PyCapsule_GetPointer +# define PyCapsule_CheckExact(capsule) (PyCObject_Check(capsule)) +# define PyCapsule_GetPointer(capsule, name) \ + (PyCObject_AsVoidPtr(capsule)) +#endif + +#if PY_MAJOR_VERSION >= 3 +# define PyInt_FromLong PyLong_FromLong +#endif + +#define _cffi_from_c_double PyFloat_FromDouble +#define _cffi_from_c_float PyFloat_FromDouble +#define _cffi_from_c_long PyInt_FromLong +#define _cffi_from_c_ulong PyLong_FromUnsignedLong +#define _cffi_from_c_longlong PyLong_FromLongLong +#define _cffi_from_c_ulonglong PyLong_FromUnsignedLongLong +#define _cffi_from_c__Bool PyBool_FromLong + +#define _cffi_to_c_double PyFloat_AsDouble +#define _cffi_to_c_float PyFloat_AsDouble + +#define _cffi_from_c_int_const(x) \ + (((x) > 0) ? \ + ((unsigned long long)(x) <= (unsigned long long)LONG_MAX) ? \ + PyInt_FromLong((long)(x)) : \ + PyLong_FromUnsignedLongLong((unsigned long long)(x)) : \ + ((long long)(x) >= (long long)LONG_MIN) ? \ + PyInt_FromLong((long)(x)) : \ + PyLong_FromLongLong((long long)(x))) + +#define _cffi_from_c_int(x, type) \ + (((type)-1) > 0 ? /* unsigned */ \ + (sizeof(type) < sizeof(long) ? \ + PyInt_FromLong((long)x) : \ + sizeof(type) == sizeof(long) ? \ + PyLong_FromUnsignedLong((unsigned long)x) : \ + PyLong_FromUnsignedLongLong((unsigned long long)x)) : \ + (sizeof(type) <= sizeof(long) ? \ + PyInt_FromLong((long)x) : \ + PyLong_FromLongLong((long long)x))) + +#define _cffi_to_c_int(o, type) \ + ((type)( \ + sizeof(type) == 1 ? (((type)-1) > 0 ? (type)_cffi_to_c_u8(o) \ + : (type)_cffi_to_c_i8(o)) : \ + sizeof(type) == 2 ? (((type)-1) > 0 ? (type)_cffi_to_c_u16(o) \ + : (type)_cffi_to_c_i16(o)) : \ + sizeof(type) == 4 ? (((type)-1) > 0 ? (type)_cffi_to_c_u32(o) \ + : (type)_cffi_to_c_i32(o)) : \ + sizeof(type) == 8 ? (((type)-1) > 0 ? (type)_cffi_to_c_u64(o) \ + : (type)_cffi_to_c_i64(o)) : \ + (Py_FatalError("unsupported size for type " #type), (type)0))) + +#define _cffi_to_c_i8 \ + ((int(*)(PyObject *))_cffi_exports[1]) +#define _cffi_to_c_u8 \ + ((int(*)(PyObject *))_cffi_exports[2]) +#define _cffi_to_c_i16 \ + ((int(*)(PyObject *))_cffi_exports[3]) +#define _cffi_to_c_u16 \ + ((int(*)(PyObject *))_cffi_exports[4]) +#define _cffi_to_c_i32 \ + ((int(*)(PyObject *))_cffi_exports[5]) +#define _cffi_to_c_u32 \ + ((unsigned int(*)(PyObject *))_cffi_exports[6]) +#define _cffi_to_c_i64 \ + ((long long(*)(PyObject *))_cffi_exports[7]) +#define _cffi_to_c_u64 \ + ((unsigned long long(*)(PyObject *))_cffi_exports[8]) +#define _cffi_to_c_char \ + ((int(*)(PyObject *))_cffi_exports[9]) +#define _cffi_from_c_pointer \ + ((PyObject *(*)(char *, CTypeDescrObject *))_cffi_exports[10]) +#define _cffi_to_c_pointer \ + ((char *(*)(PyObject *, CTypeDescrObject *))_cffi_exports[11]) +#define _cffi_get_struct_layout \ + ((PyObject *(*)(Py_ssize_t[]))_cffi_exports[12]) +#define _cffi_restore_errno \ + ((void(*)(void))_cffi_exports[13]) +#define _cffi_save_errno \ + ((void(*)(void))_cffi_exports[14]) +#define _cffi_from_c_char \ + ((PyObject *(*)(char))_cffi_exports[15]) +#define _cffi_from_c_deref \ + ((PyObject *(*)(char *, CTypeDescrObject *))_cffi_exports[16]) +#define _cffi_to_c \ + ((int(*)(char *, CTypeDescrObject *, PyObject *))_cffi_exports[17]) +#define _cffi_from_c_struct \ + ((PyObject *(*)(char *, CTypeDescrObject *))_cffi_exports[18]) +#define _cffi_to_c_wchar_t \ + ((wchar_t(*)(PyObject *))_cffi_exports[19]) +#define _cffi_from_c_wchar_t \ + ((PyObject *(*)(wchar_t))_cffi_exports[20]) +#define _cffi_to_c_long_double \ + ((long double(*)(PyObject *))_cffi_exports[21]) +#define _cffi_to_c__Bool \ + ((_Bool(*)(PyObject *))_cffi_exports[22]) +#define _cffi_prepare_pointer_call_argument \ + ((Py_ssize_t(*)(CTypeDescrObject *, PyObject *, char **))_cffi_exports[23]) +#define _cffi_convert_array_from_object \ + ((int(*)(char *, CTypeDescrObject *, PyObject *))_cffi_exports[24]) +#define _CFFI_NUM_EXPORTS 25 + +typedef struct _ctypedescr CTypeDescrObject; + +static void *_cffi_exports[_CFFI_NUM_EXPORTS]; +static PyObject *_cffi_types, *_cffi_VerificationError; + +static int _cffi_setup_custom(PyObject *lib); /* forward */ + +static PyObject *_cffi_setup(PyObject *self, PyObject *args) +{ + PyObject *library; + int was_alive = (_cffi_types != NULL); + (void)self; /* unused */ + if (!PyArg_ParseTuple(args, "OOO", &_cffi_types, &_cffi_VerificationError, + &library)) + return NULL; + Py_INCREF(_cffi_types); + Py_INCREF(_cffi_VerificationError); + if (_cffi_setup_custom(library) < 0) + return NULL; + return PyBool_FromLong(was_alive); +} + +union _cffi_union_alignment_u { + unsigned char m_char; + unsigned short m_short; + unsigned int m_int; + unsigned long m_long; + unsigned long long m_longlong; + float m_float; + double m_double; + long double m_longdouble; +}; + +struct _cffi_freeme_s { + struct _cffi_freeme_s *next; + union _cffi_union_alignment_u alignment; +}; + +#ifdef __GNUC__ + __attribute__((unused)) +#endif +static int _cffi_convert_array_argument(CTypeDescrObject *ctptr, PyObject *arg, + char **output_data, Py_ssize_t datasize, + struct _cffi_freeme_s **freeme) +{ + char *p; + if (datasize < 0) + return -1; + + p = *output_data; + if (p == NULL) { + struct _cffi_freeme_s *fp = (struct _cffi_freeme_s *)PyObject_Malloc( + offsetof(struct _cffi_freeme_s, alignment) + (size_t)datasize); + if (fp == NULL) + return -1; + fp->next = *freeme; + *freeme = fp; + p = *output_data = (char *)&fp->alignment; + } + memset((void *)p, 0, (size_t)datasize); + return _cffi_convert_array_from_object(p, ctptr, arg); +} + +#ifdef __GNUC__ + __attribute__((unused)) +#endif +static void _cffi_free_array_arguments(struct _cffi_freeme_s *freeme) +{ + do { + void *p = (void *)freeme; + freeme = freeme->next; + PyObject_Free(p); + } while (freeme != NULL); +} + +static int _cffi_init(void) +{ + PyObject *module, *c_api_object = NULL; + + module = PyImport_ImportModule("_cffi_backend"); + if (module == NULL) + goto failure; + + c_api_object = PyObject_GetAttrString(module, "_C_API"); + if (c_api_object == NULL) + goto failure; + if (!PyCapsule_CheckExact(c_api_object)) { + PyErr_SetNone(PyExc_ImportError); + goto failure; + } + memcpy(_cffi_exports, PyCapsule_GetPointer(c_api_object, "cffi"), + _CFFI_NUM_EXPORTS * sizeof(void *)); + + Py_DECREF(module); + Py_DECREF(c_api_object); + return 0; + + failure: + Py_XDECREF(module); + Py_XDECREF(c_api_object); + return -1; +} + +#define _cffi_type(num) ((CTypeDescrObject *)PyList_GET_ITEM(_cffi_types, num)) + +/**********/ +''' diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/vengine_gen.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/vengine_gen.py new file mode 100644 index 0000000000000000000000000000000000000000..bffc82122c353fbd15a395d77e829a95bf8546b0 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/vengine_gen.py @@ -0,0 +1,679 @@ +# +# DEPRECATED: implementation for ffi.verify() +# +import sys, os +import types + +from . import model +from .error import VerificationError + + +class VGenericEngine(object): + _class_key = 'g' + _gen_python_module = False + + def __init__(self, verifier): + self.verifier = verifier + self.ffi = verifier.ffi + self.export_symbols = [] + self._struct_pending_verification = {} + + def patch_extension_kwds(self, kwds): + # add 'export_symbols' to the dictionary. Note that we add the + # list before filling it. When we fill it, it will thus also show + # up in kwds['export_symbols']. + kwds.setdefault('export_symbols', self.export_symbols) + + def find_module(self, module_name, path, so_suffixes): + for so_suffix in so_suffixes: + basename = module_name + so_suffix + if path is None: + path = sys.path + for dirname in path: + filename = os.path.join(dirname, basename) + if os.path.isfile(filename): + return filename + + def collect_types(self): + pass # not needed in the generic engine + + def _prnt(self, what=''): + self._f.write(what + '\n') + + def write_source_to_f(self): + prnt = self._prnt + # first paste some standard set of lines that are mostly '#include' + prnt(cffimod_header) + # then paste the C source given by the user, verbatim. + prnt(self.verifier.preamble) + # + # call generate_gen_xxx_decl(), for every xxx found from + # ffi._parser._declarations. This generates all the functions. + self._generate('decl') + # + # on Windows, distutils insists on putting init_cffi_xyz in + # 'export_symbols', so instead of fighting it, just give up and + # give it one + if sys.platform == 'win32': + if sys.version_info >= (3,): + prefix = 'PyInit_' + else: + prefix = 'init' + modname = self.verifier.get_module_name() + prnt("void %s%s(void) { }\n" % (prefix, modname)) + + def load_library(self, flags=0): + # import it with the CFFI backend + backend = self.ffi._backend + # needs to make a path that contains '/', on Posix + filename = os.path.join(os.curdir, self.verifier.modulefilename) + module = backend.load_library(filename, flags) + # + # call loading_gen_struct() to get the struct layout inferred by + # the C compiler + self._load(module, 'loading') + + # build the FFILibrary class and instance, this is a module subclass + # because modules are expected to have usually-constant-attributes and + # in PyPy this means the JIT is able to treat attributes as constant, + # which we want. + class FFILibrary(types.ModuleType): + _cffi_generic_module = module + _cffi_ffi = self.ffi + _cffi_dir = [] + def __dir__(self): + return FFILibrary._cffi_dir + library = FFILibrary("") + # + # finally, call the loaded_gen_xxx() functions. This will set + # up the 'library' object. + self._load(module, 'loaded', library=library) + return library + + def _get_declarations(self): + lst = [(key, tp) for (key, (tp, qual)) in + self.ffi._parser._declarations.items()] + lst.sort() + return lst + + def _generate(self, step_name): + for name, tp in self._get_declarations(): + kind, realname = name.split(' ', 1) + try: + method = getattr(self, '_generate_gen_%s_%s' % (kind, + step_name)) + except AttributeError: + raise VerificationError( + "not implemented in verify(): %r" % name) + try: + method(tp, realname) + except Exception as e: + model.attach_exception_info(e, name) + raise + + def _load(self, module, step_name, **kwds): + for name, tp in self._get_declarations(): + kind, realname = name.split(' ', 1) + method = getattr(self, '_%s_gen_%s' % (step_name, kind)) + try: + method(tp, realname, module, **kwds) + except Exception as e: + model.attach_exception_info(e, name) + raise + + def _generate_nothing(self, tp, name): + pass + + def _loaded_noop(self, tp, name, module, **kwds): + pass + + # ---------- + # typedefs: generates no code so far + + _generate_gen_typedef_decl = _generate_nothing + _loading_gen_typedef = _loaded_noop + _loaded_gen_typedef = _loaded_noop + + # ---------- + # function declarations + + def _generate_gen_function_decl(self, tp, name): + assert isinstance(tp, model.FunctionPtrType) + if tp.ellipsis: + # cannot support vararg functions better than this: check for its + # exact type (including the fixed arguments), and build it as a + # constant function pointer (no _cffi_f_%s wrapper) + self._generate_gen_const(False, name, tp) + return + prnt = self._prnt + numargs = len(tp.args) + argnames = [] + for i, type in enumerate(tp.args): + indirection = '' + if isinstance(type, model.StructOrUnion): + indirection = '*' + argnames.append('%sx%d' % (indirection, i)) + context = 'argument of %s' % name + arglist = [type.get_c_name(' %s' % arg, context) + for type, arg in zip(tp.args, argnames)] + tpresult = tp.result + if isinstance(tpresult, model.StructOrUnion): + arglist.insert(0, tpresult.get_c_name(' *r', context)) + tpresult = model.void_type + arglist = ', '.join(arglist) or 'void' + wrappername = '_cffi_f_%s' % name + self.export_symbols.append(wrappername) + if tp.abi: + abi = tp.abi + ' ' + else: + abi = '' + funcdecl = ' %s%s(%s)' % (abi, wrappername, arglist) + context = 'result of %s' % name + prnt(tpresult.get_c_name(funcdecl, context)) + prnt('{') + # + if isinstance(tp.result, model.StructOrUnion): + result_code = '*r = ' + elif not isinstance(tp.result, model.VoidType): + result_code = 'return ' + else: + result_code = '' + prnt(' %s%s(%s);' % (result_code, name, ', '.join(argnames))) + prnt('}') + prnt() + + _loading_gen_function = _loaded_noop + + def _loaded_gen_function(self, tp, name, module, library): + assert isinstance(tp, model.FunctionPtrType) + if tp.ellipsis: + newfunction = self._load_constant(False, tp, name, module) + else: + indirections = [] + base_tp = tp + if (any(isinstance(typ, model.StructOrUnion) for typ in tp.args) + or isinstance(tp.result, model.StructOrUnion)): + indirect_args = [] + for i, typ in enumerate(tp.args): + if isinstance(typ, model.StructOrUnion): + typ = model.PointerType(typ) + indirections.append((i, typ)) + indirect_args.append(typ) + indirect_result = tp.result + if isinstance(indirect_result, model.StructOrUnion): + if indirect_result.fldtypes is None: + raise TypeError("'%s' is used as result type, " + "but is opaque" % ( + indirect_result._get_c_name(),)) + indirect_result = model.PointerType(indirect_result) + indirect_args.insert(0, indirect_result) + indirections.insert(0, ("result", indirect_result)) + indirect_result = model.void_type + tp = model.FunctionPtrType(tuple(indirect_args), + indirect_result, tp.ellipsis) + BFunc = self.ffi._get_cached_btype(tp) + wrappername = '_cffi_f_%s' % name + newfunction = module.load_function(BFunc, wrappername) + for i, typ in indirections: + newfunction = self._make_struct_wrapper(newfunction, i, typ, + base_tp) + setattr(library, name, newfunction) + type(library)._cffi_dir.append(name) + + def _make_struct_wrapper(self, oldfunc, i, tp, base_tp): + backend = self.ffi._backend + BType = self.ffi._get_cached_btype(tp) + if i == "result": + ffi = self.ffi + def newfunc(*args): + res = ffi.new(BType) + oldfunc(res, *args) + return res[0] + else: + def newfunc(*args): + args = args[:i] + (backend.newp(BType, args[i]),) + args[i+1:] + return oldfunc(*args) + newfunc._cffi_base_type = base_tp + return newfunc + + # ---------- + # named structs + + def _generate_gen_struct_decl(self, tp, name): + assert name == tp.name + self._generate_struct_or_union_decl(tp, 'struct', name) + + def _loading_gen_struct(self, tp, name, module): + self._loading_struct_or_union(tp, 'struct', name, module) + + def _loaded_gen_struct(self, tp, name, module, **kwds): + self._loaded_struct_or_union(tp) + + def _generate_gen_union_decl(self, tp, name): + assert name == tp.name + self._generate_struct_or_union_decl(tp, 'union', name) + + def _loading_gen_union(self, tp, name, module): + self._loading_struct_or_union(tp, 'union', name, module) + + def _loaded_gen_union(self, tp, name, module, **kwds): + self._loaded_struct_or_union(tp) + + def _generate_struct_or_union_decl(self, tp, prefix, name): + if tp.fldnames is None: + return # nothing to do with opaque structs + checkfuncname = '_cffi_check_%s_%s' % (prefix, name) + layoutfuncname = '_cffi_layout_%s_%s' % (prefix, name) + cname = ('%s %s' % (prefix, name)).strip() + # + prnt = self._prnt + prnt('static void %s(%s *p)' % (checkfuncname, cname)) + prnt('{') + prnt(' /* only to generate compile-time warnings or errors */') + prnt(' (void)p;') + for fname, ftype, fbitsize, fqual in tp.enumfields(): + if (isinstance(ftype, model.PrimitiveType) + and ftype.is_integer_type()) or fbitsize >= 0: + # accept all integers, but complain on float or double + prnt(' (void)((p->%s) << 1);' % fname) + else: + # only accept exactly the type declared. + try: + prnt(' { %s = &p->%s; (void)tmp; }' % ( + ftype.get_c_name('*tmp', 'field %r'%fname, quals=fqual), + fname)) + except VerificationError as e: + prnt(' /* %s */' % str(e)) # cannot verify it, ignore + prnt('}') + self.export_symbols.append(layoutfuncname) + prnt('intptr_t %s(intptr_t i)' % (layoutfuncname,)) + prnt('{') + prnt(' struct _cffi_aligncheck { char x; %s y; };' % cname) + prnt(' static intptr_t nums[] = {') + prnt(' sizeof(%s),' % cname) + prnt(' offsetof(struct _cffi_aligncheck, y),') + for fname, ftype, fbitsize, fqual in tp.enumfields(): + if fbitsize >= 0: + continue # xxx ignore fbitsize for now + prnt(' offsetof(%s, %s),' % (cname, fname)) + if isinstance(ftype, model.ArrayType) and ftype.length is None: + prnt(' 0, /* %s */' % ftype._get_c_name()) + else: + prnt(' sizeof(((%s *)0)->%s),' % (cname, fname)) + prnt(' -1') + prnt(' };') + prnt(' return nums[i];') + prnt(' /* the next line is not executed, but compiled */') + prnt(' %s(0);' % (checkfuncname,)) + prnt('}') + prnt() + + def _loading_struct_or_union(self, tp, prefix, name, module): + if tp.fldnames is None: + return # nothing to do with opaque structs + layoutfuncname = '_cffi_layout_%s_%s' % (prefix, name) + # + BFunc = self.ffi._typeof_locked("intptr_t(*)(intptr_t)")[0] + function = module.load_function(BFunc, layoutfuncname) + layout = [] + num = 0 + while True: + x = function(num) + if x < 0: break + layout.append(x) + num += 1 + if isinstance(tp, model.StructOrUnion) and tp.partial: + # use the function()'s sizes and offsets to guide the + # layout of the struct + totalsize = layout[0] + totalalignment = layout[1] + fieldofs = layout[2::2] + fieldsize = layout[3::2] + tp.force_flatten() + assert len(fieldofs) == len(fieldsize) == len(tp.fldnames) + tp.fixedlayout = fieldofs, fieldsize, totalsize, totalalignment + else: + cname = ('%s %s' % (prefix, name)).strip() + self._struct_pending_verification[tp] = layout, cname + + def _loaded_struct_or_union(self, tp): + if tp.fldnames is None: + return # nothing to do with opaque structs + self.ffi._get_cached_btype(tp) # force 'fixedlayout' to be considered + + if tp in self._struct_pending_verification: + # check that the layout sizes and offsets match the real ones + def check(realvalue, expectedvalue, msg): + if realvalue != expectedvalue: + raise VerificationError( + "%s (we have %d, but C compiler says %d)" + % (msg, expectedvalue, realvalue)) + ffi = self.ffi + BStruct = ffi._get_cached_btype(tp) + layout, cname = self._struct_pending_verification.pop(tp) + check(layout[0], ffi.sizeof(BStruct), "wrong total size") + check(layout[1], ffi.alignof(BStruct), "wrong total alignment") + i = 2 + for fname, ftype, fbitsize, fqual in tp.enumfields(): + if fbitsize >= 0: + continue # xxx ignore fbitsize for now + check(layout[i], ffi.offsetof(BStruct, fname), + "wrong offset for field %r" % (fname,)) + if layout[i+1] != 0: + BField = ffi._get_cached_btype(ftype) + check(layout[i+1], ffi.sizeof(BField), + "wrong size for field %r" % (fname,)) + i += 2 + assert i == len(layout) + + # ---------- + # 'anonymous' declarations. These are produced for anonymous structs + # or unions; the 'name' is obtained by a typedef. + + def _generate_gen_anonymous_decl(self, tp, name): + if isinstance(tp, model.EnumType): + self._generate_gen_enum_decl(tp, name, '') + else: + self._generate_struct_or_union_decl(tp, '', name) + + def _loading_gen_anonymous(self, tp, name, module): + if isinstance(tp, model.EnumType): + self._loading_gen_enum(tp, name, module, '') + else: + self._loading_struct_or_union(tp, '', name, module) + + def _loaded_gen_anonymous(self, tp, name, module, **kwds): + if isinstance(tp, model.EnumType): + self._loaded_gen_enum(tp, name, module, **kwds) + else: + self._loaded_struct_or_union(tp) + + # ---------- + # constants, likely declared with '#define' + + def _generate_gen_const(self, is_int, name, tp=None, category='const', + check_value=None): + prnt = self._prnt + funcname = '_cffi_%s_%s' % (category, name) + self.export_symbols.append(funcname) + if check_value is not None: + assert is_int + assert category == 'const' + prnt('int %s(char *out_error)' % funcname) + prnt('{') + self._check_int_constant_value(name, check_value) + prnt(' return 0;') + prnt('}') + elif is_int: + assert category == 'const' + prnt('int %s(long long *out_value)' % funcname) + prnt('{') + prnt(' *out_value = (long long)(%s);' % (name,)) + prnt(' return (%s) <= 0;' % (name,)) + prnt('}') + else: + assert tp is not None + assert check_value is None + if category == 'var': + ampersand = '&' + else: + ampersand = '' + extra = '' + if category == 'const' and isinstance(tp, model.StructOrUnion): + extra = 'const *' + ampersand = '&' + prnt(tp.get_c_name(' %s%s(void)' % (extra, funcname), name)) + prnt('{') + prnt(' return (%s%s);' % (ampersand, name)) + prnt('}') + prnt() + + def _generate_gen_constant_decl(self, tp, name): + is_int = isinstance(tp, model.PrimitiveType) and tp.is_integer_type() + self._generate_gen_const(is_int, name, tp) + + _loading_gen_constant = _loaded_noop + + def _load_constant(self, is_int, tp, name, module, check_value=None): + funcname = '_cffi_const_%s' % name + if check_value is not None: + assert is_int + self._load_known_int_constant(module, funcname) + value = check_value + elif is_int: + BType = self.ffi._typeof_locked("long long*")[0] + BFunc = self.ffi._typeof_locked("int(*)(long long*)")[0] + function = module.load_function(BFunc, funcname) + p = self.ffi.new(BType) + negative = function(p) + value = int(p[0]) + if value < 0 and not negative: + BLongLong = self.ffi._typeof_locked("long long")[0] + value += (1 << (8*self.ffi.sizeof(BLongLong))) + else: + assert check_value is None + fntypeextra = '(*)(void)' + if isinstance(tp, model.StructOrUnion): + fntypeextra = '*' + fntypeextra + BFunc = self.ffi._typeof_locked(tp.get_c_name(fntypeextra, name))[0] + function = module.load_function(BFunc, funcname) + value = function() + if isinstance(tp, model.StructOrUnion): + value = value[0] + return value + + def _loaded_gen_constant(self, tp, name, module, library): + is_int = isinstance(tp, model.PrimitiveType) and tp.is_integer_type() + value = self._load_constant(is_int, tp, name, module) + setattr(library, name, value) + type(library)._cffi_dir.append(name) + + # ---------- + # enums + + def _check_int_constant_value(self, name, value): + prnt = self._prnt + if value <= 0: + prnt(' if ((%s) > 0 || (long)(%s) != %dL) {' % ( + name, name, value)) + else: + prnt(' if ((%s) <= 0 || (unsigned long)(%s) != %dUL) {' % ( + name, name, value)) + prnt(' char buf[64];') + prnt(' if ((%s) <= 0)' % name) + prnt(' sprintf(buf, "%%ld", (long)(%s));' % name) + prnt(' else') + prnt(' sprintf(buf, "%%lu", (unsigned long)(%s));' % + name) + prnt(' sprintf(out_error, "%s has the real value %s, not %s",') + prnt(' "%s", buf, "%d");' % (name[:100], value)) + prnt(' return -1;') + prnt(' }') + + def _load_known_int_constant(self, module, funcname): + BType = self.ffi._typeof_locked("char[]")[0] + BFunc = self.ffi._typeof_locked("int(*)(char*)")[0] + function = module.load_function(BFunc, funcname) + p = self.ffi.new(BType, 256) + if function(p) < 0: + error = self.ffi.string(p) + if sys.version_info >= (3,): + error = str(error, 'utf-8') + raise VerificationError(error) + + def _enum_funcname(self, prefix, name): + # "$enum_$1" => "___D_enum____D_1" + name = name.replace('$', '___D_') + return '_cffi_e_%s_%s' % (prefix, name) + + def _generate_gen_enum_decl(self, tp, name, prefix='enum'): + if tp.partial: + for enumerator in tp.enumerators: + self._generate_gen_const(True, enumerator) + return + # + funcname = self._enum_funcname(prefix, name) + self.export_symbols.append(funcname) + prnt = self._prnt + prnt('int %s(char *out_error)' % funcname) + prnt('{') + for enumerator, enumvalue in zip(tp.enumerators, tp.enumvalues): + self._check_int_constant_value(enumerator, enumvalue) + prnt(' return 0;') + prnt('}') + prnt() + + def _loading_gen_enum(self, tp, name, module, prefix='enum'): + if tp.partial: + enumvalues = [self._load_constant(True, tp, enumerator, module) + for enumerator in tp.enumerators] + tp.enumvalues = tuple(enumvalues) + tp.partial_resolved = True + else: + funcname = self._enum_funcname(prefix, name) + self._load_known_int_constant(module, funcname) + + def _loaded_gen_enum(self, tp, name, module, library): + for enumerator, enumvalue in zip(tp.enumerators, tp.enumvalues): + setattr(library, enumerator, enumvalue) + type(library)._cffi_dir.append(enumerator) + + # ---------- + # macros: for now only for integers + + def _generate_gen_macro_decl(self, tp, name): + if tp == '...': + check_value = None + else: + check_value = tp # an integer + self._generate_gen_const(True, name, check_value=check_value) + + _loading_gen_macro = _loaded_noop + + def _loaded_gen_macro(self, tp, name, module, library): + if tp == '...': + check_value = None + else: + check_value = tp # an integer + value = self._load_constant(True, tp, name, module, + check_value=check_value) + setattr(library, name, value) + type(library)._cffi_dir.append(name) + + # ---------- + # global variables + + def _generate_gen_variable_decl(self, tp, name): + if isinstance(tp, model.ArrayType): + if tp.length_is_unknown(): + prnt = self._prnt + funcname = '_cffi_sizeof_%s' % (name,) + self.export_symbols.append(funcname) + prnt("size_t %s(void)" % funcname) + prnt("{") + prnt(" return sizeof(%s);" % (name,)) + prnt("}") + tp_ptr = model.PointerType(tp.item) + self._generate_gen_const(False, name, tp_ptr) + else: + tp_ptr = model.PointerType(tp) + self._generate_gen_const(False, name, tp_ptr, category='var') + + _loading_gen_variable = _loaded_noop + + def _loaded_gen_variable(self, tp, name, module, library): + if isinstance(tp, model.ArrayType): # int a[5] is "constant" in the + # sense that "a=..." is forbidden + if tp.length_is_unknown(): + funcname = '_cffi_sizeof_%s' % (name,) + BFunc = self.ffi._typeof_locked('size_t(*)(void)')[0] + function = module.load_function(BFunc, funcname) + size = function() + BItemType = self.ffi._get_cached_btype(tp.item) + length, rest = divmod(size, self.ffi.sizeof(BItemType)) + if rest != 0: + raise VerificationError( + "bad size: %r does not seem to be an array of %s" % + (name, tp.item)) + tp = tp.resolve_length(length) + tp_ptr = model.PointerType(tp.item) + value = self._load_constant(False, tp_ptr, name, module) + # 'value' is a which we have to replace with + # a if the N is actually known + if tp.length is not None: + BArray = self.ffi._get_cached_btype(tp) + value = self.ffi.cast(BArray, value) + setattr(library, name, value) + type(library)._cffi_dir.append(name) + return + # remove ptr= from the library instance, and replace + # it by a property on the class, which reads/writes into ptr[0]. + funcname = '_cffi_var_%s' % name + BFunc = self.ffi._typeof_locked(tp.get_c_name('*(*)(void)', name))[0] + function = module.load_function(BFunc, funcname) + ptr = function() + def getter(library): + return ptr[0] + def setter(library, value): + ptr[0] = value + setattr(type(library), name, property(getter, setter)) + type(library)._cffi_dir.append(name) + +cffimod_header = r''' +#include +#include +#include +#include +#include /* XXX for ssize_t on some platforms */ + +/* this block of #ifs should be kept exactly identical between + c/_cffi_backend.c, cffi/vengine_cpy.py, cffi/vengine_gen.py + and cffi/_cffi_include.h */ +#if defined(_MSC_VER) +# include /* for alloca() */ +# if _MSC_VER < 1600 /* MSVC < 2010 */ + typedef __int8 int8_t; + typedef __int16 int16_t; + typedef __int32 int32_t; + typedef __int64 int64_t; + typedef unsigned __int8 uint8_t; + typedef unsigned __int16 uint16_t; + typedef unsigned __int32 uint32_t; + typedef unsigned __int64 uint64_t; + typedef __int8 int_least8_t; + typedef __int16 int_least16_t; + typedef __int32 int_least32_t; + typedef __int64 int_least64_t; + typedef unsigned __int8 uint_least8_t; + typedef unsigned __int16 uint_least16_t; + typedef unsigned __int32 uint_least32_t; + typedef unsigned __int64 uint_least64_t; + typedef __int8 int_fast8_t; + typedef __int16 int_fast16_t; + typedef __int32 int_fast32_t; + typedef __int64 int_fast64_t; + typedef unsigned __int8 uint_fast8_t; + typedef unsigned __int16 uint_fast16_t; + typedef unsigned __int32 uint_fast32_t; + typedef unsigned __int64 uint_fast64_t; + typedef __int64 intmax_t; + typedef unsigned __int64 uintmax_t; +# else +# include +# endif +# if _MSC_VER < 1800 /* MSVC < 2013 */ +# ifndef __cplusplus + typedef unsigned char _Bool; +# endif +# endif +# define _cffi_float_complex_t _Fcomplex /* include for it */ +# define _cffi_double_complex_t _Dcomplex /* include for it */ +#else +# include +# if (defined (__SVR4) && defined (__sun)) || defined(_AIX) || defined(__hpux) +# include +# endif +# define _cffi_float_complex_t float _Complex +# define _cffi_double_complex_t double _Complex +#endif +''' diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/verifier.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..e392a2b7fdab66662f5a32885cbe865d6c538ebe --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/verifier.py @@ -0,0 +1,306 @@ +# +# DEPRECATED: implementation for ffi.verify() +# +import sys, os, binascii, shutil, io +from . import __version_verifier_modules__ +from . import ffiplatform +from .error import VerificationError + +if sys.version_info >= (3, 3): + import importlib.machinery + def _extension_suffixes(): + return importlib.machinery.EXTENSION_SUFFIXES[:] +else: + import imp + def _extension_suffixes(): + return [suffix for suffix, _, type in imp.get_suffixes() + if type == imp.C_EXTENSION] + + +if sys.version_info >= (3,): + NativeIO = io.StringIO +else: + class NativeIO(io.BytesIO): + def write(self, s): + if isinstance(s, unicode): + s = s.encode('ascii') + super(NativeIO, self).write(s) + + +class Verifier(object): + + def __init__(self, ffi, preamble, tmpdir=None, modulename=None, + ext_package=None, tag='', force_generic_engine=False, + source_extension='.c', flags=None, relative_to=None, **kwds): + if ffi._parser._uses_new_feature: + raise VerificationError( + "feature not supported with ffi.verify(), but only " + "with ffi.set_source(): %s" % (ffi._parser._uses_new_feature,)) + self.ffi = ffi + self.preamble = preamble + if not modulename: + flattened_kwds = ffiplatform.flatten(kwds) + vengine_class = _locate_engine_class(ffi, force_generic_engine) + self._vengine = vengine_class(self) + self._vengine.patch_extension_kwds(kwds) + self.flags = flags + self.kwds = self.make_relative_to(kwds, relative_to) + # + if modulename: + if tag: + raise TypeError("can't specify both 'modulename' and 'tag'") + else: + key = '\x00'.join(['%d.%d' % sys.version_info[:2], + __version_verifier_modules__, + preamble, flattened_kwds] + + ffi._cdefsources) + if sys.version_info >= (3,): + key = key.encode('utf-8') + k1 = hex(binascii.crc32(key[0::2]) & 0xffffffff) + k1 = k1.lstrip('0x').rstrip('L') + k2 = hex(binascii.crc32(key[1::2]) & 0xffffffff) + k2 = k2.lstrip('0').rstrip('L') + modulename = '_cffi_%s_%s%s%s' % (tag, self._vengine._class_key, + k1, k2) + suffix = _get_so_suffixes()[0] + self.tmpdir = tmpdir or _caller_dir_pycache() + self.sourcefilename = os.path.join(self.tmpdir, modulename + source_extension) + self.modulefilename = os.path.join(self.tmpdir, modulename + suffix) + self.ext_package = ext_package + self._has_source = False + self._has_module = False + + def write_source(self, file=None): + """Write the C source code. It is produced in 'self.sourcefilename', + which can be tweaked beforehand.""" + with self.ffi._lock: + if self._has_source and file is None: + raise VerificationError( + "source code already written") + self._write_source(file) + + def compile_module(self): + """Write the C source code (if not done already) and compile it. + This produces a dynamic link library in 'self.modulefilename'.""" + with self.ffi._lock: + if self._has_module: + raise VerificationError("module already compiled") + if not self._has_source: + self._write_source() + self._compile_module() + + def load_library(self): + """Get a C module from this Verifier instance. + Returns an instance of a FFILibrary class that behaves like the + objects returned by ffi.dlopen(), but that delegates all + operations to the C module. If necessary, the C code is written + and compiled first. + """ + with self.ffi._lock: + if not self._has_module: + self._locate_module() + if not self._has_module: + if not self._has_source: + self._write_source() + self._compile_module() + return self._load_library() + + def get_module_name(self): + basename = os.path.basename(self.modulefilename) + # kill both the .so extension and the other .'s, as introduced + # by Python 3: 'basename.cpython-33m.so' + basename = basename.split('.', 1)[0] + # and the _d added in Python 2 debug builds --- but try to be + # conservative and not kill a legitimate _d + if basename.endswith('_d') and hasattr(sys, 'gettotalrefcount'): + basename = basename[:-2] + return basename + + def get_extension(self): + if not self._has_source: + with self.ffi._lock: + if not self._has_source: + self._write_source() + sourcename = ffiplatform.maybe_relative_path(self.sourcefilename) + modname = self.get_module_name() + return ffiplatform.get_extension(sourcename, modname, **self.kwds) + + def generates_python_module(self): + return self._vengine._gen_python_module + + def make_relative_to(self, kwds, relative_to): + if relative_to and os.path.dirname(relative_to): + dirname = os.path.dirname(relative_to) + kwds = kwds.copy() + for key in ffiplatform.LIST_OF_FILE_NAMES: + if key in kwds: + lst = kwds[key] + if not isinstance(lst, (list, tuple)): + raise TypeError("keyword '%s' should be a list or tuple" + % (key,)) + lst = [os.path.join(dirname, fn) for fn in lst] + kwds[key] = lst + return kwds + + # ---------- + + def _locate_module(self): + if not os.path.isfile(self.modulefilename): + if self.ext_package: + try: + pkg = __import__(self.ext_package, None, None, ['__doc__']) + except ImportError: + return # cannot import the package itself, give up + # (e.g. it might be called differently before installation) + path = pkg.__path__ + else: + path = None + filename = self._vengine.find_module(self.get_module_name(), path, + _get_so_suffixes()) + if filename is None: + return + self.modulefilename = filename + self._vengine.collect_types() + self._has_module = True + + def _write_source_to(self, file): + self._vengine._f = file + try: + self._vengine.write_source_to_f() + finally: + del self._vengine._f + + def _write_source(self, file=None): + if file is not None: + self._write_source_to(file) + else: + # Write our source file to an in memory file. + f = NativeIO() + self._write_source_to(f) + source_data = f.getvalue() + + # Determine if this matches the current file + if os.path.exists(self.sourcefilename): + with open(self.sourcefilename, "r") as fp: + needs_written = not (fp.read() == source_data) + else: + needs_written = True + + # Actually write the file out if it doesn't match + if needs_written: + _ensure_dir(self.sourcefilename) + with open(self.sourcefilename, "w") as fp: + fp.write(source_data) + + # Set this flag + self._has_source = True + + def _compile_module(self): + # compile this C source + tmpdir = os.path.dirname(self.sourcefilename) + outputfilename = ffiplatform.compile(tmpdir, self.get_extension()) + try: + same = ffiplatform.samefile(outputfilename, self.modulefilename) + except OSError: + same = False + if not same: + _ensure_dir(self.modulefilename) + shutil.move(outputfilename, self.modulefilename) + self._has_module = True + + def _load_library(self): + assert self._has_module + if self.flags is not None: + return self._vengine.load_library(self.flags) + else: + return self._vengine.load_library() + +# ____________________________________________________________ + +_FORCE_GENERIC_ENGINE = False # for tests + +def _locate_engine_class(ffi, force_generic_engine): + if _FORCE_GENERIC_ENGINE: + force_generic_engine = True + if not force_generic_engine: + if '__pypy__' in sys.builtin_module_names: + force_generic_engine = True + else: + try: + import _cffi_backend + except ImportError: + _cffi_backend = '?' + if ffi._backend is not _cffi_backend: + force_generic_engine = True + if force_generic_engine: + from . import vengine_gen + return vengine_gen.VGenericEngine + else: + from . import vengine_cpy + return vengine_cpy.VCPythonEngine + +# ____________________________________________________________ + +_TMPDIR = None + +def _caller_dir_pycache(): + if _TMPDIR: + return _TMPDIR + result = os.environ.get('CFFI_TMPDIR') + if result: + return result + filename = sys._getframe(2).f_code.co_filename + return os.path.abspath(os.path.join(os.path.dirname(filename), + '__pycache__')) + +def set_tmpdir(dirname): + """Set the temporary directory to use instead of __pycache__.""" + global _TMPDIR + _TMPDIR = dirname + +def cleanup_tmpdir(tmpdir=None, keep_so=False): + """Clean up the temporary directory by removing all files in it + called `_cffi_*.{c,so}` as well as the `build` subdirectory.""" + tmpdir = tmpdir or _caller_dir_pycache() + try: + filelist = os.listdir(tmpdir) + except OSError: + return + if keep_so: + suffix = '.c' # only remove .c files + else: + suffix = _get_so_suffixes()[0].lower() + for fn in filelist: + if fn.lower().startswith('_cffi_') and ( + fn.lower().endswith(suffix) or fn.lower().endswith('.c')): + try: + os.unlink(os.path.join(tmpdir, fn)) + except OSError: + pass + clean_dir = [os.path.join(tmpdir, 'build')] + for dir in clean_dir: + try: + for fn in os.listdir(dir): + fn = os.path.join(dir, fn) + if os.path.isdir(fn): + clean_dir.append(fn) + else: + os.unlink(fn) + except OSError: + pass + +def _get_so_suffixes(): + suffixes = _extension_suffixes() + if not suffixes: + # bah, no C_EXTENSION available. Occurs on pypy without cpyext + if sys.platform == 'win32': + suffixes = [".pyd"] + else: + suffixes = [".so"] + + return suffixes + +def _ensure_dir(filename): + dirname = os.path.dirname(filename) + if dirname and not os.path.isdir(dirname): + os.makedirs(dirname) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/chardet-6.0.0.post1.dist-info/INSTALLER b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/chardet-6.0.0.post1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/chardet-6.0.0.post1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/chardet-6.0.0.post1.dist-info/METADATA b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/chardet-6.0.0.post1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..928dad697117450dcb96c3cec679742eb6793d4e --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/chardet-6.0.0.post1.dist-info/METADATA @@ -0,0 +1,92 @@ +Metadata-Version: 2.4 +Name: chardet +Version: 6.0.0.post1 +Summary: Universal encoding detector for Python 3 +Project-URL: Documentation, https://chardet.readthedocs.io/ +Project-URL: Homepage, http://chardet.github.io +Project-URL: Issues, https://github.com/chardet/chardet/issues +Project-URL: Repository, https://github.com/chardet/chardet +Author-email: Mark Pilgrim +Maintainer: Ian Cordasco +Maintainer-email: Dan Blanchard +License: LGPL-2.1-or-later +License-File: LICENSE +Keywords: encoding,i18n,xml +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: GNU Lesser General Public License v2 or later (LGPLv2+) +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +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 :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Topic :: Text Processing :: Linguistic +Requires-Python: >=3.10 +Description-Content-Type: text/x-rst + +Chardet: The Universal Character Encoding Detector +-------------------------------------------------- + +.. image:: https://github.com/chardet/chardet/actions/workflows/test.yml/badge.svg?branch=main + :alt: Build status + :target: https://github.com/chardet/chardet/actions/workflows/test.yml + +.. image:: https://img.shields.io/pypi/v/chardet.svg + :target: https://pypi.org/project/chardet/ + :alt: Latest version on PyPI + +.. image:: https://img.shields.io/pypi/l/chardet.svg + :alt: License + + +Detects over 70 character encodings including: + +- All major Unicode encodings (UTF-8, UTF-16, UTF-32) +- Windows code pages (Windows-1250 through Windows-1258) +- ISO-8859 family (ISO-8859-1 through ISO-8859-16) +- CJK encodings (Big5, GB18030, EUC-JP, EUC-KR, Shift-JIS, and more) +- Cyrillic encodings (KOI8-R, KOI8-U, IBM866, and more) +- Mac encodings (MacRoman, MacCyrillic, and more) +- DOS/OEM code pages (CP437, CP850, CP866, and more) +- EBCDIC variants (CP037, CP500) + +See the `full list of supported encodings `_. + + +Requires Python 3.10+. + +Installation +------------ + +Install from `PyPI `_:: + + pip install chardet + +Documentation +------------- + +For users, docs are now available at https://chardet.readthedocs.io/. + +Command-line Tool +----------------- + +chardet comes with a command-line script which reports on the encodings of one +or more files:: + + % chardetect somefile someotherfile + somefile: windows-1252 with confidence 0.5 + someotherfile: ascii with confidence 1.0 + +About +----- + +This is a continuation of Mark Pilgrim's excellent original chardet port from C, and `Ian Cordasco `_'s +`charade `_ Python 3-compatible fork. + +:maintainer: Dan Blanchard diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/chardet-6.0.0.post1.dist-info/RECORD b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/chardet-6.0.0.post1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..ea4346255ba7c196f4c567058e51a9274e506369 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/chardet-6.0.0.post1.dist-info/RECORD @@ -0,0 +1,177 @@ +../../../bin/chardetect,sha256=EWpqGUBN3bWRKtLFYLmdtT3fck2Kxic-qWVBMsr5Ajk,255 +chardet-6.0.0.post1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +chardet-6.0.0.post1.dist-info/METADATA,sha256=cWfnW72-smToT0ag5zwj5YiAAZTPDPbceLwcnYJxahQ,3309 +chardet-6.0.0.post1.dist-info/RECORD,, +chardet-6.0.0.post1.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87 +chardet-6.0.0.post1.dist-info/entry_points.txt,sha256=_cdvYc4jyY68GYfsQAAthNMxO-yodcGkvNC1xOEsLmI,59 +chardet-6.0.0.post1.dist-info/licenses/LICENSE,sha256=IOUP56rj5WN46_BBfZ3pBPVaDmHk3zFTM-YypNNVXZU,26419 +chardet/__init__.py,sha256=64kOBYhycwV6NujTpHvMQfnesHQhkoW7lwq_-THjckw,6974 +chardet/__main__.py,sha256=puNj2o_QfBRKElEkiVp1zEIL1gGYD2o-JuXLFlqHDC4,123 +chardet/__pycache__/__init__.cpython-310.pyc,, +chardet/__pycache__/__main__.cpython-310.pyc,, +chardet/__pycache__/big5freq.cpython-310.pyc,, +chardet/__pycache__/big5prober.cpython-310.pyc,, +chardet/__pycache__/chardistribution.cpython-310.pyc,, +chardet/__pycache__/charsetgroupprober.cpython-310.pyc,, +chardet/__pycache__/charsetprober.cpython-310.pyc,, +chardet/__pycache__/codingstatemachine.cpython-310.pyc,, +chardet/__pycache__/codingstatemachinedict.cpython-310.pyc,, +chardet/__pycache__/cp949prober.cpython-310.pyc,, +chardet/__pycache__/enums.cpython-310.pyc,, +chardet/__pycache__/escprober.cpython-310.pyc,, +chardet/__pycache__/escsm.cpython-310.pyc,, +chardet/__pycache__/eucjpprober.cpython-310.pyc,, +chardet/__pycache__/euckrfreq.cpython-310.pyc,, +chardet/__pycache__/euckrprober.cpython-310.pyc,, +chardet/__pycache__/gb18030prober.cpython-310.pyc,, +chardet/__pycache__/gb2312freq.cpython-310.pyc,, +chardet/__pycache__/hebrewprober.cpython-310.pyc,, +chardet/__pycache__/jisfreq.cpython-310.pyc,, +chardet/__pycache__/johabfreq.cpython-310.pyc,, +chardet/__pycache__/johabprober.cpython-310.pyc,, +chardet/__pycache__/jpcntx.cpython-310.pyc,, +chardet/__pycache__/langarabicmodel.cpython-310.pyc,, +chardet/__pycache__/langbelarusianmodel.cpython-310.pyc,, +chardet/__pycache__/langbretonmodel.cpython-310.pyc,, +chardet/__pycache__/langbulgarianmodel.cpython-310.pyc,, +chardet/__pycache__/langcroatianmodel.cpython-310.pyc,, +chardet/__pycache__/langczechmodel.cpython-310.pyc,, +chardet/__pycache__/langdanishmodel.cpython-310.pyc,, +chardet/__pycache__/langdutchmodel.cpython-310.pyc,, +chardet/__pycache__/langenglishmodel.cpython-310.pyc,, +chardet/__pycache__/langesperantomodel.cpython-310.pyc,, +chardet/__pycache__/langestonianmodel.cpython-310.pyc,, +chardet/__pycache__/langfarsimodel.cpython-310.pyc,, +chardet/__pycache__/langfinnishmodel.cpython-310.pyc,, +chardet/__pycache__/langfrenchmodel.cpython-310.pyc,, +chardet/__pycache__/langgermanmodel.cpython-310.pyc,, +chardet/__pycache__/langgreekmodel.cpython-310.pyc,, +chardet/__pycache__/langhebrewmodel.cpython-310.pyc,, +chardet/__pycache__/langhungarianmodel.cpython-310.pyc,, +chardet/__pycache__/langicelandicmodel.cpython-310.pyc,, +chardet/__pycache__/langindonesianmodel.cpython-310.pyc,, +chardet/__pycache__/langirishmodel.cpython-310.pyc,, +chardet/__pycache__/langitalianmodel.cpython-310.pyc,, +chardet/__pycache__/langkazakhmodel.cpython-310.pyc,, +chardet/__pycache__/langlatvianmodel.cpython-310.pyc,, +chardet/__pycache__/langlithuanianmodel.cpython-310.pyc,, +chardet/__pycache__/langmacedonianmodel.cpython-310.pyc,, +chardet/__pycache__/langmalaymodel.cpython-310.pyc,, +chardet/__pycache__/langmaltesemodel.cpython-310.pyc,, +chardet/__pycache__/langnorwegianmodel.cpython-310.pyc,, +chardet/__pycache__/langpolishmodel.cpython-310.pyc,, +chardet/__pycache__/langportuguesemodel.cpython-310.pyc,, +chardet/__pycache__/langromanianmodel.cpython-310.pyc,, +chardet/__pycache__/langrussianmodel.cpython-310.pyc,, +chardet/__pycache__/langscottishgaelicmodel.cpython-310.pyc,, +chardet/__pycache__/langserbianmodel.cpython-310.pyc,, +chardet/__pycache__/langslovakmodel.cpython-310.pyc,, +chardet/__pycache__/langslovenemodel.cpython-310.pyc,, +chardet/__pycache__/langspanishmodel.cpython-310.pyc,, +chardet/__pycache__/langswedishmodel.cpython-310.pyc,, +chardet/__pycache__/langtajikmodel.cpython-310.pyc,, +chardet/__pycache__/langthaimodel.cpython-310.pyc,, +chardet/__pycache__/langturkishmodel.cpython-310.pyc,, +chardet/__pycache__/langukrainianmodel.cpython-310.pyc,, +chardet/__pycache__/langvietnamesemodel.cpython-310.pyc,, +chardet/__pycache__/langwelshmodel.cpython-310.pyc,, +chardet/__pycache__/mbcharsetprober.cpython-310.pyc,, +chardet/__pycache__/mbcsgroupprober.cpython-310.pyc,, +chardet/__pycache__/mbcssm.cpython-310.pyc,, +chardet/__pycache__/resultdict.cpython-310.pyc,, +chardet/__pycache__/sbcharsetprober.cpython-310.pyc,, +chardet/__pycache__/sbcsgroupprober.cpython-310.pyc,, +chardet/__pycache__/sjisprober.cpython-310.pyc,, +chardet/__pycache__/universaldetector.cpython-310.pyc,, +chardet/__pycache__/utf1632prober.cpython-310.pyc,, +chardet/__pycache__/utf8prober.cpython-310.pyc,, +chardet/__pycache__/version.cpython-310.pyc,, +chardet/big5freq.py,sha256=Mh0i4xY_VYRd2qrG1G8W2xvBrduJeZf30rGG9KFN8rQ,31208 +chardet/big5prober.py,sha256=OAjbiv2wbu5Z1jy6FOruiQzeFkJVKZxTKUbt9934ye0,1697 +chardet/chardistribution.py,sha256=6NilX0ynktuzRcvHjqLzipMs81Kbb1uY7y9ufUyBHSc,9487 +chardet/charsetgroupprober.py,sha256=OEEHKZVeHO7yjBey5a6xSqzb_FrNUvKW4AhhKPjgSvs,5353 +chardet/charsetprober.py,sha256=SGyK8t60bJ_Rc8pucGgiQsxI8DV_idXkaQSjsFyQ84Y,7255 +chardet/cli/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +chardet/cli/__pycache__/__init__.cpython-310.pyc,, +chardet/cli/__pycache__/chardetect.cpython-310.pyc,, +chardet/cli/chardetect.py,sha256=FfKct9uaAzNhEVlY4ZMtTO0nYJ0TjqJOmF2DJgJTKZQ,4174 +chardet/codingstatemachine.py,sha256=tYqfs3CoCCGd-15NPX4qjrUyZvtYTW22aJ1J7EoP2Ho,3666 +chardet/codingstatemachinedict.py,sha256=_VF226B6hayBOfXPWQlkwiTL-mqotwYX6nT2sph1O6E,257 +chardet/cp949prober.py,sha256=NBS0IHVFGjFkYGQNuRN3QkFFQm505Tpp6VSycppmB0E,1794 +chardet/enums.py,sha256=kpJ2-n-gcIRrSziCfBXTZ2mCFOKW3JgSlI34wUSbVVk,2565 +chardet/escprober.py,sha256=drclRmIesU7qZaXotZsyWgPpWw3ogYiZjBTqj_D9eMc,3957 +chardet/escsm.py,sha256=k6_GmKNj6g_AdmrvYBhPsF3thV_PDdFBfrSMLfY29xU,9157 +chardet/eucjpprober.py,sha256=rIPh6tup-MOLn29-7MQdN4DhTlyjVB5z3zrcRxq7zJs,3868 +chardet/euckrfreq.py,sha256=opYQeXgdj_MX-JEQAXgIIK7kIecD_TDDr-lTS6zVmSE,13500 +chardet/euckrprober.py,sha256=bkmj4Ubo30YxTpMHdhrdXqiIDWLLqi1BskSNoN6kLK4,1687 +chardet/gb18030prober.py,sha256=sfNljf6YOBm9Gai_URvUSDZZOIThZ8Fxcm3_mjntcXE,1832 +chardet/gb2312freq.py,sha256=MqgP5KiRO-RrDzx109yd72sks9Wod8d0q0O1zpD7V60,20669 +chardet/hebrewprober.py,sha256=gHTwPK0hfDejJgemGbPpJCr2KRqX9jDdXcI7ET6xVao,14471 +chardet/jisfreq.py,sha256=7swGVKLeF6Pw_I8xptFD-zQjrgcsXbCcPhAbYlj2FlY,25730 +chardet/johabfreq.py,sha256=oN93lsV5WMhoFKmPyyzvS4PW4b5q_Qs0fxqQ_vnLQWo,42432 +chardet/johabprober.py,sha256=4XpzH7soufuaj7A4cnyNaJ2mPSmKsT7Bln5kOZVDr_o,1686 +chardet/jpcntx.py,sha256=negoAkSPQggOpCDX7wsoesmlZ1MLLY39GWjHH02E6Rg,27076 +chardet/langarabicmodel.py,sha256=xml1O_7Nq7wftOmINSGferIMdO8Yo-P89VgIwLA5o18,70304 +chardet/langbelarusianmodel.py,sha256=Vpw_Fey_ggJHptgNNw-t1bPd-i_op__UAId97cpK5G0,240191 +chardet/langbretonmodel.py,sha256=Pa7QohbfJJEzN4_fMDa7Pn0MW6c6xhS6hw8MnF9DUWI,309826 +chardet/langbulgarianmodel.py,sha256=esh93M79Y2_-gLCAyGxsdaKFByRb9pKq8_3MJq4UoHo,226268 +chardet/langcroatianmodel.py,sha256=QJjVlxxg15rAVsmOtDzg7Ckm9j_rjR2V3o_xpntEU7M,226583 +chardet/langczechmodel.py,sha256=DuD2khvUxZS_SUuh1XUFXivTsqR0-7-Ub6V1ta-cy7M,367193 +chardet/langdanishmodel.py,sha256=PWE1QaNYOrriRKqJT_qiuiR5HncdA_y1l7L9R15Flt8,248894 +chardet/langdutchmodel.py,sha256=GmirIFJbGBqPf7-MdjoXdQPb3fU_SoAi-utBrAb2vzw,388428 +chardet/langenglishmodel.py,sha256=C8MgAPjQsfMEY1Yf4FZLYEe3yM8IivWl88Sjc6OWtKs,207690 +chardet/langesperantomodel.py,sha256=gl5tPnUc74_7HnB4b2lE4chfMiAi6o3Jp3iDN0wzHGs,206136 +chardet/langestonianmodel.py,sha256=_F3-XNEqCBH7cu-J1Tmgw5vJoSmg-qKji7L1rl8ki7M,231838 +chardet/langfarsimodel.py,sha256=vVR21mqIxOvbw_pkWslOhQKPJGziHjRFR2OzCD-xpF0,134265 +chardet/langfinnishmodel.py,sha256=1SQpvuv-OW7w34E6JNmqAzq1bOeLhWnfe7QydRcfPKs,263432 +chardet/langfrenchmodel.py,sha256=rF5L64mvyj9-n7VwMFg7kojhaHiQws6xlTxaSwQjbYg,429813 +chardet/langgermanmodel.py,sha256=bbUTYnkpSkccrDsGoNocbZCjeI8D-dtxdQFAlbfXYlg,251537 +chardet/langgreekmodel.py,sha256=z59gZhq3dX9XrQwu6SylwZggmeUamqmXGVU4XSautpA,246200 +chardet/langhebrewmodel.py,sha256=bGq0xmik1S78WO5v05ZZa0nU5KDbDVxQhWL0SMSkiaw,91563 +chardet/langhungarianmodel.py,sha256=IcxKdHiJlntu2_sB8g5DqmEv4VhybJChK9s_J9GlV44,278187 +chardet/langicelandicmodel.py,sha256=J9pgVLVlbfadZXnT5kvq248TlxjP7Sm37aXvO0iHIpI,354898 +chardet/langindonesianmodel.py,sha256=NmlegGHLaOyRZwnJN-duL78YOf6lUQo5Wtkypo4wEKc,207828 +chardet/langirishmodel.py,sha256=pP0b_9Hul7iFcq2v-zUm396iXfzpS3x1NRWUfIHPbAk,271595 +chardet/langitalianmodel.py,sha256=X-mdqYXNLaX_-xLapuJg2LKqsNK-ggLvFpVKx85_Hjw,288506 +chardet/langkazakhmodel.py,sha256=zk_NOHDHvDKQzyPQKo7YGU4CMeDS8kUinuPd7svMkzI,362124 +chardet/langlatvianmodel.py,sha256=Z7V5Q2TUpSnf0YBWVUpmSipyC1h93LB7pZnueGmbW7I,299197 +chardet/langlithuanianmodel.py,sha256=3_093epeaKFCjFm8cesV12mOxF7gWe5H5A_cXjH3i8w,271132 +chardet/langmacedonianmodel.py,sha256=qBk34UwZV1n0ziXE3ZuFFS0thFhQ5t3yAR0VeYR_55A,238293 +chardet/langmalaymodel.py,sha256=bMYJfTyCPYGDHlKBujBZ1vSuwJwklrgkQwM0ADkO-Xw,207598 +chardet/langmaltesemodel.py,sha256=oNjxWqZ21qMa3Ttg8YDaYHHU5VGbj1uQ6ceFoDwX118,181952 +chardet/langnorwegianmodel.py,sha256=c2J39HtfSfpauAMPxK8g-sppfTzBg94WZRIr4oCdtGQ,249047 +chardet/langpolishmodel.py,sha256=nDtI30JLxqlr55JUPebikxlm1YY6BkESa6YZZnQoJUs,278109 +chardet/langportuguesemodel.py,sha256=14SmXngDcCs55Szi-xINTMAVcFeMOvIsqEdeEnYRMYQ,367167 +chardet/langromanianmodel.py,sha256=Bl68dfQRTmUb1noQXucrg-GlFxhRTHbVKLyD2PoE7Go,226575 +chardet/langrussianmodel.py,sha256=8GlMBo2a8EkisgleEE__6SugkFmdc27POrl22NatYEs,263454 +chardet/langscottishgaelicmodel.py,sha256=16wt6DG4RJnQ3KP5MlO2OKv9MqQdC6vROW1r5Ylt3I8,272104 +chardet/langserbianmodel.py,sha256=xXHFU7MRNoKedEGwhD7jfZnsZI9Y0MNXKo9JsEW06mc,226182 +chardet/langslovakmodel.py,sha256=KmD2wza5Ma_zlKYpM57vS4mUDVpuUktzENUdmSdwXfk,400059 +chardet/langslovenemodel.py,sha256=xbmWZRcsGc6OOxMiiYW4eBgzmoxaOVbqknm1AdonpTw,203123 +chardet/langspanishmodel.py,sha256=a0-KbO5010FSOrXDI2KR_LNiuYhAhcpaZa7_2H1sF0E,288508 +chardet/langswedishmodel.py,sha256=IZ7aHEfo3q0XQOwSHef_kORw2vquAKhYSr_JcDlKr7k,239976 +chardet/langtajikmodel.py,sha256=XsdKlSZWBu_-7OfRQdwxi5Vcp1qpLJ7Wyi3tyDm-55w,248857 +chardet/langthaimodel.py,sha256=fNdy4fqF2fLmAJAaY5seGfQFictcGYDQKs1vQ7kXPdY,404730 +chardet/langturkishmodel.py,sha256=RmWBF4_yiqsHfCz7R_U5Y-fNwXrProoFMGIoxvxbAk0,288701 +chardet/language_model_notes.md,sha256=BcClrV_llpehvCRXrPdU1p8e7Zv5uNP8b2R7rGkUL-g,3311 +chardet/langukrainianmodel.py,sha256=Jkq7D5c2AHgLPAdWQImSLDJfTC2wR0bp9uhamiWIvlY,287188 +chardet/langvietnamesemodel.py,sha256=9fvINcY-6KbncWmg8Lh4jTrx7zUqHryE9-q4J1l_feg,200475 +chardet/langwelshmodel.py,sha256=02OIFEVVOVI2WWnubGgVI4sMiJTPiBPf4yT7Dy6OFn8,525698 +chardet/mbcharsetprober.py,sha256=v0706BWeu3O_5deqVjZLyZckr2q_XOW_lF4DInES4NU,3764 +chardet/mbcsgroupprober.py,sha256=QMbV4B7w9BJ0rpDOK-FYsf5dmhmHGy1CVjjIdGq2BIg,2292 +chardet/mbcssm.py,sha256=jSblpWW4j0kwI8UhZsXe7_fh3GF141nG2ZksskwLwQM,28522 +chardet/metadata/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +chardet/metadata/__pycache__/__init__.cpython-310.pyc,, +chardet/metadata/__pycache__/charsets.cpython-310.pyc,, +chardet/metadata/__pycache__/languages.cpython-310.pyc,, +chardet/metadata/charsets.py,sha256=ZSt-pzTC0OlssYqNwVLnWKMFj867NhWvlkCKA0Cgvcw,15915 +chardet/metadata/languages.py,sha256=TKx7qPjXFdM_79A5BODsrFf0PgTvTAhfrXBSQdYb3-k,35237 +chardet/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +chardet/resultdict.py,sha256=C4dQ_Dlw2A-Sj-vvy3BlmRBPefkWjFLRCSgUBcrmqgk,148 +chardet/sbcharsetprober.py,sha256=ubj_bogoTDm9wN0lv-VkI-9jFsUteJTfTr4n9RfMBi8,7842 +chardet/sbcsgroupprober.py,sha256=sa0ZAtDPh_5sNmLaVM9stlFUckekhmok4hAgLLHUfyM,38107 +chardet/sjisprober.py,sha256=r7GU3r_Jq_wmrzLAOd5HdfLEhl2uanBev3wEQuF_5vs,3941 +chardet/universaldetector.py,sha256=hJo4RfbrqEjlF7Z9Z8qwnnsdENIwUZ6Xwhg3_kWnxeA,24145 +chardet/utf1632prober.py,sha256=Np53ZVoKjtss6gZgvrigq9biRUUp4dNNhWZCqt2ogPw,9414 +chardet/utf8prober.py,sha256=SoFzQgqniOVJLmbcnWr9au9b-0cp8N-yg_p-Ac5ZXb0,2746 +chardet/version.py,sha256=opZrj3C3i89QMkc5QGBeUietp3VU0bYJ6SSSEHuDJwY,250 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/chardet-6.0.0.post1.dist-info/WHEEL b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/chardet-6.0.0.post1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..ae8ec1bdaa94d726ceb907542d76cbd5d38cafcd --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/chardet-6.0.0.post1.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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/chardet-6.0.0.post1.dist-info/entry_points.txt b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/chardet-6.0.0.post1.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..c36a5e3ee479856d913cae1521b4bd2122587325 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/chardet-6.0.0.post1.dist-info/entry_points.txt @@ -0,0 +1,2 @@ +[console_scripts] +chardetect = chardet.cli.chardetect:main diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cryptography/__about__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cryptography/__about__.py new file mode 100644 index 0000000000000000000000000000000000000000..c81901c0ab9a8d07842000edfb07b9857ee78b1d --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cryptography/__about__.py @@ -0,0 +1,17 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +__all__ = [ + "__author__", + "__copyright__", + "__version__", +] + +__version__ = "48.0.0" + + +__author__ = "The Python Cryptographic Authority and individual contributors" +__copyright__ = f"Copyright 2013-2026 {__author__}" diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cryptography/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cryptography/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d374f752dfd53c6f9a12c69309fdcb6eee765251 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cryptography/__init__.py @@ -0,0 +1,13 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography.__about__ import __author__, __copyright__, __version__ + +__all__ = [ + "__author__", + "__copyright__", + "__version__", +] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cryptography/exceptions.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cryptography/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..fe125ea9a763ad731ba99e4761d6623e1d2c639c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cryptography/exceptions.py @@ -0,0 +1,52 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import typing + +from cryptography.hazmat.bindings._rust import exceptions as rust_exceptions + +if typing.TYPE_CHECKING: + from cryptography.hazmat.bindings._rust import openssl as rust_openssl + +_Reasons = rust_exceptions._Reasons + + +class UnsupportedAlgorithm(Exception): + def __init__(self, message: str, reason: _Reasons | None = None) -> None: + super().__init__(message) + self._reason = reason + + +class AlreadyFinalized(Exception): + pass + + +class AlreadyUpdated(Exception): + pass + + +class NotYetFinalized(Exception): + pass + + +class InvalidTag(Exception): + pass + + +class InvalidSignature(Exception): + pass + + +class InternalError(Exception): + def __init__( + self, msg: str, err_code: list[rust_openssl.OpenSSLError] + ) -> None: + super().__init__(msg) + self.err_code = err_code + + +class InvalidKey(Exception): + pass diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cryptography/fernet.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cryptography/fernet.py new file mode 100644 index 0000000000000000000000000000000000000000..c6744ae384e3497d2855b32398f8ee59b972f371 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cryptography/fernet.py @@ -0,0 +1,224 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import base64 +import binascii +import os +import time +import typing +from collections.abc import Iterable + +from cryptography import utils +from cryptography.exceptions import InvalidSignature +from cryptography.hazmat.primitives import hashes, padding +from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes +from cryptography.hazmat.primitives.hmac import HMAC + + +class InvalidToken(Exception): + pass + + +_MAX_CLOCK_SKEW = 60 + + +class Fernet: + def __init__( + self, + key: bytes | str, + backend: typing.Any = None, + ) -> None: + try: + key = base64.urlsafe_b64decode(key) + except binascii.Error as exc: + raise ValueError( + "Fernet key must be 32 url-safe base64-encoded bytes." + ) from exc + if len(key) != 32: + raise ValueError( + "Fernet key must be 32 url-safe base64-encoded bytes." + ) + + self._signing_key = key[:16] + self._encryption_key = key[16:] + + @classmethod + def generate_key(cls) -> bytes: + return base64.urlsafe_b64encode(os.urandom(32)) + + def encrypt(self, data: bytes) -> bytes: + return self.encrypt_at_time(data, int(time.time())) + + def encrypt_at_time(self, data: bytes, current_time: int) -> bytes: + iv = os.urandom(16) + return self._encrypt_from_parts(data, current_time, iv) + + def _encrypt_from_parts( + self, data: bytes, current_time: int, iv: bytes + ) -> bytes: + utils._check_bytes("data", data) + + padder = padding.PKCS7(algorithms.AES.block_size).padder() + padded_data = padder.update(data) + padder.finalize() + encryptor = Cipher( + algorithms.AES(self._encryption_key), + modes.CBC(iv), + ).encryptor() + ciphertext = encryptor.update(padded_data) + encryptor.finalize() + + basic_parts = ( + b"\x80" + + current_time.to_bytes(length=8, byteorder="big") + + iv + + ciphertext + ) + + h = HMAC(self._signing_key, hashes.SHA256()) + h.update(basic_parts) + hmac = h.finalize() + return base64.urlsafe_b64encode(basic_parts + hmac) + + def decrypt(self, token: bytes | str, ttl: int | None = None) -> bytes: + timestamp, data = Fernet._get_unverified_token_data(token) + if ttl is None: + time_info = None + else: + time_info = (ttl, int(time.time())) + return self._decrypt_data(data, timestamp, time_info) + + def decrypt_at_time( + self, token: bytes | str, ttl: int, current_time: int + ) -> bytes: + if ttl is None: + raise ValueError( + "decrypt_at_time() can only be used with a non-None ttl" + ) + timestamp, data = Fernet._get_unverified_token_data(token) + return self._decrypt_data(data, timestamp, (ttl, current_time)) + + def extract_timestamp(self, token: bytes | str) -> int: + timestamp, data = Fernet._get_unverified_token_data(token) + # Verify the token was not tampered with. + self._verify_signature(data) + return timestamp + + @staticmethod + def _get_unverified_token_data(token: bytes | str) -> tuple[int, bytes]: + if not isinstance(token, (str, bytes)): + raise TypeError("token must be bytes or str") + + try: + data = base64.urlsafe_b64decode(token) + except (TypeError, binascii.Error): + raise InvalidToken + + if not data or data[0] != 0x80: + raise InvalidToken + + if len(data) < 9: + raise InvalidToken + + timestamp = int.from_bytes(data[1:9], byteorder="big") + return timestamp, data + + def _verify_signature(self, data: bytes) -> None: + h = HMAC(self._signing_key, hashes.SHA256()) + h.update(data[:-32]) + try: + h.verify(data[-32:]) + except InvalidSignature: + raise InvalidToken + + def _decrypt_data( + self, + data: bytes, + timestamp: int, + time_info: tuple[int, int] | None, + ) -> bytes: + if time_info is not None: + ttl, current_time = time_info + if timestamp + ttl < current_time: + raise InvalidToken + + if current_time + _MAX_CLOCK_SKEW < timestamp: + raise InvalidToken + + self._verify_signature(data) + + iv = data[9:25] + ciphertext = data[25:-32] + decryptor = Cipher( + algorithms.AES(self._encryption_key), modes.CBC(iv) + ).decryptor() + plaintext_padded = decryptor.update(ciphertext) + try: + plaintext_padded += decryptor.finalize() + except ValueError: + raise InvalidToken + unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder() + + unpadded = unpadder.update(plaintext_padded) + try: + unpadded += unpadder.finalize() + except ValueError: + raise InvalidToken + return unpadded + + +class MultiFernet: + def __init__(self, fernets: Iterable[Fernet]): + fernets = list(fernets) + if not fernets: + raise ValueError( + "MultiFernet requires at least one Fernet instance" + ) + self._fernets = fernets + + def encrypt(self, msg: bytes) -> bytes: + return self.encrypt_at_time(msg, int(time.time())) + + def encrypt_at_time(self, msg: bytes, current_time: int) -> bytes: + return self._fernets[0].encrypt_at_time(msg, current_time) + + def rotate(self, msg: bytes | str) -> bytes: + timestamp, data = Fernet._get_unverified_token_data(msg) + for f in self._fernets: + try: + p = f._decrypt_data(data, timestamp, None) + break + except InvalidToken: + pass + else: + raise InvalidToken + + iv = os.urandom(16) + return self._fernets[0]._encrypt_from_parts(p, timestamp, iv) + + def decrypt(self, msg: bytes | str, ttl: int | None = None) -> bytes: + for f in self._fernets: + try: + return f.decrypt(msg, ttl) + except InvalidToken: + pass + raise InvalidToken + + def decrypt_at_time( + self, msg: bytes | str, ttl: int, current_time: int + ) -> bytes: + for f in self._fernets: + try: + return f.decrypt_at_time(msg, ttl, current_time) + except InvalidToken: + pass + raise InvalidToken + + def extract_timestamp(self, msg: bytes | str) -> int: + for f in self._fernets: + try: + return f.extract_timestamp(msg) + except InvalidToken: + pass + raise InvalidToken diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cryptography/py.typed b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cryptography/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cryptography/utils.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cryptography/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9cfc9927362668d654a09bae232c27811ca44842 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cryptography/utils.py @@ -0,0 +1,135 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import enum +import sys +import types +import typing +import warnings +from collections.abc import Callable, Sequence + + +# We use a UserWarning subclass, instead of DeprecationWarning, because CPython +# decided deprecation warnings should be invisible by default. +class CryptographyDeprecationWarning(UserWarning): + pass + + +# Several APIs were deprecated with no specific end-of-life date because of the +# ubiquity of their use. They should not be removed until we agree on when that +# cycle ends. +DeprecatedIn36 = CryptographyDeprecationWarning +DeprecatedIn40 = CryptographyDeprecationWarning +DeprecatedIn41 = CryptographyDeprecationWarning +DeprecatedIn42 = CryptographyDeprecationWarning +DeprecatedIn43 = CryptographyDeprecationWarning +DeprecatedIn47 = CryptographyDeprecationWarning + + +# If you're wondering why we don't use `Buffer`, it's because `Buffer` would +# be more accurately named: Bufferable. It means something which has an +# `__buffer__`. Which means you can't actually treat the result as a buffer +# (and do things like take a `len()`). +Buffer = typing.Union[bytes, bytearray, memoryview] + + +def _check_bytes(name: str, value: bytes) -> None: + if not isinstance(value, bytes): + raise TypeError(f"{name} must be bytes") + + +def _check_byteslike(name: str, value: Buffer) -> None: + try: + memoryview(value) + except TypeError: + raise TypeError(f"{name} must be bytes-like") + + +def int_to_bytes(integer: int, length: int | None = None) -> bytes: + if length == 0: + raise ValueError("length argument can't be 0") + return integer.to_bytes( + length or (integer.bit_length() + 7) // 8 or 1, "big" + ) + + +class InterfaceNotImplemented(Exception): + pass + + +class _DeprecatedValue: + def __init__(self, value: object, message: str, warning_class): + self.value = value + self.message = message + self.warning_class = warning_class + + +class _ModuleWithDeprecations(types.ModuleType): + def __init__(self, module: types.ModuleType): + super().__init__(module.__name__) + self.__dict__["_module"] = module + + def __getattr__(self, name: str) -> typing.Any: + obj = getattr(self._module, name) + if isinstance(obj, _DeprecatedValue): + warnings.warn(obj.message, obj.warning_class, stacklevel=2) + obj = obj.value + return obj + + def __setattr__(self, attr: str, value: object) -> None: + setattr(self._module, attr, value) + + def __delattr__(self, attr: str) -> None: + obj = getattr(self._module, attr) + if isinstance(obj, _DeprecatedValue): + warnings.warn(obj.message, obj.warning_class, stacklevel=2) + + delattr(self._module, attr) + + def __dir__(self) -> Sequence[str]: + return ["_module", *dir(self._module)] + + +def deprecated( + value: object, + module_name: str, + message: str, + warning_class: type[Warning], + name: str | None = None, +) -> _DeprecatedValue: + module = sys.modules[module_name] + if not isinstance(module, _ModuleWithDeprecations): + sys.modules[module_name] = module = _ModuleWithDeprecations(module) + dv = _DeprecatedValue(value, message, warning_class) + # Maintain backwards compatibility with `name is None` for pyOpenSSL. + if name is not None: + setattr(module, name, dv) + return dv + + +def cached_property(func: Callable) -> property: + cached_name = f"_cached_{func}" + sentinel = object() + + def inner(instance: object): + cache = getattr(instance, cached_name, sentinel) + if cache is not sentinel: + return cache + result = func(instance) + setattr(instance, cached_name, result) + return result + + return property(inner) + + +# Python 3.10 changed representation of enums. We use well-defined object +# representation and string representation from Python 3.9. +class Enum(enum.Enum): + def __repr__(self) -> str: + return f"<{self.__class__.__name__}.{self._name_}: {self._value_!r}>" + + def __str__(self) -> str: + return f"{self.__class__.__name__}.{self._name_}" diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/emoji/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/emoji/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cfa04c32bacfd0a33fd7518ccb475bfd15dd7e22 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/emoji/__init__.py @@ -0,0 +1,61 @@ +__all__ = [ + # emoji.core + 'emojize', + 'demojize', + 'analyze', + 'config', + 'emoji_list', + 'distinct_emoji_list', + 'emoji_count', + 'replace_emoji', + 'is_emoji', + 'purely_emoji', + 'version', + 'Token', + 'EmojiMatch', + 'EmojiMatchZWJ', + 'EmojiMatchZWJNonRGI', + # emoji.unicode_codes + 'EMOJI_DATA', + 'STATUS', + 'LANGUAGES', +] + +__version__ = '2.15.0' +__author__ = 'Taehoon Kim, Kevin Wurster' +__email__ = 'carpedm20@gmail.com' +# and wursterk@gmail.com, tahir.jalilov@gmail.com +__source__ = 'https://github.com/carpedm20/emoji/' +__license__ = """ +New BSD License + +Copyright (c) 2014-2025, Taehoon Kim, Kevin Wurster +All rights reserved. + +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. + +* The names of its contributors may not 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 HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +""" + +from emoji.core import * +from emoji.unicode_codes import * diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/emoji/core.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/emoji/core.py new file mode 100644 index 0000000000000000000000000000000000000000..c317a18bf8b8c82a2357a816a36051268fc66518 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/emoji/core.py @@ -0,0 +1,445 @@ +""" +emoji.core +~~~~~~~~~~ + +Core components for emoji. + +""" + +import re +import unicodedata +from typing import Any, Callable, Dict, Iterator, List, Literal, Match, Optional, Tuple, TypedDict, Union + +from emoji import unicode_codes +from emoji.tokenizer import ( + Token, + EmojiMatch, + EmojiMatchZWJ, + EmojiMatchZWJNonRGI, + tokenize, + filter_tokens, +) + +__all__ = [ + 'emojize', + 'demojize', + 'analyze', + 'config', + 'emoji_list', + 'distinct_emoji_list', + 'emoji_count', + 'replace_emoji', + 'is_emoji', + 'purely_emoji', + 'version', + 'Token', + 'EmojiMatch', + 'EmojiMatchZWJ', + 'EmojiMatchZWJNonRGI', +] + +_DEFAULT_DELIMITER = ':' +# In Arabic language, the unicode character "\u0655" should be kept so we add it to the pattern below +_EMOJI_NAME_PATTERN = '\\w\\-&.’”“()!#*+,/«»\u0300\u0301\u0302\u0303\u0306\u0308\u030a\u0327\u064b\u064e\u064f\u0650\u0653\u0654\u3099\u30fb\u309a\u0655' + + +class _EmojiListReturn(TypedDict): + emoji: str + match_start: int + match_end: int + + +class config: + """Module-wide configuration""" + + demojize_keep_zwj = True + """Change the behavior of :func:`emoji.demojize()` regarding + zero-width-joiners (ZWJ/``\\u200D``) in emoji that are not + "recommended for general interchange" (non-RGI). + It has no effect on RGI emoji. + + For example this family emoji with different skin tones "👨‍👩🏿‍👧🏻‍👦🏾" contains four + person emoji that are joined together by three ZWJ characters: + ``👨\\u200D👩🏿\\u200D👧🏻\\u200D👦🏾`` + + If ``True``, the zero-width-joiners will be kept and :func:`emoji.emojize()` can + reverse the :func:`emoji.demojize()` operation: + ``emoji.emojize(emoji.demojize(s)) == s`` + + The example emoji would be converted to + ``:man:\\u200d:woman_dark_skin_tone:\\u200d:girl_light_skin_tone:\\u200d:boy_medium-dark_skin_tone:`` + + If ``False``, the zero-width-joiners will be removed and :func:`emoji.emojize()` + can only reverse the individual emoji: ``emoji.emojize(emoji.demojize(s)) != s`` + + The example emoji would be converted to + ``:man::woman_dark_skin_tone::girl_light_skin_tone::boy_medium-dark_skin_tone:`` + """ + + replace_emoji_keep_zwj = False + """Change the behavior of :func:`emoji.replace_emoji()` regarding + zero-width-joiners (ZWJ/``\\u200D``) in emoji that are not + "recommended for general interchange" (non-RGI). + It has no effect on RGI emoji. + + See :attr:`config.demojize_keep_zwj` for more information. + """ + + @staticmethod + def load_language(language: Union[List[str], str, None] = None): + """Load one or multiple languages into memory. + If no language is specified, all languages will be loaded. + + This makes language data accessible in the :data:`EMOJI_DATA` dict. + For example to access a French emoji name, first load French with + + ``emoji.config.load_language('fr')`` + + and then access it with + + ``emoji.EMOJI_DATA['🏄']['fr']`` + + Available languages are listed in :data:`LANGUAGES`""" + + languages = ( + [language] + if isinstance(language, str) + else language + if language + else unicode_codes.LANGUAGES + ) + + for lang in languages: + unicode_codes.load_from_json(lang) + + +def emojize( + string: str, + delimiters: Tuple[str, str] = (_DEFAULT_DELIMITER, _DEFAULT_DELIMITER), + variant: Optional[Literal['text_type', 'emoji_type']] = None, + language: str = 'en', + version: Optional[float] = None, + handle_version: Optional[Union[str, Callable[[str, Dict[str, str]], str]]] = None, +) -> str: + """ + Replace emoji names in a string with Unicode codes. + >>> import emoji + >>> print(emoji.emojize("Python is fun :thumbsup:", language='alias')) + Python is fun 👍 + >>> print(emoji.emojize("Python is fun :thumbs_up:")) + Python is fun 👍 + >>> print(emoji.emojize("Python is fun {thumbs_up}", delimiters = ("{", "}"))) + Python is fun 👍 + >>> print(emoji.emojize("Python is fun :red_heart:", variant="text_type")) + Python is fun ❤ + >>> print(emoji.emojize("Python is fun :red_heart:", variant="emoji_type")) + Python is fun ❤️ # red heart, not black heart + + :param string: String contains emoji names. + :param delimiters: (optional) Use delimiters other than _DEFAULT_DELIMITER. Each delimiter + should contain at least one character that is not part of a-zA-Z0-9 and ``_-&.()!?#*+,``. + See ``emoji.core._EMOJI_NAME_PATTERN`` for the regular expression of unsafe characters. + :param variant: (optional) Choose variation selector between "base"(None), VS-15 ("text_type") and VS-16 ("emoji_type") + :param language: Choose language of emoji name: language code 'es', 'de', etc. or 'alias' + to use English aliases + :param version: (optional) Max version. If set to an Emoji Version, + all emoji above this version will be ignored. + :param handle_version: (optional) Replace the emoji above ``version`` + instead of ignoring it. handle_version can be either a string or a + callable; If it is a callable, it's passed the Unicode emoji and the + data dict from :data:`EMOJI_DATA` and must return a replacement string + to be used:: + + handle_version('\\U0001F6EB', { + 'en' : ':airplane_departure:', + 'status' : fully_qualified, + 'E' : 1, + 'alias' : [':flight_departure:'], + 'de': ':abflug:', + 'es': ':avión_despegando:', + ... + }) + + :raises ValueError: if ``variant`` is neither None, 'text_type' or 'emoji_type' + + """ + + unicode_codes.load_from_json(language) + + pattern = re.compile( + '(%s[%s]+%s)' + % (re.escape(delimiters[0]), _EMOJI_NAME_PATTERN, re.escape(delimiters[1])) + ) + + def replace(match: Match[str]) -> str: + name = match.group(1)[len(delimiters[0]) : -len(delimiters[1])] + emj = unicode_codes.get_emoji_by_name( + _DEFAULT_DELIMITER + + unicodedata.normalize('NFKC', name) + + _DEFAULT_DELIMITER, + language, + ) + + if emj is None: + return match.group(1) + + if version is not None and unicode_codes.EMOJI_DATA[emj]['E'] > version: + if callable(handle_version): + emj_data = unicode_codes.EMOJI_DATA[emj].copy() + emj_data['match_start'] = match.start() + emj_data['match_end'] = match.end() + return handle_version(emj, emj_data) + + elif handle_version is not None: + return str(handle_version) + else: + return '' + + if variant is None or 'variant' not in unicode_codes.EMOJI_DATA[emj]: + return emj + + if emj[-1] == '\ufe0e' or emj[-1] == '\ufe0f': + # Remove an existing variant + emj = emj[0:-1] + if variant == 'text_type': + return emj + '\ufe0e' + elif variant == 'emoji_type': + return emj + '\ufe0f' + else: + raise ValueError( + "Parameter 'variant' must be either None, 'text_type' or 'emoji_type'" + ) + + return pattern.sub(replace, string) + + +def analyze( + string: str, non_emoji: bool = False, join_emoji: bool = True +) -> Iterator[Token]: + """ + Find unicode emoji in a string. Yield each emoji as a named tuple + :class:`Token` ``(chars, EmojiMatch)`` or :class:`Token` ``(chars, EmojiMatchZWJNonRGI)``. + If ``non_emoji`` is True, also yield all other characters as + :class:`Token` ``(char, char)`` . + + :param string: String to analyze + :param non_emoji: If True also yield all non-emoji characters as Token(char, char) + :param join_emoji: If True, multiple EmojiMatch are merged into a single + EmojiMatchZWJNonRGI if they are separated only by a ZWJ. + """ + + return filter_tokens( + tokenize(string, keep_zwj=True), emoji_only=not non_emoji, join_emoji=join_emoji + ) + + +def demojize( + string: str, + delimiters: Tuple[str, str] = (_DEFAULT_DELIMITER, _DEFAULT_DELIMITER), + language: str = 'en', + version: Optional[float] = None, + handle_version: Optional[Union[str, Callable[[str, Dict[str, str]], str]]] = None, +) -> str: + """ + Replace Unicode emoji in a string with emoji shortcodes. Useful for storage. + >>> import emoji + >>> print(emoji.emojize("Python is fun :thumbs_up:")) + Python is fun 👍 + >>> print(emoji.demojize("Python is fun 👍")) + Python is fun :thumbs_up: + >>> print(emoji.demojize("icode is tricky 😯", delimiters=("__", "__"))) + Unicode is tricky __hushed_face__ + + :param string: String contains Unicode characters. MUST BE UNICODE. + :param delimiters: (optional) User delimiters other than ``_DEFAULT_DELIMITER`` + :param language: Choose language of emoji name: language code 'es', 'de', etc. or 'alias' + to use English aliases + :param version: (optional) Max version. If set to an Emoji Version, + all emoji above this version will be removed. + :param handle_version: (optional) Replace the emoji above ``version`` + instead of removing it. handle_version can be either a string or a + callable ``handle_version(emj: str, data: dict) -> str``; If it is + a callable, it's passed the Unicode emoji and the data dict from + :data:`EMOJI_DATA` and must return a replacement string to be used. + The passed data is in the form of:: + + handle_version('\\U0001F6EB', { + 'en' : ':airplane_departure:', + 'status' : fully_qualified, + 'E' : 1, + 'alias' : [':flight_departure:'], + 'de': ':abflug:', + 'es': ':avión_despegando:', + ... + }) + + """ + + if language == 'alias': + language = 'en' + _use_aliases = True + else: + _use_aliases = False + + unicode_codes.load_from_json(language) + + def handle(emoji_match: EmojiMatch) -> str: + assert emoji_match.data is not None + if version is not None and emoji_match.data['E'] > version: + if callable(handle_version): + return handle_version(emoji_match.emoji, emoji_match.data_copy()) + elif handle_version is not None: + return handle_version + else: + return '' + elif language in emoji_match.data: + if _use_aliases and 'alias' in emoji_match.data: + return ( + delimiters[0] + emoji_match.data['alias'][0][1:-1] + delimiters[1] + ) + else: + return delimiters[0] + emoji_match.data[language][1:-1] + delimiters[1] + else: + # The emoji exists, but it is not translated, so we keep the emoji + return emoji_match.emoji + + matches = tokenize(string, keep_zwj=config.demojize_keep_zwj) + return ''.join( + str(handle(token.value)) if isinstance(token.value, EmojiMatch) else token.value + for token in matches + ) + + +def replace_emoji( + string: str, + replace: Union[str, Callable[[str, Dict[str, str]], str]] = '', + version: float = -1, +) -> str: + """ + Replace Unicode emoji in a customizable string. + + :param string: String contains Unicode characters. MUST BE UNICODE. + :param replace: (optional) replace can be either a string or a callable; + If it is a callable, it's passed the Unicode emoji and the data dict from + :data:`EMOJI_DATA` and must return a replacement string to be used. + replace(str, dict) -> str + :param version: (optional) Max version. If set to an Emoji Version, + only emoji above this version will be replaced. + """ + + def handle(emoji_match: EmojiMatch) -> str: + if version > -1: + assert emoji_match.data is not None + if emoji_match.data['E'] > version: + if callable(replace): + return replace(emoji_match.emoji, emoji_match.data_copy()) + else: + return str(replace) + elif callable(replace): + return replace(emoji_match.emoji, emoji_match.data_copy()) + elif replace is not None: # type: ignore + return replace + return emoji_match.emoji + + matches = tokenize(string, keep_zwj=config.replace_emoji_keep_zwj) + if config.replace_emoji_keep_zwj: + matches = filter_tokens(matches, emoji_only=False, join_emoji=True) + return ''.join( + str(handle(m.value)) if isinstance(m.value, EmojiMatch) else m.value + for m in matches + ) + + +def emoji_list(string: str) -> List[_EmojiListReturn]: + """ + Returns the location and emoji in list of dict format. + >>> emoji.emoji_list("Hi, I am fine. 😁") + [{'match_start': 15, 'match_end': 16, 'emoji': '😁'}] + """ + + return [ + { + 'match_start': m.value.start, + 'match_end': m.value.end, + 'emoji': m.value.emoji, + } + for m in tokenize(string, keep_zwj=False) + if isinstance(m.value, EmojiMatch) + ] + + +def distinct_emoji_list(string: str) -> List[str]: + """Returns distinct list of emojis from the string.""" + distinct_list = list({e['emoji'] for e in emoji_list(string)}) + return distinct_list + + +def emoji_count(string: str, unique: bool = False) -> int: + """ + Returns the count of emojis in a string. + + :param unique: (optional) True if count only unique emojis + """ + if unique: + return len(distinct_emoji_list(string)) + return len(emoji_list(string)) + + +def is_emoji(string: str) -> bool: + """ + Returns True if the string is a single emoji, and it is "recommended for + general interchange" by Unicode.org. + """ + return string in unicode_codes.EMOJI_DATA + + +def purely_emoji(string: str) -> bool: + """ + Returns True if the string contains only emojis. + This might not imply that `is_emoji` for all the characters, for example, + if the string contains variation selectors. + """ + return all(isinstance(m.value, EmojiMatch) for m in analyze(string, non_emoji=True)) + + +def version(string: str) -> float: + """ + Returns the Emoji Version of the emoji. + + See https://www.unicode.org/reports/tr51/#Versioning for more information. + >>> emoji.version("😁") + 0.6 + >>> emoji.version(":butterfly:") + 3 + + :param string: An emoji or a text containing an emoji + :raises ValueError: if ``string`` does not contain an emoji + """ + # Try dictionary lookup + if string in unicode_codes.EMOJI_DATA: + return unicode_codes.EMOJI_DATA[string]['E'] + + # Try name lookup + emj_code = unicode_codes.get_emoji_by_name(string, 'en') + if emj_code and emj_code in unicode_codes.EMOJI_DATA: + return unicode_codes.EMOJI_DATA[emj_code]['E'] + + # Try to find first emoji in string + version: List[float] = [] + + def f(e: str, emoji_data: Dict[str, Any]) -> str: + version.append(emoji_data['E']) + return '' + + replace_emoji(string, replace=f, version=-1) + if version: + return version[0] + emojize(string, language='alias', version=-1, handle_version=f) + if version: + return version[0] + for lang_code in unicode_codes.LANGUAGES: + emojize(string, language=lang_code, version=-1, handle_version=f) + if version: + return version[0] + + raise ValueError('No emoji found in string') diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/emoji/py.typed b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/emoji/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/emoji/tokenizer.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/emoji/tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..2001251118980d7c0c991bff3e8dbc4287e7e762 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/emoji/tokenizer.py @@ -0,0 +1,376 @@ +""" +emoji.tokenizer +~~~~~~~~~~~~~~~ + +Components for detecting and tokenizing emoji in strings. + +""" + +from typing import List, NamedTuple, Dict, Union, Iterator, Any +from emoji import unicode_codes + + +__all__ = [ + 'EmojiMatch', + 'EmojiMatchZWJ', + 'EmojiMatchZWJNonRGI', + 'Token', + 'tokenize', + 'filter_tokens', +] + +_ZWJ = '\u200d' +_SEARCH_TREE: Dict[str, Any] = {} + + +class EmojiMatch: + """ + Represents a match of a "recommended for general interchange" (RGI) + emoji in a string. + """ + + __slots__ = ('emoji', 'start', 'end', 'data') + + def __init__( + self, emoji: str, start: int, end: int, data: Union[Dict[str, Any], None] + ): + self.emoji = emoji + """The emoji substring""" + + self.start = start + """The start index of the match in the string""" + + self.end = end + """The end index of the match in the string""" + + self.data = data + """The entry from :data:`EMOJI_DATA` for this emoji or ``None`` if the emoji is non-RGI""" + + def data_copy(self) -> Dict[str, Any]: + """ + Returns a copy of the data from :data:`EMOJI_DATA` for this match + with the additional keys ``match_start`` and ``match_end``. + """ + if self.data: + emj_data = self.data.copy() + emj_data['match_start'] = self.start + emj_data['match_end'] = self.end + return emj_data + else: + return {'match_start': self.start, 'match_end': self.end} + + def is_zwj(self) -> bool: + """ + Checks if this is a ZWJ-emoji. + + :returns: True if this is a ZWJ-emoji, False otherwise + """ + + return _ZWJ in self.emoji + + def split(self) -> Union['EmojiMatchZWJ', 'EmojiMatch']: + """ + Splits a ZWJ-emoji into its constituents. + + :returns: An :class:`EmojiMatchZWJ` containing the "sub-emoji" if this is a ZWJ-emoji, otherwise self + """ + + if self.is_zwj(): + return EmojiMatchZWJ(self) + else: + return self + + def __repr__(self) -> str: + return f'{self.__class__.__name__}({self.emoji}, {self.start}:{self.end})' + + +class EmojiMatchZWJ(EmojiMatch): + """ + Represents a match of multiple emoji in a string that were joined by + zero-width-joiners (ZWJ/``\\u200D``).""" + + __slots__ = ('emojis',) + + def __init__(self, match: EmojiMatch): + super().__init__(match.emoji, match.start, match.end, match.data) + + self.emojis: List[EmojiMatch] = [] + """List of sub emoji as EmojiMatch objects""" + + i = match.start + for e in match.emoji.split(_ZWJ): + m = EmojiMatch(e, i, i + len(e), unicode_codes.EMOJI_DATA.get(e, None)) + self.emojis.append(m) + i += len(e) + 1 + + def join(self) -> str: + """ + Joins a ZWJ-emoji into a string + """ + + return _ZWJ.join(e.emoji for e in self.emojis) + + def is_zwj(self) -> bool: + return True + + def split(self) -> 'EmojiMatchZWJ': + return self + + def __repr__(self) -> str: + return f'{self.__class__.__name__}({self.join()}, {self.start}:{self.end})' + + +class EmojiMatchZWJNonRGI(EmojiMatchZWJ): + """ + Represents a match of multiple emoji in a string that were joined by + zero-width-joiners (ZWJ/``\\u200D``). This class is only used for emoji + that are not "recommended for general interchange" (non-RGI) by Unicode.org. + The data property of this class is always None. + """ + + def __init__(self, first_emoji_match: EmojiMatch, second_emoji_match: EmojiMatch): + self.emojis = [first_emoji_match, second_emoji_match] + """List of sub emoji as EmojiMatch objects""" + + self._update() + + def _update(self): + self.emoji = _ZWJ.join(e.emoji for e in self.emojis) + self.start = self.emojis[0].start + self.end = self.emojis[-1].end + self.data = None + + def _add(self, next_emoji_match: EmojiMatch): + self.emojis.append(next_emoji_match) + self._update() + + +class Token(NamedTuple): + """ + A named tuple containing the matched string and its :class:`EmojiMatch` object if it is an emoji + or a single character that is not a unicode emoji. + """ + + chars: str + value: Union[str, EmojiMatch] + + +def tokenize(string: str, keep_zwj: bool) -> Iterator[Token]: + """ + Finds unicode emoji in a string. Yields all normal characters as a named + tuple :class:`Token` ``(char, char)`` and all emoji as :class:`Token` ``(chars, EmojiMatch)``. + + :param string: String contains unicode characters. MUST BE UNICODE. + :param keep_zwj: Should ZWJ-characters (``\\u200D``) that join non-RGI emoji be + skipped or should be yielded as normal characters + :return: An iterable of tuples :class:`Token` ``(char, char)`` or :class:`Token` ``(chars, EmojiMatch)`` + """ + + tree = get_search_tree() + EMOJI_DATA = unicode_codes.EMOJI_DATA + # result: [ Token(oldsubstring0, EmojiMatch), Token(char1, char1), ... ] + result: List[Token] = [] + i = 0 + length = len(string) + ignore: List[ + int + ] = [] # index of chars in string that are skipped, i.e. the ZWJ-char in non-RGI-ZWJ-sequences + while i < length: + consumed = False + char = string[i] + if i in ignore: + i += 1 + if char == _ZWJ and keep_zwj: + result.append(Token(char, char)) + continue + + elif char in tree: + j = i + 1 + sub_tree = tree[char] + while j < length and string[j] in sub_tree: + if j in ignore: + break + sub_tree = sub_tree[string[j]] + j += 1 + if 'data' in sub_tree: + emj_data = sub_tree['data'] + code_points = string[i:j] + + # We cannot yield the result here, we need to defer + # the call until we are sure that the emoji is finished + # i.e. we're not inside an ongoing ZWJ-sequence + match_obj = EmojiMatch(code_points, i, j, emj_data) + + i = j - 1 + consumed = True + result.append(Token(code_points, match_obj)) + + elif ( + char == _ZWJ + and result + and result[-1].chars in EMOJI_DATA + and i > 0 + and string[i - 1] in tree + ): + # the current char is ZWJ and the last match was an emoji + ignore.append(i) + if ( + EMOJI_DATA[result[-1].chars]['status'] + == unicode_codes.STATUS['component'] + ): + # last match was a component, it could be ZWJ+EMOJI+COMPONENT + # or ZWJ+COMPONENT + i = i - sum(len(t.chars) for t in result[-2:]) + if string[i] == _ZWJ: + # It's ZWJ+COMPONENT, move one back + i += 1 + del result[-1] + else: + # It's ZWJ+EMOJI+COMPONENT, move two back + del result[-2:] + else: + # last match result[-1] was a normal emoji, move cursor + # before the emoji + i = i - len(result[-1].chars) + del result[-1] + continue + + elif result: + yield from result + result = [] + + if not consumed and char != '\ufe0e' and char != '\ufe0f': + result.append(Token(char, char)) + i += 1 + + yield from result + + +def filter_tokens( + matches: Iterator[Token], emoji_only: bool, join_emoji: bool +) -> Iterator[Token]: + """ + Filters the output of `tokenize()` + + :param matches: An iterable of tuples of the form ``(match_str, result)`` + where ``result`` is either an EmojiMatch or a string. + :param emoji_only: If True, only EmojiMatch are returned in the output. + If False all characters are returned + :param join_emoji: If True, multiple EmojiMatch are merged into + a single :class:`EmojiMatchZWJNonRGI` if they are separated only by a ZWJ. + + :return: An iterable of tuples :class:`Token` ``(char, char)``, + :class:`Token` ``(chars, EmojiMatch)`` or :class:`Token` ``(chars, EmojiMatchZWJNonRGI)`` + """ + + if not join_emoji and not emoji_only: + yield from matches + return + + if not join_emoji: + for token in matches: + if token.chars != _ZWJ: + yield token + return + + # Combine multiple EmojiMatch that are separated by ZWJs into + # a single EmojiMatchZWJNonRGI + previous_is_emoji = False + previous_is_zwj = False + pre_previous_is_emoji = False + accumulator: List[Token] = [] + for token in matches: + pre_previous_is_emoji = previous_is_emoji + if previous_is_emoji and token.value == _ZWJ: + previous_is_zwj = True + elif isinstance(token.value, EmojiMatch): + if pre_previous_is_emoji and previous_is_zwj: + if isinstance(accumulator[-1].value, EmojiMatchZWJNonRGI): + accumulator[-1].value._add(token.value) # pyright: ignore [reportPrivateUsage] + accumulator[-1] = Token( + accumulator[-1].chars + _ZWJ + token.chars, + accumulator[-1].value, + ) + else: + prev = accumulator.pop() + assert isinstance(prev.value, EmojiMatch) + accumulator.append( + Token( + prev.chars + _ZWJ + token.chars, + EmojiMatchZWJNonRGI(prev.value, token.value), + ) + ) + else: + accumulator.append(token) + previous_is_emoji = True + previous_is_zwj = False + else: + # Other character, not an emoji + previous_is_emoji = False + previous_is_zwj = False + yield from accumulator + if not emoji_only: + yield token + accumulator = [] + yield from accumulator + + +def get_search_tree() -> Dict[str, Any]: + """ + Generate a search tree for demojize(). + Example of a search tree:: + + EMOJI_DATA = + {'a': {'en': ':Apple:'}, + 'b': {'en': ':Bus:'}, + 'ba': {'en': ':Bat:'}, + 'band': {'en': ':Beatles:'}, + 'bandit': {'en': ':Outlaw:'}, + 'bank': {'en': ':BankOfEngland:'}, + 'bb': {'en': ':BB-gun:'}, + 'c': {'en': ':Car:'}} + + _SEARCH_TREE = + {'a': {'data': {'en': ':Apple:'}}, + 'b': {'a': {'data': {'en': ':Bat:'}, + 'n': {'d': {'data': {'en': ':Beatles:'}, + 'i': {'t': {'data': {'en': ':Outlaw:'}}}}, + 'k': {'data': {'en': ':BankOfEngland:'}}}}, + 'b': {'data': {'en': ':BB-gun:'}}, + 'data': {'en': ':Bus:'}}, + 'c': {'data': {'en': ':Car:'}}} + + _SEARCH_TREE + / | ⧵ + / | ⧵ + a b c + | / | ⧵ | + | / | ⧵ | + :Apple: ba :Bus: bb :Car: + / ⧵ | + / ⧵ | + :Bat: ban :BB-gun: + / ⧵ + / ⧵ + band bank + / ⧵ | + / ⧵ | + bandi :Beatles: :BankOfEngland: + | + bandit + | + :Outlaw: + + + """ + if not _SEARCH_TREE: + for emj in unicode_codes.EMOJI_DATA: + sub_tree = _SEARCH_TREE + lastidx = len(emj) - 1 + for i, char in enumerate(emj): + if char not in sub_tree: + sub_tree[char] = {} + sub_tree = sub_tree[char] + if i == lastidx: + sub_tree['data'] = unicode_codes.EMOJI_DATA[emj] + return _SEARCH_TREE diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/examples/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/examples/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/examples/basic_example.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/examples/basic_example.py new file mode 100644 index 0000000000000000000000000000000000000000..7d6402f67c25ac28f5d0132398e3982d030c86f9 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/examples/basic_example.py @@ -0,0 +1,60 @@ +from time import sleep +import multiprocessing + +import logging +from tqdm_multiprocess.logger import setup_logger_tqdm +logger = logging.getLogger(__name__) + +from tqdm_multiprocess import TqdmMultiProcessPool + +def some_other_function(tqdm_func): + iterations1 = 100 + iterations2 = 5 + iterations3 = 2 + + total_iterations = iterations1 * iterations2 * iterations3 + with tqdm_func(total=total_iterations, dynamic_ncols=True) as progress3: + progress3.set_description("outer") + for i in range(iterations3): + logger.info("outer") + total_iterations = iterations1 * iterations2 + with tqdm_func(total=total_iterations, dynamic_ncols=True) as progress2: + progress2.set_description("middle") + for j in range(iterations2): + logger.info("middle") + #for k in tqdm_func(range(iterations1), dynamic_ncols=True, desc="inner"): + with tqdm_func(total=iterations1, dynamic_ncols=True) as progress1: + for j in range(iterations1): + # logger.info("inner") # Spam slows down tqdm too much + progress1.set_description("innert") + sleep(0.01) + progress1.update() + progress2.update() + progress3.update() + + logger.warning(f"Warning test message. {multiprocessing.current_process().name}") + logger.error(f"Error test message. {multiprocessing.current_process().name}") + + +# Multiprocessed +def example_multiprocessing_function(some_input, tqdm_func): + logger.debug(f"Debug test message - I won't show up in console. {multiprocessing.current_process().name}") + logger.info(f"Info test message. {multiprocessing.current_process().name}") + some_other_function(tqdm_func) + return True + +def error_callback(): + print("Error!") + +def example(): + pool = TqdmMultiProcessPool() + process_count = 4 + task_count = 10 + initial_tasks = [(example_multiprocessing_function, (i,)) for i in range(task_count)] + results = pool.map(process_count, initial_tasks, error_callback) + print(results) + +if __name__ == '__main__': + logfile_path = "tqdm_multiprocessing_example.log" + setup_logger_tqdm(logfile_path) # Logger will write messages using tqdm.write + example() \ No newline at end of file diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/fastuuid-0.14.0.dist-info/INSTALLER b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/fastuuid-0.14.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/fastuuid-0.14.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/fastuuid-0.14.0.dist-info/METADATA b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/fastuuid-0.14.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..54dbc15248c2af474a3dfc6d3fc94f75c0e12330 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/fastuuid-0.14.0.dist-info/METADATA @@ -0,0 +1,24 @@ +Metadata-Version: 2.4 +Name: fastuuid +Version: 0.14.0 +Classifier: Development Status :: 4 - Beta +Classifier: License :: OSI Approved :: BSD License +Classifier: Programming Language :: Rust +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3 +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.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Topic :: Software Development :: Libraries +Classifier: Topic :: Software Development :: Libraries :: Python Modules +License-File: LICENSE +Summary: Python bindings to Rust's UUID library. +Maintainer-email: Omer Katz +Requires-Python: >=3.8 +Project-URL: homepage, https://github.com/thedrow/fastuuid/ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/fastuuid-0.14.0.dist-info/RECORD b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/fastuuid-0.14.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..30ac6d1748f0db072061b67b343b834a401b14a6 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/fastuuid-0.14.0.dist-info/RECORD @@ -0,0 +1,10 @@ +fastuuid-0.14.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +fastuuid-0.14.0.dist-info/METADATA,sha256=uyf1iRFUiBrvfxoZL5HUn31Ga-Vk_gsoZbXnWTQvsLQ,1094 +fastuuid-0.14.0.dist-info/RECORD,, +fastuuid-0.14.0.dist-info/WHEEL,sha256=fzKw7D4hQlly-QR1ny78JqSVziI8F0zhh7uHrIL1JAo,129 +fastuuid-0.14.0.dist-info/licenses/LICENSE,sha256=AHNshSOGrBWhIoPABne0bvSzA75TqwodBfSKkpE1X6Q,1534 +fastuuid/__init__.py,sha256=DttcCzqwuWmdg2_9O6ZKe5WWv5cpwAPzO3aT-xZx9zk,115 +fastuuid/__init__.pyi,sha256=0xoNm6mo3LxCSrg4F1wGvEzWLS6aehIOo2yHqEesvBo,2141 +fastuuid/__pycache__/__init__.cpython-310.pyc,, +fastuuid/fastuuid.cpython-310-x86_64-linux-gnu.so,sha256=IkcBxN8rMEBC6JV0G6gAyvS1_SdvwdzfICfC2I1eGrg,621456 +fastuuid/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/fastuuid-0.14.0.dist-info/WHEEL b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/fastuuid-0.14.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..e8fd6888e9b6be4b8339bcd99f19c143018b0f54 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/fastuuid-0.14.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: maturin (1.9.6) +Root-Is-Purelib: false +Tag: cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/functorch/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/functorch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0aef38c8a9bb84a9833c4c2c9c34ad528d564b32 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/functorch/__init__.py @@ -0,0 +1,39 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. +import torch +from torch._functorch.deprecated import ( + combine_state_for_ensemble, + functionalize, + grad, + grad_and_value, + hessian, + jacfwd, + jacrev, + jvp, + make_functional, + make_functional_with_buffers, + vjp, + vmap, +) + +# utilities. Maybe these should go in their own namespace in the future? +from torch._functorch.make_functional import ( + FunctionalModule, + FunctionalModuleWithBuffers, +) + +# Was never documented +from torch._functorch.python_key import make_fx + + +# Top-level APIs. Please think carefully before adding something to the +# top-level namespace: +# - private helper functions should go into torch._functorch +# - very experimental things should go into functorch.experimental +# - compilation related things should go into functorch.compile + + +__version__ = torch.__version__ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/gitdb-4.0.12.dist-info/AUTHORS b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/gitdb-4.0.12.dist-info/AUTHORS new file mode 100644 index 0000000000000000000000000000000000000000..6c7e9b9971cca907772213fce28eb8e0162a875f --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/gitdb-4.0.12.dist-info/AUTHORS @@ -0,0 +1,4 @@ +Creator: Sebastian Thiel + +Contributors: + - Ram Rachum (@cool-RR) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/gitdb-4.0.12.dist-info/INSTALLER b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/gitdb-4.0.12.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/gitdb-4.0.12.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/gitdb-4.0.12.dist-info/LICENSE b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/gitdb-4.0.12.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0d6fe8bdb9ee5bb745e2b86c9e8745676ff0ef4a --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/gitdb-4.0.12.dist-info/LICENSE @@ -0,0 +1,42 @@ +Copyright (C) 2010, 2011 Sebastian Thiel and contributors +All rights reserved. + +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 the GitDB project 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. + + +Additional Licenses +------------------- +The files at +gitdb/test/fixtures/packs/pack-11fdfa9e156ab73caae3b6da867192221f2089c2.idx +and +gitdb/test/fixtures/packs/pack-11fdfa9e156ab73caae3b6da867192221f2089c2.pack +are licensed under GNU GPL as part of the git source repository, +see http://en.wikipedia.org/wiki/Git_%28software%29 for more information. + +They are not required for the actual operation, which is why they are not found +in the distribution package. diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/gitdb-4.0.12.dist-info/METADATA b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/gitdb-4.0.12.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..a06741dcc03232d817d536ce63d15246b243f250 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/gitdb-4.0.12.dist-info/METADATA @@ -0,0 +1,32 @@ +Metadata-Version: 2.1 +Name: gitdb +Version: 4.0.12 +Summary: Git Object Database +Home-page: https://github.com/gitpython-developers/gitdb +Author: Sebastian Thiel +Author-email: byronimo@gmail.com +License: BSD License +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Console +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: Operating System :: OS Independent +Classifier: Operating System :: POSIX +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: MacOS :: MacOS X +Classifier: Programming Language :: Python +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.13 +Classifier: Programming Language :: Python :: 3 :: Only +Requires-Python: >=3.7 +License-File: LICENSE +License-File: AUTHORS +Requires-Dist: smmap<6,>=3.0.1 + +GitDB is a pure-Python git object database diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/gitdb-4.0.12.dist-info/RECORD b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/gitdb-4.0.12.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..1bd60a5670f90c29fbca80f5e85b300f53dcdbff --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/gitdb-4.0.12.dist-info/RECORD @@ -0,0 +1,57 @@ +gitdb-4.0.12.dist-info/AUTHORS,sha256=aUmmuuKGJrGDzN5i-dDIbj00R1IOPcFTZDWznhEwZuM,66 +gitdb-4.0.12.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +gitdb-4.0.12.dist-info/LICENSE,sha256=79KfWWoI6IV-aOdpSlC82nKDl5LafD8EG8v_XxgAkjk,1984 +gitdb-4.0.12.dist-info/METADATA,sha256=lnDS3IZgOda3yR9SzYHH8iTNdGf3aFx8KebEaR0b89k,1230 +gitdb-4.0.12.dist-info/RECORD,, +gitdb-4.0.12.dist-info/WHEEL,sha256=PZUExdf71Ui_so67QXpySuHtCi3-J3wvF4ORK6k_S8U,91 +gitdb-4.0.12.dist-info/top_level.txt,sha256=ss6atT8cG4mQuAYXO6PokJ0r4Mm5cBiDbKsu2e3YHfs,6 +gitdb/__init__.py,sha256=Zfj1Uasvn9KgccHILrsHFZGTGFm4mvmEmw0trh6HOrM,551 +gitdb/__pycache__/__init__.cpython-310.pyc,, +gitdb/__pycache__/base.cpython-310.pyc,, +gitdb/__pycache__/const.cpython-310.pyc,, +gitdb/__pycache__/exc.cpython-310.pyc,, +gitdb/__pycache__/fun.cpython-310.pyc,, +gitdb/__pycache__/pack.cpython-310.pyc,, +gitdb/__pycache__/stream.cpython-310.pyc,, +gitdb/__pycache__/typ.cpython-310.pyc,, +gitdb/__pycache__/util.cpython-310.pyc,, +gitdb/base.py,sha256=krg61c_FKEvn4KAcX6pjH-hlpFfRCcM7mrki4Hnmxew,8023 +gitdb/const.py,sha256=WWmEYKNDdm3J9fxYTFT_B6-QLDSMBClbz0LSBa1D1S8,90 +gitdb/db/__init__.py,sha256=aQTZnxpfk6c76X1ubZzO9pBq4STnL6hCoGxZzXurEZ4,371 +gitdb/db/__pycache__/__init__.cpython-310.pyc,, +gitdb/db/__pycache__/base.cpython-310.pyc,, +gitdb/db/__pycache__/git.cpython-310.pyc,, +gitdb/db/__pycache__/loose.cpython-310.pyc,, +gitdb/db/__pycache__/mem.cpython-310.pyc,, +gitdb/db/__pycache__/pack.cpython-310.pyc,, +gitdb/db/__pycache__/ref.cpython-310.pyc,, +gitdb/db/base.py,sha256=_qpZ1VzwpoTcU3_-IIXmwIW0p63HXrtJ5jWNgjrLjRY,9061 +gitdb/db/git.py,sha256=b5O01eZsnzldruzEENvqiw8Q7Daz2iETrlAqH0aggdE,2666 +gitdb/db/loose.py,sha256=z7m0Cju-knikJi5UX6KWdWAJ9OOCeOE4gfYBso4XAQA,8734 +gitdb/db/mem.py,sha256=VDscunT4EtRo2GBE52lup1ki3si8enImUSKmSVq8kwc,3343 +gitdb/db/pack.py,sha256=iZPDF6rQ-kCrgbdsZRA83CL-zWsoQaZxo5rcTarjAoQ,7285 +gitdb/db/ref.py,sha256=rGOzF3cAOBW9i0Owz_Iw6c4K5BgbYFwk5btMaXGvCoc,2591 +gitdb/exc.py,sha256=B0N6I2rctCwd0Upoq2laTigbVZNOZ38nfobRcKDBtV4,1496 +gitdb/fun.py,sha256=jw3paQMgxexUn2NENFavLXfABfNvDBRfRCvv2VHkvms,23243 +gitdb/pack.py,sha256=buboXaTzXKEedNX5j1zIUIPhnLmHkDRl7Rg9ftclt14,39228 +gitdb/stream.py,sha256=0-BWcggWWZniMXGGaAe3MR6iH9DBt5ir9YtgE2_rKKw,27541 +gitdb/test/__init__.py,sha256=4cJQwIMepzCxK0hdxDegJGxNVK4dungjbPzCUJc1ZIU,204 +gitdb/test/__pycache__/__init__.cpython-310.pyc,, +gitdb/test/__pycache__/lib.cpython-310.pyc,, +gitdb/test/__pycache__/test_base.cpython-310.pyc,, +gitdb/test/__pycache__/test_example.cpython-310.pyc,, +gitdb/test/__pycache__/test_pack.cpython-310.pyc,, +gitdb/test/__pycache__/test_stream.cpython-310.pyc,, +gitdb/test/__pycache__/test_util.cpython-310.pyc,, +gitdb/test/lib.py,sha256=iXBcJ3RDAN0uj9NbyEzt90TuCsDFt3SjHA61Ly6Xyxs,5489 +gitdb/test/test_base.py,sha256=6zjmON19J7LRDidlMSz2iQArONdkK6_v-DzhAQJzChg,2836 +gitdb/test/test_example.py,sha256=In7WgwvrGCbxPcuLCmkVIs4kdhCJ8rtcEvp115fHeU4,1350 +gitdb/test/test_pack.py,sha256=bbkupZPBFlpjBcPZTZ0OmRrTA9I3-fVdfwLtNa14_3s,9228 +gitdb/test/test_stream.py,sha256=RwSB49q6JHM7EFW413CZQeGRfkK92aQ0IVfTocIa3bo,5727 +gitdb/test/test_util.py,sha256=WQKQBP2uPF4wwNJFlUd9-YE2Q3CmlgpoY4MRk5G0r54,3243 +gitdb/typ.py,sha256=dZlbzfy5RFNHiZHEOwVy-6T-aZ3xLv0mGaJVyxKBd0M,373 +gitdb/util.py,sha256=F3bE24b2QDihz4tqc3Km7wbC6N65EjwFoao-yzrRJSY,12302 +gitdb/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +gitdb/utils/__pycache__/__init__.cpython-310.pyc,, +gitdb/utils/__pycache__/encoding.cpython-310.pyc,, +gitdb/utils/encoding.py,sha256=ceZZFb86LGJ71cwW6qkq_BFquAlNE7jaafNbwxYRSXk,372 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/gitdb-4.0.12.dist-info/WHEEL b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/gitdb-4.0.12.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..ae527e7d64811439e61b93aa375defb30e06edfe --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/gitdb-4.0.12.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (75.6.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/gitdb-4.0.12.dist-info/top_level.txt b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/gitdb-4.0.12.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..c2023eef06a4fb9bb4a6e90d6405308215059169 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/gitdb-4.0.12.dist-info/top_level.txt @@ -0,0 +1 @@ +gitdb diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google_auth-2.52.0.dist-info/INSTALLER b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google_auth-2.52.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google_auth-2.52.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google_auth-2.52.0.dist-info/METADATA b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google_auth-2.52.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..ddec9a5e19dbe908b11aec1983dc1fba271d64a8 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google_auth-2.52.0.dist-info/METADATA @@ -0,0 +1,165 @@ +Metadata-Version: 2.4 +Name: google-auth +Version: 2.52.0 +Summary: Google Authentication Library +Home-page: https://github.com/googleapis/google-auth-library-python +Author: Google Cloud Platform +Author-email: googleapis-packages@google.com +License: Apache 2.0 +Keywords: google auth oauth client +Classifier: Programming Language :: Python :: 3 +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: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Operating System :: POSIX +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: MacOS :: MacOS X +Classifier: Operating System :: OS Independent +Classifier: Topic :: Internet :: WWW/HTTP +Requires-Python: >=3.10 +License-File: LICENSE +Requires-Dist: pyasn1-modules>=0.2.1 +Requires-Dist: cryptography>=38.0.3 +Provides-Extra: cryptography +Requires-Dist: cryptography>=38.0.3; extra == "cryptography" +Provides-Extra: aiohttp +Requires-Dist: aiohttp<4.0.0,>=3.8.0; extra == "aiohttp" +Requires-Dist: requests<3.0.0,>=2.20.0; extra == "aiohttp" +Provides-Extra: enterprise-cert +Requires-Dist: pyopenssl; extra == "enterprise-cert" +Provides-Extra: pyopenssl +Requires-Dist: pyopenssl>=20.0.0; extra == "pyopenssl" +Provides-Extra: pyjwt +Requires-Dist: pyjwt>=2.0; extra == "pyjwt" +Provides-Extra: reauth +Requires-Dist: pyu2f>=0.1.5; extra == "reauth" +Provides-Extra: requests +Requires-Dist: requests<3.0.0,>=2.20.0; extra == "requests" +Provides-Extra: testing +Requires-Dist: grpcio; extra == "testing" +Requires-Dist: flask; extra == "testing" +Requires-Dist: freezegun; extra == "testing" +Requires-Dist: pyjwt>=2.0; extra == "testing" +Requires-Dist: pytest; extra == "testing" +Requires-Dist: pytest-cov; extra == "testing" +Requires-Dist: pytest-localserver; extra == "testing" +Requires-Dist: pyopenssl>=20.0.0; extra == "testing" +Requires-Dist: pyu2f>=0.1.5; extra == "testing" +Requires-Dist: responses; extra == "testing" +Requires-Dist: urllib3; extra == "testing" +Requires-Dist: packaging; extra == "testing" +Requires-Dist: aiohttp<4.0.0,>=3.8.0; extra == "testing" +Requires-Dist: requests<3.0.0,>=2.20.0; extra == "testing" +Requires-Dist: aioresponses; extra == "testing" +Requires-Dist: pytest-asyncio; extra == "testing" +Requires-Dist: pyopenssl<24.3.0; extra == "testing" +Requires-Dist: aiohttp<3.10.0; extra == "testing" +Provides-Extra: urllib3 +Requires-Dist: urllib3; extra == "urllib3" +Requires-Dist: packaging; extra == "urllib3" +Provides-Extra: rsa +Requires-Dist: rsa<5,>=3.1.4; extra == "rsa" +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: home-page +Dynamic: keywords +Dynamic: license +Dynamic: license-file +Dynamic: provides-extra +Dynamic: requires-dist +Dynamic: requires-python +Dynamic: summary + +Google Auth Python Library +========================== + +|pypi| + +This library simplifies using Google's various server-to-server authentication +mechanisms to access Google APIs. + +.. |pypi| image:: https://img.shields.io/pypi/v/google-auth.svg + :target: https://pypi.python.org/pypi/google-auth + +Installing +---------- + +You can install using `pip`_:: + + $ pip install google-auth + +.. _pip: https://pip.pypa.io/en/stable/ + +For more information on setting up your Python development environment, please refer to `Python Development Environment Setup Guide`_ for Google Cloud Platform. + +.. _`Python Development Environment Setup Guide`: https://cloud.google.com/python/docs/setup + +Extras +------ + +google-auth has few extras that you can install. For example:: + + $ pip install google-auth[pyopenssl] + +Note that the extras pyopenssl and enterprise_cert should not be used together because they use conflicting versions of `cryptography`_. + +.. _`cryptography`: https://cryptography.io/en/latest/ + +Supported Python Versions +^^^^^^^^^^^^^^^^^^^^^^^^^ +Python >= 3.10 + +Unsupported Python Versions +^^^^^^^^^^^^^^^^^^^^^^^^^^^ +- Python == 2.7: The last version of this library with support for Python 2.7 + was `google.auth == 1.34.0`. + +- Python 3.5: The last version of this library with support for Python 3.5 + was `google.auth == 1.23.0`. + +- Python 3.6: The last version of this library with support for Python 3.6 + was `google.auth == 2.22.0`. + +- Python 3.7: The last version of this library with support for Python 3.7 + was `google.auth == 2.45.0`. + + +Documentation +------------- + +Google Auth Python Library has usage and reference documentation at https://googleapis.dev/python/google-auth/latest/index.html. + +Current Maintainers +------------------- +- googleapis-auth@google.com + +Authors +------- + +- `@theacodes `_ (Thea Flowers) +- `@dhermes `_ (Danny Hermes) +- `@lukesneeringer `_ (Luke Sneeringer) +- `@busunkim96 `_ (Bu Sun Kim) + +Contributing +------------ + +Contributions to this library are always welcome and highly encouraged. + +See `CONTRIBUTING.rst`_ for more information on how to get started. + +.. _CONTRIBUTING.rst: https://github.com/googleapis/google-auth-library-python/blob/main/CONTRIBUTING.rst + +License +------- + +Apache 2.0 - See `the LICENSE`_ for more information. + +.. _the LICENSE: https://github.com/googleapis/google-auth-library-python/blob/main/LICENSE diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google_auth-2.52.0.dist-info/RECORD b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google_auth-2.52.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..bc1c988fb36d26245220b46b81652468267a8dfd --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google_auth-2.52.0.dist-info/RECORD @@ -0,0 +1,164 @@ +google/auth/__init__.py,sha256=Aq1Iysvxvj5sqbsNHPFR5CMbBJs6JCKCCmn5JtNaKQY,1064 +google/auth/__pycache__/__init__.cpython-310.pyc,, +google/auth/__pycache__/_agent_identity_utils.cpython-310.pyc,, +google/auth/__pycache__/_cache.cpython-310.pyc,, +google/auth/__pycache__/_cloud_sdk.cpython-310.pyc,, +google/auth/__pycache__/_credentials_async.cpython-310.pyc,, +google/auth/__pycache__/_credentials_base.cpython-310.pyc,, +google/auth/__pycache__/_default.cpython-310.pyc,, +google/auth/__pycache__/_default_async.cpython-310.pyc,, +google/auth/__pycache__/_exponential_backoff.cpython-310.pyc,, +google/auth/__pycache__/_helpers.cpython-310.pyc,, +google/auth/__pycache__/_jwt_async.cpython-310.pyc,, +google/auth/__pycache__/_oauth2client.cpython-310.pyc,, +google/auth/__pycache__/_refresh_worker.cpython-310.pyc,, +google/auth/__pycache__/_regional_access_boundary_utils.cpython-310.pyc,, +google/auth/__pycache__/_service_account_info.cpython-310.pyc,, +google/auth/__pycache__/api_key.cpython-310.pyc,, +google/auth/__pycache__/app_engine.cpython-310.pyc,, +google/auth/__pycache__/aws.cpython-310.pyc,, +google/auth/__pycache__/credentials.cpython-310.pyc,, +google/auth/__pycache__/downscoped.cpython-310.pyc,, +google/auth/__pycache__/environment_vars.cpython-310.pyc,, +google/auth/__pycache__/exceptions.cpython-310.pyc,, +google/auth/__pycache__/external_account.cpython-310.pyc,, +google/auth/__pycache__/external_account_authorized_user.cpython-310.pyc,, +google/auth/__pycache__/iam.cpython-310.pyc,, +google/auth/__pycache__/identity_pool.cpython-310.pyc,, +google/auth/__pycache__/impersonated_credentials.cpython-310.pyc,, +google/auth/__pycache__/jwt.cpython-310.pyc,, +google/auth/__pycache__/metrics.cpython-310.pyc,, +google/auth/__pycache__/pluggable.cpython-310.pyc,, +google/auth/__pycache__/version.cpython-310.pyc,, +google/auth/_agent_identity_utils.py,sha256=91ZHrF7BnB5OyxuQtqBDwrMmlBrVjP4kchmvaEF09Aw,9519 +google/auth/_cache.py,sha256=9xbqdkwFa-9W5tzb2WM_bNzFwZ6hKazMcsPugqHuAyA,1863 +google/auth/_cloud_sdk.py,sha256=pwX6vZhYqEpu3vkSNxJ2MI5wMT5t-xX7273QqCtWFZk,5211 +google/auth/_credentials_async.py,sha256=bHB28wMULOIEMmYqKEOU06A4co7uIXPcnfVC_TaA6KY,6802 +google/auth/_credentials_base.py,sha256=KxdCZyoFyvrfWhJbNnuYkpUhxs0bmbxYvcH8-xp5hUs,2692 +google/auth/_default.py,sha256=FqwhclHCgKNZz1p-lMREv6mY9lKTn2le6CPxckGitxk,31271 +google/auth/_default_async.py,sha256=ZkU8jig_lEb_IpsYT8DBzNPLRGgfYNb_QbL0S3lpjks,11848 +google/auth/_exponential_backoff.py,sha256=qxA9ek80rBkoARx0Egl2b1MlYU0D-pQNVqgCmUh-lgU,5372 +google/auth/_helpers.py,sha256=aLk0KE2T8XWepwngfPGqSANOFB0a4Pym80FCmTdFSco,17363 +google/auth/_jwt_async.py,sha256=5mGab5CkdnBMkQkS4mtNkwFkktp1jBw6G1sYQk8bYKY,5972 +google/auth/_oauth2client.py,sha256=9pBShk1ekwkPNoD5WoQJNQHHD3luNfzpBVoQJo8n1rc,5875 +google/auth/_refresh_worker.py,sha256=zT2jj-PjPtjF3Bqg_n4t1CdL32yBVEUhPKZQwoNu-Xg,3379 +google/auth/_regional_access_boundary_utils.py,sha256=jp7vzofME65Ksn9l6ovqS_aVIob-11LYgvNlruVQFfA,15414 +google/auth/_service_account_info.py,sha256=EdOEZql9_mG2cJ54KmL3Q5jO3C3wcadwlCObg4gKjus,2813 +google/auth/aio/__init__.py,sha256=e3ToAxXNHhqJLBgW8B66650xdqrTCZDLcwP2p5DhCPM,869 +google/auth/aio/__pycache__/__init__.cpython-310.pyc,, +google/auth/aio/__pycache__/_helpers.cpython-310.pyc,, +google/auth/aio/__pycache__/credentials.cpython-310.pyc,, +google/auth/aio/_helpers.py,sha256=glCa_-GYxDrcPBFt80LBhMz_V7vLjxAEEWfOZB8lwT0,2334 +google/auth/aio/credentials.py,sha256=lXY0_SJ9c36Mzp47fN4a8JT5HfNzFQtIIwsZEwzoDR4,5273 +google/auth/aio/transport/__init__.py,sha256=8dQWHpube1IeWw02q6AvMRTM5V_2iN4y3UMLenbmUUQ,4692 +google/auth/aio/transport/__pycache__/__init__.cpython-310.pyc,, +google/auth/aio/transport/__pycache__/aiohttp.cpython-310.pyc,, +google/auth/aio/transport/__pycache__/mtls.cpython-310.pyc,, +google/auth/aio/transport/__pycache__/sessions.cpython-310.pyc,, +google/auth/aio/transport/aiohttp.py,sha256=Gweuf3GcNG1_1_GmPpZvcFRXMYvE3MgSPT7XDZSlSAc,7552 +google/auth/aio/transport/mtls.py,sha256=Xpd57h-DHmgjv8dQdjsqxj-ftr_pfhWAWY5_gYJKgPw,6801 +google/auth/aio/transport/sessions.py,sha256=Xrhnl9cLP5egcoQuG8ensQBmCu454j7k1mlpDNLYPzc,23961 +google/auth/api_key.py,sha256=PeieTYceHJIFCo0zQo1EA9NEDL_Ie6S78qmD-6Ig17s,2583 +google/auth/app_engine.py,sha256=mQ7NrKQYd3LiZ7F_ttlqs9Tjf4EEtJNHTPfpixCycW0,6096 +google/auth/aws.py,sha256=aVSDOH2pnECuEYjxn_pHGu8447xyB3P9sAiCQem4ePo,34573 +google/auth/compute_engine/__init__.py,sha256=BqeTka-oyHFATkys3SGKRlOyWQ8mVV0vVaP2hOwV4Qw,910 +google/auth/compute_engine/__pycache__/__init__.cpython-310.pyc,, +google/auth/compute_engine/__pycache__/_metadata.cpython-310.pyc,, +google/auth/compute_engine/__pycache__/_mtls.cpython-310.pyc,, +google/auth/compute_engine/__pycache__/credentials.cpython-310.pyc,, +google/auth/compute_engine/_metadata.py,sha256=g44MLHIWkwM2g59-YEWsbSASJCfLRR6JdJO1H9xDciw,17859 +google/auth/compute_engine/_mtls.py,sha256=8EQrVyWVQPuAnuG8C4uq29OaerpsmFxGXruw3Rfuxco,5720 +google/auth/compute_engine/credentials.py,sha256=MsFquoNefl-Hcl7ZlzmDnNqnu8_IFhF0oUOLHHmVeHo,21944 +google/auth/credentials.py,sha256=KqtYVGHpPJh6BEeiIFvhHJZ6W1s1JpkI6pU0VT4M5-I,29028 +google/auth/crypt/__init__.py,sha256=ukDmKrdUmHqGc5rDLcoel_TKXdV5wX05r5Gqi9hnWBE,3144 +google/auth/crypt/__pycache__/__init__.cpython-310.pyc,, +google/auth/crypt/__pycache__/_cryptography_rsa.cpython-310.pyc,, +google/auth/crypt/__pycache__/_helpers.cpython-310.pyc,, +google/auth/crypt/__pycache__/_python_rsa.cpython-310.pyc,, +google/auth/crypt/__pycache__/base.cpython-310.pyc,, +google/auth/crypt/__pycache__/es.cpython-310.pyc,, +google/auth/crypt/__pycache__/es256.cpython-310.pyc,, +google/auth/crypt/__pycache__/rsa.cpython-310.pyc,, +google/auth/crypt/_cryptography_rsa.py,sha256=o2QTRkfDRLtEBiq-fbpbTWypvxaxUDwzlx2NpXG9o0w,5158 +google/auth/crypt/_helpers.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +google/auth/crypt/_python_rsa.py,sha256=Exqz9OgDm-3JHHd636gnAdXdcH6pjDWBNJz21uDRnUE,6747 +google/auth/crypt/base.py,sha256=3CJrnQsppR6h-WnTRqSrt1hPEQVkHcwNIVJ_B5M00hY,4190 +google/auth/crypt/es.py,sha256=3eHSDU_lh95pMYE3eIGErGHPETqsRCHeK2VtQnqVPk8,8019 +google/auth/crypt/es256.py,sha256=cFaDuQRdXx3f_aVy-HH0VQ6G49VNSAhB04jnbjyxHNI,1454 +google/auth/crypt/rsa.py,sha256=coLr0FFyuDAmDaoXefpriH_naAJbmgwFORUDVYGdBYU,4770 +google/auth/downscoped.py,sha256=KmmC8lbBWUFUsIYt1VpcbTXs3yYJYXteH19qdZQgobA,21793 +google/auth/environment_vars.py,sha256=elIkXWjxdlOsf-CQid8UFcXcAIHtg17wi6otcveYCsQ,5163 +google/auth/exceptions.py,sha256=8oEeB_1UirJIyBoglQRpCFjCOcxcTaLr6EpBrrxjeEs,3193 +google/auth/external_account.py,sha256=BjNWaDWxOCCPHAoxOcuTWTuY5T-Arqkh2aRlUWY640E,31161 +google/auth/external_account_authorized_user.py,sha256=4_skldJ-9v5pG_fMhbEJeSMkvsasREbiQtD_-v5PPYE,17725 +google/auth/iam.py,sha256=Fc-wdlFaixOi1lKnneSNItQA29_xkqH7vB-P-qOS2h0,5607 +google/auth/identity_pool.py,sha256=doIKIMU7_c9GbDrXqv12A1BS9Bb6AgL-uSt72QpsjuQ,24697 +google/auth/impersonated_credentials.py,sha256=QRGtYzyRyJKgTsZOJIK7434HAARRRvyOIE_4Ysm8LJQ,27592 +google/auth/jwt.py,sha256=CxVlg9VxMbgdSaT7_4hISDNkL9eBVNi4jCmpFJXiOJM,31178 +google/auth/metrics.py,sha256=usjITvTFmO0YogJJDi31_hgl2kgENuKMfgWy6LTGhxg,5616 +google/auth/pluggable.py,sha256=N9lxIiiegT6DIv3poc5B3B-6OlVmFRZr-AmNO6Xzid4,18371 +google/auth/py.typed,sha256=l05_LTgi3oy-einKBrw66s6aavgzG2o-SekKPOY3ayM,74 +google/auth/transport/__init__.py,sha256=vTdWUDBCXWF6wk3Xzu7L5I1lbtGYTxONi-IKYOmDdFM,3654 +google/auth/transport/__pycache__/__init__.cpython-310.pyc,, +google/auth/transport/__pycache__/_aiohttp_requests.cpython-310.pyc,, +google/auth/transport/__pycache__/_custom_tls_signer.cpython-310.pyc,, +google/auth/transport/__pycache__/_http_client.cpython-310.pyc,, +google/auth/transport/__pycache__/_mtls_helper.cpython-310.pyc,, +google/auth/transport/__pycache__/_requests_base.cpython-310.pyc,, +google/auth/transport/__pycache__/grpc.cpython-310.pyc,, +google/auth/transport/__pycache__/mtls.cpython-310.pyc,, +google/auth/transport/__pycache__/requests.cpython-310.pyc,, +google/auth/transport/__pycache__/urllib3.cpython-310.pyc,, +google/auth/transport/_aiohttp_requests.py,sha256=aJNNT09VISGPwcGS8DVR8G1l_DeOvnlJ2Z7kcAjXs14,14819 +google/auth/transport/_custom_tls_signer.py,sha256=ilLlKFNognkvOWcnlYAWmUIUo9YhSrTSAKLa05zQ8Do,9989 +google/auth/transport/_http_client.py,sha256=_lE2TaQOb2hZq5OrblNAYbpZzLX18LGXSyaNJuXHJ2w,3798 +google/auth/transport/_mtls_helper.py,sha256=PcYF7siMNiHMce_tXZa_oAgMaON3mBkJqqF5SqVXhm0,19684 +google/auth/transport/_requests_base.py,sha256=4y0tTMR_hPGeAmBSyCU6_moh99ZxJZ4CF79E2s-t7TA,1657 +google/auth/transport/grpc.py,sha256=cRYju1kWZ2YE5IlagRMh9trAW8J5kmmIrBmyZW7IGik,13742 +google/auth/transport/mtls.py,sha256=dfOH5kaz4R9pNdm5l-cRQc1PfpGldpS3FBwdSF72KfY,5163 +google/auth/transport/requests.py,sha256=--9PLv4Jaiz1HiIzl_tVKJ0Z1k-3XPQ3HBsXVBaIf4U,24332 +google/auth/transport/urllib3.py,sha256=bmYdTtBa3Yni5Q1pvpqbuHwF70g0gz7RfNsR6hDFz7g,18349 +google/auth/version.py,sha256=dsvR5WLpcs2VndN1GdJnexGRmTsOVQAi_paJLiPyWPw,598 +google/oauth2/__init__.py,sha256=iDyTpxuh864rLf4YyINgeO4wMJLQ53EUMPJpiw1GA3U,619 +google/oauth2/__pycache__/__init__.cpython-310.pyc,, +google/oauth2/__pycache__/_client.cpython-310.pyc,, +google/oauth2/__pycache__/_client_async.cpython-310.pyc,, +google/oauth2/__pycache__/_credentials_async.cpython-310.pyc,, +google/oauth2/__pycache__/_id_token_async.cpython-310.pyc,, +google/oauth2/__pycache__/_reauth_async.cpython-310.pyc,, +google/oauth2/__pycache__/_service_account_async.cpython-310.pyc,, +google/oauth2/__pycache__/challenges.cpython-310.pyc,, +google/oauth2/__pycache__/credentials.cpython-310.pyc,, +google/oauth2/__pycache__/gdch_credentials.cpython-310.pyc,, +google/oauth2/__pycache__/id_token.cpython-310.pyc,, +google/oauth2/__pycache__/reauth.cpython-310.pyc,, +google/oauth2/__pycache__/service_account.cpython-310.pyc,, +google/oauth2/__pycache__/sts.cpython-310.pyc,, +google/oauth2/__pycache__/utils.cpython-310.pyc,, +google/oauth2/__pycache__/webauthn_handler.cpython-310.pyc,, +google/oauth2/__pycache__/webauthn_handler_factory.cpython-310.pyc,, +google/oauth2/__pycache__/webauthn_types.cpython-310.pyc,, +google/oauth2/_client.py,sha256=2bOKX6ET_CF6kpa6bim8XKtFmzkH99KTeDfuhQfyPHU,22710 +google/oauth2/_client_async.py,sha256=nXLgAI5KVPRR6w7-5cjB8jc5V59hd-gpPu9OR7mElCw,10170 +google/oauth2/_credentials_async.py,sha256=hUrucQkcYuYlyCdHMci8tzaVncnjQlFc2sAfNu5Dt8k,4474 +google/oauth2/_id_token_async.py,sha256=ot4_u-rhA22TufWOAR5Mpaua7Q2aAtN4q_kJmj-YnII,10171 +google/oauth2/_reauth_async.py,sha256=XK63x1CCWTBX4TG_mwc1WnRmB3vG0JRZ5F-dNfxodcs,11715 +google/oauth2/_service_account_async.py,sha256=_epalmLbNizOHgHcLZXSoK6_Z5lTk1OiIdEBioBGB5E,5878 +google/oauth2/challenges.py,sha256=Pdy8IpwGJstz890Ctz_xZvhUwIlTvKibSnmHNbRBZd0,10405 +google/oauth2/credentials.py,sha256=BhgwiXwTPy42462fpXp8-A39XkEqLJXV9WCRbzOEUpw,25880 +google/oauth2/gdch_credentials.py,sha256=CY6iPnPuc2OCIe1Zujwg1Mu9QSl1iGJqGOy6TkUleHw,9007 +google/oauth2/id_token.py,sha256=sCPdYw6LxcLgDqUvKygmdcrIGzZFGGXoARRYI-BzZ_U,13710 +google/oauth2/py.typed,sha256=I0muXRRdbdpJoZ_VyheisiTTYcmjTAitQpNvuuh6fMw,76 +google/oauth2/reauth.py,sha256=CkkDpv79_8SsQDromAyI3sa2lS3V_M7bSZqWFZj30nw,12878 +google/oauth2/service_account.py,sha256=51OAO215HosNkPIHNa8HiCf7HNxW6099T0yh3d4HQLY,33572 +google/oauth2/sts.py,sha256=df-lzhe8cBKr2O-tWZTaWdgYonKm1J9HI5Cz_AfW1hU,7728 +google/oauth2/utils.py,sha256=4crAdpKbDtobpQfXJc3uF6Zm6F3IzffvRSo-9h_515w,6315 +google/oauth2/webauthn_handler.py,sha256=lg_5mHowRJ0kx2hluMYhcdiFctHZyi8CFc9fT8CkQwA,2743 +google/oauth2/webauthn_handler_factory.py,sha256=soE5cokZ3pLNbBo1HC6F1N-N-I-ir-DGlD0trGPCpBs,429 +google/oauth2/webauthn_types.py,sha256=IHdqUe-EWOU-CmyLnHLniqc7vGHZ8HpavB0dcjn7Zl8,5386 +google_auth-2.52.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +google_auth-2.52.0.dist-info/METADATA,sha256=FwwtDemqpiD1QdKWV6YFZTbggnM_5wB6RMoDBagIsKQ,5536 +google_auth-2.52.0.dist-info/RECORD,, +google_auth-2.52.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91 +google_auth-2.52.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357 +google_auth-2.52.0.dist-info/top_level.txt,sha256=_1QvSJIhFAGfxb79D6DhB7SUw2X6T4rwnz_LLrbcD3c,7 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google_auth-2.52.0.dist-info/WHEEL b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google_auth-2.52.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..14a883f292bc96b20c2b76a3081991f2676523a9 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google_auth-2.52.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (82.0.1) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google_auth-2.52.0.dist-info/top_level.txt b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google_auth-2.52.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..cb429113e0f9a73019fd799e8052093fea7f0c8b --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google_auth-2.52.0.dist-info/top_level.txt @@ -0,0 +1 @@ +google diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google_auth_oauthlib-1.4.0.dist-info/INSTALLER b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google_auth_oauthlib-1.4.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google_auth_oauthlib-1.4.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google_auth_oauthlib-1.4.0.dist-info/METADATA b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google_auth_oauthlib-1.4.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..eb1b5222989ca7497cff664c06f1d07ba1ca3c46 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google_auth_oauthlib-1.4.0.dist-info/METADATA @@ -0,0 +1,88 @@ +Metadata-Version: 2.4 +Name: google-auth-oauthlib +Version: 1.4.0 +Summary: Google Authentication Library +Home-page: https://github.com/googleapis/google-cloud-python/tree/main/packages/google-auth-oauthlib +Author: Google Cloud Platform +Author-email: googleapis-packages@google.com +License: Apache 2.0 +Keywords: google auth oauth client oauthlib +Classifier: Programming Language :: Python :: 3 +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: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Operating System :: POSIX +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: MacOS :: MacOS X +Classifier: Operating System :: OS Independent +Classifier: Topic :: Internet :: WWW/HTTP +Requires-Python: >=3.10 +License-File: LICENSE +Requires-Dist: google-auth!=2.43.0,!=2.44.0,!=2.45.0,<3.0.0,>=2.15.0 +Requires-Dist: requests-oauthlib>=0.7.0 +Provides-Extra: tool +Requires-Dist: click>=6.0.0; extra == "tool" +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: home-page +Dynamic: keywords +Dynamic: license +Dynamic: license-file +Dynamic: provides-extra +Dynamic: requires-dist +Dynamic: requires-python +Dynamic: summary + +oauthlib integration for Google Auth +==================================== + +|pypi| + +This library provides `oauthlib`_ integration with `google-auth`_. + +.. |pypi| image:: https://img.shields.io/pypi/v/google-auth-oauthlib.svg + :target: https://pypi.python.org/pypi/google-auth-oauthlib + +.. _oauthlib: https://github.com/idan/oauthlib +.. _google-auth: https://github.com/googleapis/google-auth-library-python + +Installing +---------- + +You can install using `pip`_:: + + $ pip install google-auth-oauthlib + +.. _pip: https://pip.pypa.io/en/stable/ + +Documentation +------------- + +The latest documentation is available at `google-auth-oauthlib.googleapis.dev`_. + +.. _google-auth-oauthlib.googleapis.dev: https://googleapis.dev/python/google-auth-oauthlib/latest/index.html + +Supported Python Versions +------------------------- +Python >= 3.10 + + +Unsupported Python Versions +--------------------------- + +Python == 2.7, Python <= 3.9. + + +License +------- + +Apache 2.0 - See `the LICENSE`_ for more information. + +.. _the LICENSE: https://github.com/googleapis/google-cloud-python/blob/main/LICENSE diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google_auth_oauthlib-1.4.0.dist-info/RECORD b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google_auth_oauthlib-1.4.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..5915aec09a4d9e6fe36f5a7afc1a9c032e4bf2fe --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google_auth_oauthlib-1.4.0.dist-info/RECORD @@ -0,0 +1,20 @@ +../../../bin/google-oauthlib-tool,sha256=HNW1mM0LCH0H3ScUXWDnSGIECKibTeKlHrm8todAS_Y,267 +google_auth_oauthlib-1.4.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +google_auth_oauthlib-1.4.0.dist-info/METADATA,sha256=zedFvagK6-josvLLOwvdGnDL6K4NMD3TtkWA4qeytvw,2586 +google_auth_oauthlib-1.4.0.dist-info/RECORD,, +google_auth_oauthlib-1.4.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91 +google_auth_oauthlib-1.4.0.dist-info/entry_points.txt,sha256=DL3GRTp3HgwLxdBZCPkz9o8sK9cnENZMmu09EzAovkk,88 +google_auth_oauthlib-1.4.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358 +google_auth_oauthlib-1.4.0.dist-info/top_level.txt,sha256=7odKtDnfVqHR3mxRtqx0bx6Vu0juw_gEOZCkWYyCjbo,21 +google_auth_oauthlib/__init__.py,sha256=TTUgKl-F0eTBxBmbwDwDbIN-L33LmD4JbNKwXE-HngU,846 +google_auth_oauthlib/__pycache__/__init__.cpython-310.pyc,, +google_auth_oauthlib/__pycache__/flow.cpython-310.pyc,, +google_auth_oauthlib/__pycache__/helpers.cpython-310.pyc,, +google_auth_oauthlib/__pycache__/interactive.cpython-310.pyc,, +google_auth_oauthlib/flow.py,sha256=3lttr091s_HHeceUQVKjAoLxnZtCgwzUWE7oAJ6jvKc,20361 +google_auth_oauthlib/helpers.py,sha256=px-X57Wr-SEvtGdExrsj4CQl7H-Fz88qwQCmbvVXR7o,5784 +google_auth_oauthlib/interactive.py,sha256=tJMCOCYoaOCGSHnXZ8tAAo-sG2MFOdIQd5PVw1zLEpw,6062 +google_auth_oauthlib/tool/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +google_auth_oauthlib/tool/__main__.py,sha256=0w3OwVESdHPsqlj6F-iYJUmA28TwBYTF2J2EGtL1SWA,3834 +google_auth_oauthlib/tool/__pycache__/__init__.cpython-310.pyc,, +google_auth_oauthlib/tool/__pycache__/__main__.cpython-310.pyc,, diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google_auth_oauthlib-1.4.0.dist-info/WHEEL b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google_auth_oauthlib-1.4.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..14a883f292bc96b20c2b76a3081991f2676523a9 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google_auth_oauthlib-1.4.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (82.0.1) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google_auth_oauthlib-1.4.0.dist-info/entry_points.txt b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google_auth_oauthlib-1.4.0.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..a33f32fa2ef02405f14d1457af1055e1e2fc44c4 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google_auth_oauthlib-1.4.0.dist-info/entry_points.txt @@ -0,0 +1,2 @@ +[console_scripts] +google-oauthlib-tool = google_auth_oauthlib.tool.__main__:main [tool] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google_auth_oauthlib-1.4.0.dist-info/top_level.txt b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google_auth_oauthlib-1.4.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..acba0c802b1a7f82e60daaf544d2f8fdc281b7a1 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google_auth_oauthlib-1.4.0.dist-info/top_level.txt @@ -0,0 +1 @@ +google_auth_oauthlib diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/googleapiclient/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/googleapiclient/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c9218dd854063df739f78247c299643f2c6b29f0 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/googleapiclient/__init__.py @@ -0,0 +1,27 @@ +# Copyright 2014 Google Inc. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Set default logging handler to avoid "No handler found" warnings. +import logging + +try: # Python 2.7+ + from logging import NullHandler +except ImportError: + + class NullHandler(logging.Handler): + def emit(self, record): + pass + + +logging.getLogger(__name__).addHandler(NullHandler()) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/googleapiclient/_auth.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/googleapiclient/_auth.py new file mode 100644 index 0000000000000000000000000000000000000000..065b2ecd307df1d69a7e6afe1b94086b8b33c838 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/googleapiclient/_auth.py @@ -0,0 +1,167 @@ +# Copyright 2016 Google Inc. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Helpers for authentication using oauth2client or google-auth.""" + +import httplib2 + +try: + import google.auth + import google.auth.credentials + + HAS_GOOGLE_AUTH = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH = False + +try: + import google_auth_httplib2 +except ImportError: # pragma: NO COVER + google_auth_httplib2 = None + +try: + import oauth2client + import oauth2client.client + + HAS_OAUTH2CLIENT = True +except ImportError: # pragma: NO COVER + HAS_OAUTH2CLIENT = False + + +def credentials_from_file(filename, scopes=None, quota_project_id=None): + """Returns credentials loaded from a file.""" + if HAS_GOOGLE_AUTH: + credentials, _ = google.auth.load_credentials_from_file( + filename, scopes=scopes, quota_project_id=quota_project_id + ) + return credentials + else: + raise EnvironmentError( + "client_options.credentials_file is only supported in google-auth." + ) + + +def default_credentials(scopes=None, quota_project_id=None): + """Returns Application Default Credentials.""" + if HAS_GOOGLE_AUTH: + credentials, _ = google.auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) + return credentials + elif HAS_OAUTH2CLIENT: + if scopes is not None or quota_project_id is not None: + raise EnvironmentError( + "client_options.scopes and client_options.quota_project_id are not supported in oauth2client." + "Please install google-auth." + ) + return oauth2client.client.GoogleCredentials.get_application_default() + else: + raise EnvironmentError( + "No authentication library is available. Please install either " + "google-auth or oauth2client." + ) + + +def with_scopes(credentials, scopes): + """Scopes the credentials if necessary. + + Args: + credentials (Union[ + google.auth.credentials.Credentials, + oauth2client.client.Credentials]): The credentials to scope. + scopes (Sequence[str]): The list of scopes. + + Returns: + Union[google.auth.credentials.Credentials, + oauth2client.client.Credentials]: The scoped credentials. + """ + if HAS_GOOGLE_AUTH and isinstance(credentials, google.auth.credentials.Credentials): + return google.auth.credentials.with_scopes_if_required(credentials, scopes) + else: + try: + if credentials.create_scoped_required(): + return credentials.create_scoped(scopes) + else: + return credentials + except AttributeError: + return credentials + + +def authorized_http(credentials): + """Returns an http client that is authorized with the given credentials. + + Args: + credentials (Union[ + google.auth.credentials.Credentials, + oauth2client.client.Credentials]): The credentials to use. + + Returns: + Union[httplib2.Http, google_auth_httplib2.AuthorizedHttp]: An + authorized http client. + """ + from googleapiclient.http import build_http + + if HAS_GOOGLE_AUTH and isinstance(credentials, google.auth.credentials.Credentials): + if google_auth_httplib2 is None: + raise ValueError( + "Credentials from google.auth specified, but " + "google-api-python-client is unable to use these credentials " + "unless google-auth-httplib2 is installed. Please install " + "google-auth-httplib2." + ) + return google_auth_httplib2.AuthorizedHttp(credentials, http=build_http()) + else: + return credentials.authorize(build_http()) + + +def refresh_credentials(credentials): + # Refresh must use a new http instance, as the one associated with the + # credentials could be a AuthorizedHttp or an oauth2client-decorated + # Http instance which would cause a weird recursive loop of refreshing + # and likely tear a hole in spacetime. + refresh_http = httplib2.Http() + if HAS_GOOGLE_AUTH and isinstance(credentials, google.auth.credentials.Credentials): + request = google_auth_httplib2.Request(refresh_http) + return credentials.refresh(request) + else: + return credentials.refresh(refresh_http) + + +def apply_credentials(credentials, headers): + # oauth2client and google-auth have the same interface for this. + if not is_valid(credentials): + refresh_credentials(credentials) + return credentials.apply(headers) + + +def is_valid(credentials): + if HAS_GOOGLE_AUTH and isinstance(credentials, google.auth.credentials.Credentials): + return credentials.valid + else: + return ( + credentials.access_token is not None + and not credentials.access_token_expired + ) + + +def get_credentials_from_http(http): + if http is None: + return None + elif hasattr(http.request, "credentials"): + return http.request.credentials + elif hasattr(http, "credentials") and not isinstance( + http.credentials, httplib2.Credentials + ): + return http.credentials + else: + return None diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/googleapiclient/_helpers.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/googleapiclient/_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..17b8a171514eb144ba67b75de58f526b36680ea1 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/googleapiclient/_helpers.py @@ -0,0 +1,207 @@ +# Copyright 2015 Google Inc. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 commonly used utilities.""" + +import functools +import inspect +import logging +import urllib + +logger = logging.getLogger(__name__) + +POSITIONAL_WARNING = "WARNING" +POSITIONAL_EXCEPTION = "EXCEPTION" +POSITIONAL_IGNORE = "IGNORE" +POSITIONAL_SET = frozenset( + [POSITIONAL_WARNING, POSITIONAL_EXCEPTION, POSITIONAL_IGNORE] +) + +positional_parameters_enforcement = POSITIONAL_WARNING + +_SYM_LINK_MESSAGE = "File: {0}: Is a symbolic link." +_IS_DIR_MESSAGE = "{0}: Is a directory" +_MISSING_FILE_MESSAGE = "Cannot access {0}: No such file or directory" + + +def positional(max_positional_args): + """A decorator to declare that only the first N arguments may be positional. + + This decorator makes it easy to support Python 3 style keyword-only + parameters. For example, in Python 3 it is possible to write:: + + def fn(pos1, *, kwonly1=None, kwonly2=None): + ... + + All named parameters after ``*`` must be a keyword:: + + fn(10, 'kw1', 'kw2') # Raises exception. + fn(10, kwonly1='kw1') # Ok. + + Example + ^^^^^^^ + + To define a function like above, do:: + + @positional(1) + def fn(pos1, kwonly1=None, kwonly2=None): + ... + + If no default value is provided to a keyword argument, it becomes a + required keyword argument:: + + @positional(0) + def fn(required_kw): + ... + + This must be called with the keyword parameter:: + + fn() # Raises exception. + fn(10) # Raises exception. + fn(required_kw=10) # Ok. + + When defining instance or class methods always remember to account for + ``self`` and ``cls``:: + + class MyClass(object): + + @positional(2) + def my_method(self, pos1, kwonly1=None): + ... + + @classmethod + @positional(2) + def my_method(cls, pos1, kwonly1=None): + ... + + The positional decorator behavior is controlled by + ``_helpers.positional_parameters_enforcement``, which may be set to + ``POSITIONAL_EXCEPTION``, ``POSITIONAL_WARNING`` or + ``POSITIONAL_IGNORE`` to raise an exception, log a warning, or do + nothing, respectively, if a declaration is violated. + + Args: + max_positional_arguments: Maximum number of positional arguments. All + parameters after this index must be + keyword only. + + Returns: + A decorator that prevents using arguments after max_positional_args + from being used as positional parameters. + + Raises: + TypeError: if a keyword-only argument is provided as a positional + parameter, but only if + _helpers.positional_parameters_enforcement is set to + POSITIONAL_EXCEPTION. + """ + + def positional_decorator(wrapped): + @functools.wraps(wrapped) + def positional_wrapper(*args, **kwargs): + if len(args) > max_positional_args: + plural_s = "" + if max_positional_args != 1: + plural_s = "s" + message = ( + "{function}() takes at most {args_max} positional " + "argument{plural} ({args_given} given)".format( + function=wrapped.__name__, + args_max=max_positional_args, + args_given=len(args), + plural=plural_s, + ) + ) + if positional_parameters_enforcement == POSITIONAL_EXCEPTION: + raise TypeError(message) + elif positional_parameters_enforcement == POSITIONAL_WARNING: + logger.warning(message) + return wrapped(*args, **kwargs) + + return positional_wrapper + + if isinstance(max_positional_args, int): + return positional_decorator + else: + args, _, _, defaults, _, _, _ = inspect.getfullargspec(max_positional_args) + return positional(len(args) - len(defaults))(max_positional_args) + + +def parse_unique_urlencoded(content): + """Parses unique key-value parameters from urlencoded content. + + Args: + content: string, URL-encoded key-value pairs. + + Returns: + dict, The key-value pairs from ``content``. + + Raises: + ValueError: if one of the keys is repeated. + """ + urlencoded_params = urllib.parse.parse_qs(content) + params = {} + for key, value in urlencoded_params.items(): + if len(value) != 1: + msg = "URL-encoded content contains a repeated value:" "%s -> %s" % ( + key, + ", ".join(value), + ) + raise ValueError(msg) + params[key] = value[0] + return params + + +def update_query_params(uri, params): + """Updates a URI with new query parameters. + + If a given key from ``params`` is repeated in the ``uri``, then + the URI will be considered invalid and an error will occur. + + If the URI is valid, then each value from ``params`` will + replace the corresponding value in the query parameters (if + it exists). + + Args: + uri: string, A valid URI, with potential existing query parameters. + params: dict, A dictionary of query parameters. + + Returns: + The same URI but with the new query parameters added. + """ + parts = urllib.parse.urlparse(uri) + query_params = parse_unique_urlencoded(parts.query) + query_params.update(params) + new_query = urllib.parse.urlencode(query_params) + new_parts = parts._replace(query=new_query) + return urllib.parse.urlunparse(new_parts) + + +def _add_query_parameter(url, name, value): + """Adds a query parameter to a url. + + Replaces the current value if it already exists in the URL. + + Args: + url: string, url to add the query parameter to. + name: string, query parameter name. + value: string, query parameter value. + + Returns: + Updated query parameter. Does not update the url if value is None. + """ + if value is None: + return url + else: + return update_query_params(url, {name: value}) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/googleapiclient/channel.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/googleapiclient/channel.py new file mode 100644 index 0000000000000000000000000000000000000000..37bda1ea7e52630d2a775961816ea19d6174a62b --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/googleapiclient/channel.py @@ -0,0 +1,315 @@ +# Copyright 2014 Google Inc. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Channel notifications support. + +Classes and functions to support channel subscriptions and notifications +on those channels. + +Notes: + - This code is based on experimental APIs and is subject to change. + - Notification does not do deduplication of notification ids, that's up to + the receiver. + - Storing the Channel between calls is up to the caller. + + +Example setting up a channel: + + # Create a new channel that gets notifications via webhook. + channel = new_webhook_channel("https://example.com/my_web_hook") + + # Store the channel, keyed by 'channel.id'. Store it before calling the + # watch method because notifications may start arriving before the watch + # method returns. + ... + + resp = service.objects().watchAll( + bucket="some_bucket_id", body=channel.body()).execute() + channel.update(resp) + + # Store the channel, keyed by 'channel.id'. Store it after being updated + # since the resource_id value will now be correct, and that's needed to + # stop a subscription. + ... + + +An example Webhook implementation using webapp2. Note that webapp2 puts +headers in a case insensitive dictionary, as headers aren't guaranteed to +always be upper case. + + id = self.request.headers[X_GOOG_CHANNEL_ID] + + # Retrieve the channel by id. + channel = ... + + # Parse notification from the headers, including validating the id. + n = notification_from_headers(channel, self.request.headers) + + # Do app specific stuff with the notification here. + if n.resource_state == 'sync': + # Code to handle sync state. + elif n.resource_state == 'exists': + # Code to handle the exists state. + elif n.resource_state == 'not_exists': + # Code to handle the not exists state. + + +Example of unsubscribing. + + service.channels().stop(channel.body()).execute() +""" +from __future__ import absolute_import + +import datetime +import uuid + +from googleapiclient import _helpers as util +from googleapiclient import errors + +# The unix time epoch starts at midnight 1970. +EPOCH = datetime.datetime(1970, 1, 1) + +# Map the names of the parameters in the JSON channel description to +# the parameter names we use in the Channel class. +CHANNEL_PARAMS = { + "address": "address", + "id": "id", + "expiration": "expiration", + "params": "params", + "resourceId": "resource_id", + "resourceUri": "resource_uri", + "type": "type", + "token": "token", +} + +X_GOOG_CHANNEL_ID = "X-GOOG-CHANNEL-ID" +X_GOOG_MESSAGE_NUMBER = "X-GOOG-MESSAGE-NUMBER" +X_GOOG_RESOURCE_STATE = "X-GOOG-RESOURCE-STATE" +X_GOOG_RESOURCE_URI = "X-GOOG-RESOURCE-URI" +X_GOOG_RESOURCE_ID = "X-GOOG-RESOURCE-ID" + + +def _upper_header_keys(headers): + new_headers = {} + for k, v in headers.items(): + new_headers[k.upper()] = v + return new_headers + + +class Notification(object): + """A Notification from a Channel. + + Notifications are not usually constructed directly, but are returned + from functions like notification_from_headers(). + + Attributes: + message_number: int, The unique id number of this notification. + state: str, The state of the resource being monitored. + uri: str, The address of the resource being monitored. + resource_id: str, The unique identifier of the version of the resource at + this event. + """ + + @util.positional(5) + def __init__(self, message_number, state, resource_uri, resource_id): + """Notification constructor. + + Args: + message_number: int, The unique id number of this notification. + state: str, The state of the resource being monitored. Can be one + of "exists", "not_exists", or "sync". + resource_uri: str, The address of the resource being monitored. + resource_id: str, The identifier of the watched resource. + """ + self.message_number = message_number + self.state = state + self.resource_uri = resource_uri + self.resource_id = resource_id + + +class Channel(object): + """A Channel for notifications. + + Usually not constructed directly, instead it is returned from helper + functions like new_webhook_channel(). + + Attributes: + type: str, The type of delivery mechanism used by this channel. For + example, 'web_hook'. + id: str, A UUID for the channel. + token: str, An arbitrary string associated with the channel that + is delivered to the target address with each event delivered + over this channel. + address: str, The address of the receiving entity where events are + delivered. Specific to the channel type. + expiration: int, The time, in milliseconds from the epoch, when this + channel will expire. + params: dict, A dictionary of string to string, with additional parameters + controlling delivery channel behavior. + resource_id: str, An opaque id that identifies the resource that is + being watched. Stable across different API versions. + resource_uri: str, The canonicalized ID of the watched resource. + """ + + @util.positional(5) + def __init__( + self, + type, + id, + token, + address, + expiration=None, + params=None, + resource_id="", + resource_uri="", + ): + """Create a new Channel. + + In user code, this Channel constructor will not typically be called + manually since there are functions for creating channels for each specific + type with a more customized set of arguments to pass. + + Args: + type: str, The type of delivery mechanism used by this channel. For + example, 'web_hook'. + id: str, A UUID for the channel. + token: str, An arbitrary string associated with the channel that + is delivered to the target address with each event delivered + over this channel. + address: str, The address of the receiving entity where events are + delivered. Specific to the channel type. + expiration: int, The time, in milliseconds from the epoch, when this + channel will expire. + params: dict, A dictionary of string to string, with additional parameters + controlling delivery channel behavior. + resource_id: str, An opaque id that identifies the resource that is + being watched. Stable across different API versions. + resource_uri: str, The canonicalized ID of the watched resource. + """ + self.type = type + self.id = id + self.token = token + self.address = address + self.expiration = expiration + self.params = params + self.resource_id = resource_id + self.resource_uri = resource_uri + + def body(self): + """Build a body from the Channel. + + Constructs a dictionary that's appropriate for passing into watch() + methods as the value of body argument. + + Returns: + A dictionary representation of the channel. + """ + result = { + "id": self.id, + "token": self.token, + "type": self.type, + "address": self.address, + } + if self.params: + result["params"] = self.params + if self.resource_id: + result["resourceId"] = self.resource_id + if self.resource_uri: + result["resourceUri"] = self.resource_uri + if self.expiration: + result["expiration"] = self.expiration + + return result + + def update(self, resp): + """Update a channel with information from the response of watch(). + + When a request is sent to watch() a resource, the response returned + from the watch() request is a dictionary with updated channel information, + such as the resource_id, which is needed when stopping a subscription. + + Args: + resp: dict, The response from a watch() method. + """ + for json_name, param_name in CHANNEL_PARAMS.items(): + value = resp.get(json_name) + if value is not None: + setattr(self, param_name, value) + + +def notification_from_headers(channel, headers): + """Parse a notification from the webhook request headers, validate + the notification, and return a Notification object. + + Args: + channel: Channel, The channel that the notification is associated with. + headers: dict, A dictionary like object that contains the request headers + from the webhook HTTP request. + + Returns: + A Notification object. + + Raises: + errors.InvalidNotificationError if the notification is invalid. + ValueError if the X-GOOG-MESSAGE-NUMBER can't be converted to an int. + """ + headers = _upper_header_keys(headers) + channel_id = headers[X_GOOG_CHANNEL_ID] + if channel.id != channel_id: + raise errors.InvalidNotificationError( + "Channel id mismatch: %s != %s" % (channel.id, channel_id) + ) + else: + message_number = int(headers[X_GOOG_MESSAGE_NUMBER]) + state = headers[X_GOOG_RESOURCE_STATE] + resource_uri = headers[X_GOOG_RESOURCE_URI] + resource_id = headers[X_GOOG_RESOURCE_ID] + return Notification(message_number, state, resource_uri, resource_id) + + +@util.positional(2) +def new_webhook_channel(url, token=None, expiration=None, params=None): + """Create a new webhook Channel. + + Args: + url: str, URL to post notifications to. + token: str, An arbitrary string associated with the channel that + is delivered to the target address with each notification delivered + over this channel. + expiration: datetime.datetime, A time in the future when the channel + should expire. Can also be None if the subscription should use the + default expiration. Note that different services may have different + limits on how long a subscription lasts. Check the response from the + watch() method to see the value the service has set for an expiration + time. + params: dict, Extra parameters to pass on channel creation. Currently + not used for webhook channels. + """ + expiration_ms = 0 + if expiration: + delta = expiration - EPOCH + expiration_ms = ( + delta.microseconds / 1000 + (delta.seconds + delta.days * 24 * 3600) * 1000 + ) + if expiration_ms < 0: + expiration_ms = 0 + + return Channel( + "web_hook", + str(uuid.uuid4()), + token, + url, + expiration=expiration_ms, + params=params, + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/googleapiclient/discovery.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/googleapiclient/discovery.py new file mode 100644 index 0000000000000000000000000000000000000000..e1f7ee48df9e75c866d2610490888bceb35f25fa --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/googleapiclient/discovery.py @@ -0,0 +1,1669 @@ +# Copyright 2014 Google Inc. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Client for discovery based APIs. + +A client library for Google's discovery based APIs. +""" +from __future__ import absolute_import + +__author__ = "jcgregorio@google.com (Joe Gregorio)" +__all__ = ["build", "build_from_document", "fix_method_name", "key2param"] + +from collections import OrderedDict +import collections.abc + +# Standard library imports +import copy +from email.generator import BytesGenerator +from email.mime.multipart import MIMEMultipart +from email.mime.nonmultipart import MIMENonMultipart +import http.client as http_client +import io +import json +import keyword +import logging +import mimetypes +import os +import re +import urllib + +import google.api_core.client_options +from google.auth.exceptions import MutualTLSChannelError +from google.auth.transport import mtls +from google.oauth2 import service_account + +# Third-party imports +import httplib2 +import uritemplate + +try: + import google_auth_httplib2 +except ImportError: # pragma: NO COVER + google_auth_httplib2 = None + +try: + from google.api_core import universe + + HAS_UNIVERSE = True +except ImportError: + HAS_UNIVERSE = False + +# Local imports +from googleapiclient import _auth, mimeparse +from googleapiclient._helpers import _add_query_parameter, positional +from googleapiclient.errors import ( + HttpError, + InvalidJsonError, + MediaUploadSizeError, + UnacceptableMimeTypeError, + UnknownApiNameOrVersion, + UnknownFileType, +) +from googleapiclient.http import ( + BatchHttpRequest, + HttpMock, + HttpMockSequence, + HttpRequest, + MediaFileUpload, + MediaUpload, + build_http, +) +from googleapiclient.model import JsonModel, MediaModel, RawModel +from googleapiclient.schema import Schemas + +# The client library requires a version of httplib2 that supports RETRIES. +httplib2.RETRIES = 1 + +logger = logging.getLogger(__name__) + +URITEMPLATE = re.compile("{[^}]*}") +VARNAME = re.compile("[a-zA-Z0-9_-]+") +DISCOVERY_URI = ( + "https://www.googleapis.com/discovery/v1/apis/" "{api}/{apiVersion}/rest" +) +V1_DISCOVERY_URI = DISCOVERY_URI +V2_DISCOVERY_URI = ( + "https://{api}.googleapis.com/$discovery/rest?" "version={apiVersion}" +) +DEFAULT_METHOD_DOC = "A description of how to use this function" +HTTP_PAYLOAD_METHODS = frozenset(["PUT", "POST", "PATCH"]) + +_MEDIA_SIZE_BIT_SHIFTS = {"KB": 10, "MB": 20, "GB": 30, "TB": 40} +BODY_PARAMETER_DEFAULT_VALUE = {"description": "The request body.", "type": "object"} +MEDIA_BODY_PARAMETER_DEFAULT_VALUE = { + "description": ( + "The filename of the media request body, or an instance " + "of a MediaUpload object." + ), + "type": "string", + "required": False, +} +MEDIA_MIME_TYPE_PARAMETER_DEFAULT_VALUE = { + "description": ( + "The MIME type of the media request body, or an instance " + "of a MediaUpload object." + ), + "type": "string", + "required": False, +} +_PAGE_TOKEN_NAMES = ("pageToken", "nextPageToken") + +# Parameters controlling mTLS behavior. See https://google.aip.dev/auth/4114. +GOOGLE_API_USE_CLIENT_CERTIFICATE = "GOOGLE_API_USE_CLIENT_CERTIFICATE" +GOOGLE_API_USE_MTLS_ENDPOINT = "GOOGLE_API_USE_MTLS_ENDPOINT" +GOOGLE_CLOUD_UNIVERSE_DOMAIN = "GOOGLE_CLOUD_UNIVERSE_DOMAIN" +DEFAULT_UNIVERSE = "googleapis.com" +# Parameters accepted by the stack, but not visible via discovery. +# TODO(dhermes): Remove 'userip' in 'v2'. +STACK_QUERY_PARAMETERS = frozenset(["trace", "pp", "userip", "strict"]) +STACK_QUERY_PARAMETER_DEFAULT_VALUE = {"type": "string", "location": "query"} + + +class APICoreVersionError(ValueError): + def __init__(self): + message = ( + "google-api-core >= 2.18.0 is required to use the universe domain feature." + ) + super().__init__(message) + + +# Library-specific reserved words beyond Python keywords. +RESERVED_WORDS = frozenset(["body"]) + +# patch _write_lines to avoid munging '\r' into '\n' +# ( https://bugs.python.org/issue18886 https://bugs.python.org/issue19003 ) +class _BytesGenerator(BytesGenerator): + _write_lines = BytesGenerator.write + + +def fix_method_name(name): + """Fix method names to avoid '$' characters and reserved word conflicts. + + Args: + name: string, method name. + + Returns: + The name with '_' appended if the name is a reserved word and '$' and '-' + replaced with '_'. + """ + name = name.replace("$", "_").replace("-", "_") + if keyword.iskeyword(name) or name in RESERVED_WORDS: + return name + "_" + else: + return name + + +def key2param(key): + """Converts key names into parameter names. + + For example, converting "max-results" -> "max_results" + + Args: + key: string, the method key name. + + Returns: + A safe method name based on the key name. + """ + result = [] + key = list(key) + if not key[0].isalpha(): + result.append("x") + for c in key: + if c.isalnum(): + result.append(c) + else: + result.append("_") + + return "".join(result) + + +@positional(2) +def build( + serviceName, + version, + http=None, + discoveryServiceUrl=None, + developerKey=None, + model=None, + requestBuilder=HttpRequest, + credentials=None, + cache_discovery=True, + cache=None, + client_options=None, + adc_cert_path=None, + adc_key_path=None, + num_retries=1, + static_discovery=None, + always_use_jwt_access=False, +): + """Construct a Resource for interacting with an API. + + Construct a Resource object for interacting with an API. The serviceName and + version are the names from the Discovery service. + + Args: + serviceName: string, name of the service. + version: string, the version of the service. + http: httplib2.Http, An instance of httplib2.Http or something that acts + like it that HTTP requests will be made through. + discoveryServiceUrl: string, a URI Template that points to the location of + the discovery service. It should have two parameters {api} and + {apiVersion} that when filled in produce an absolute URI to the discovery + document for that service. + developerKey: string, key obtained from + https://code.google.com/apis/console. + model: googleapiclient.Model, converts to and from the wire format. + requestBuilder: googleapiclient.http.HttpRequest, encapsulator for an HTTP + request. + credentials: oauth2client.Credentials or + google.auth.credentials.Credentials, credentials to be used for + authentication. + cache_discovery: Boolean, whether or not to cache the discovery doc. + cache: googleapiclient.discovery_cache.base.CacheBase, an optional + cache object for the discovery documents. + client_options: Mapping object or google.api_core.client_options, client + options to set user options on the client. + (1) The API endpoint should be set through client_options. If API endpoint + is not set, `GOOGLE_API_USE_MTLS_ENDPOINT` environment variable can be used + to control which endpoint to use. + (2) client_cert_source is not supported, client cert should be provided using + client_encrypted_cert_source instead. In order to use the provided client + cert, `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable must be + set to `true`. + More details on the environment variables are here: + https://google.aip.dev/auth/4114 + adc_cert_path: str, client certificate file path to save the application + default client certificate for mTLS. This field is required if you want to + use the default client certificate. `GOOGLE_API_USE_CLIENT_CERTIFICATE` + environment variable must be set to `true` in order to use this field, + otherwise this field doesn't nothing. + More details on the environment variables are here: + https://google.aip.dev/auth/4114 + adc_key_path: str, client encrypted private key file path to save the + application default client encrypted private key for mTLS. This field is + required if you want to use the default client certificate. + `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable must be set to + `true` in order to use this field, otherwise this field doesn't nothing. + More details on the environment variables are here: + https://google.aip.dev/auth/4114 + num_retries: Integer, number of times to retry discovery with + randomized exponential backoff in case of intermittent/connection issues. + static_discovery: Boolean, whether or not to use the static discovery docs + included in the library. The default value for `static_discovery` depends + on the value of `discoveryServiceUrl`. `static_discovery` will default to + `True` when `discoveryServiceUrl` is also not provided, otherwise it will + default to `False`. + always_use_jwt_access: Boolean, whether always use self signed JWT for service + account credentials. This only applies to + google.oauth2.service_account.Credentials. + + Returns: + A Resource object with methods for interacting with the service. + + Raises: + google.auth.exceptions.MutualTLSChannelError: if there are any problems + setting up mutual TLS channel. + """ + params = {"api": serviceName, "apiVersion": version} + + # The default value for `static_discovery` depends on the value of + # `discoveryServiceUrl`. `static_discovery` will default to `True` when + # `discoveryServiceUrl` is also not provided, otherwise it will default to + # `False`. This is added for backwards compatability with + # google-api-python-client 1.x which does not support the `static_discovery` + # parameter. + if static_discovery is None: + if discoveryServiceUrl is None: + static_discovery = True + else: + static_discovery = False + + if http is None: + discovery_http = build_http() + else: + discovery_http = http + + service = None + + for discovery_url in _discovery_service_uri_options(discoveryServiceUrl, version): + requested_url = uritemplate.expand(discovery_url, params) + + try: + content = _retrieve_discovery_doc( + requested_url, + discovery_http, + cache_discovery, + serviceName, + version, + cache, + developerKey, + num_retries=num_retries, + static_discovery=static_discovery, + ) + service = build_from_document( + content, + base=discovery_url, + http=http, + developerKey=developerKey, + model=model, + requestBuilder=requestBuilder, + credentials=credentials, + client_options=client_options, + adc_cert_path=adc_cert_path, + adc_key_path=adc_key_path, + always_use_jwt_access=always_use_jwt_access, + ) + break # exit if a service was created + except HttpError as e: + if e.resp.status == http_client.NOT_FOUND: + continue + else: + raise e + + # If discovery_http was created by this function, we are done with it + # and can safely close it + if http is None: + discovery_http.close() + + if service is None: + raise UnknownApiNameOrVersion("name: %s version: %s" % (serviceName, version)) + else: + return service + + +def _discovery_service_uri_options(discoveryServiceUrl, version): + """ + Returns Discovery URIs to be used for attempting to build the API Resource. + + Args: + discoveryServiceUrl: + string, the Original Discovery Service URL preferred by the customer. + version: + string, API Version requested + + Returns: + A list of URIs to be tried for the Service Discovery, in order. + """ + + if discoveryServiceUrl is not None: + return [discoveryServiceUrl] + if version is None: + # V1 Discovery won't work if the requested version is None + logger.warning( + "Discovery V1 does not support empty versions. Defaulting to V2..." + ) + return [V2_DISCOVERY_URI] + else: + return [DISCOVERY_URI, V2_DISCOVERY_URI] + + +def _retrieve_discovery_doc( + url, + http, + cache_discovery, + serviceName, + version, + cache=None, + developerKey=None, + num_retries=1, + static_discovery=True, +): + """Retrieves the discovery_doc from cache or the internet. + + Args: + url: string, the URL of the discovery document. + http: httplib2.Http, An instance of httplib2.Http or something that acts + like it through which HTTP requests will be made. + cache_discovery: Boolean, whether or not to cache the discovery doc. + serviceName: string, name of the service. + version: string, the version of the service. + cache: googleapiclient.discovery_cache.base.Cache, an optional cache + object for the discovery documents. + developerKey: string, Key for controlling API usage, generated + from the API Console. + num_retries: Integer, number of times to retry discovery with + randomized exponential backoff in case of intermittent/connection issues. + static_discovery: Boolean, whether or not to use the static discovery docs + included in the library. + + Returns: + A unicode string representation of the discovery document. + """ + from . import discovery_cache + + if cache_discovery: + if cache is None: + cache = discovery_cache.autodetect() + if cache: + content = cache.get(url) + if content: + return content + + # When `static_discovery=True`, use static discovery artifacts included + # with the library + if static_discovery: + content = discovery_cache.get_static_doc(serviceName, version) + if content: + return content + else: + raise UnknownApiNameOrVersion( + "name: %s version: %s" % (serviceName, version) + ) + + actual_url = url + # REMOTE_ADDR is defined by the CGI spec [RFC3875] as the environment + # variable that contains the network address of the client sending the + # request. If it exists then add that to the request for the discovery + # document to avoid exceeding the quota on discovery requests. + if "REMOTE_ADDR" in os.environ: + actual_url = _add_query_parameter(url, "userIp", os.environ["REMOTE_ADDR"]) + if developerKey: + actual_url = _add_query_parameter(url, "key", developerKey) + logger.debug("URL being requested: GET %s", actual_url) + + # Execute this request with retries build into HttpRequest + # Note that it will already raise an error if we don't get a 2xx response + req = HttpRequest(http, HttpRequest.null_postproc, actual_url) + resp, content = req.execute(num_retries=num_retries) + + try: + content = content.decode("utf-8") + except AttributeError: + pass + + try: + service = json.loads(content) + except ValueError as e: + logger.error("Failed to parse as JSON: " + content) + raise InvalidJsonError() + if cache_discovery and cache: + cache.set(url, content) + return content + + +def _check_api_core_compatible_with_credentials_universe(credentials): + if not HAS_UNIVERSE: + credentials_universe = getattr(credentials, "universe_domain", None) + if credentials_universe and credentials_universe != DEFAULT_UNIVERSE: + raise APICoreVersionError + + +@positional(1) +def build_from_document( + service, + base=None, + future=None, + http=None, + developerKey=None, + model=None, + requestBuilder=HttpRequest, + credentials=None, + client_options=None, + adc_cert_path=None, + adc_key_path=None, + always_use_jwt_access=False, +): + """Create a Resource for interacting with an API. + + Same as `build()`, but constructs the Resource object from a discovery + document that is it given, as opposed to retrieving one over HTTP. + + Args: + service: string or object, the JSON discovery document describing the API. + The value passed in may either be the JSON string or the deserialized + JSON. + base: string, base URI for all HTTP requests, usually the discovery URI. + This parameter is no longer used as rootUrl and servicePath are included + within the discovery document. (deprecated) + future: string, discovery document with future capabilities (deprecated). + http: httplib2.Http, An instance of httplib2.Http or something that acts + like it that HTTP requests will be made through. + developerKey: string, Key for controlling API usage, generated + from the API Console. + model: Model class instance that serializes and de-serializes requests and + responses. + requestBuilder: Takes an http request and packages it up to be executed. + credentials: oauth2client.Credentials or + google.auth.credentials.Credentials, credentials to be used for + authentication. + client_options: Mapping object or google.api_core.client_options, client + options to set user options on the client. + (1) The API endpoint should be set through client_options. If API endpoint + is not set, `GOOGLE_API_USE_MTLS_ENDPOINT` environment variable can be used + to control which endpoint to use. + (2) client_cert_source is not supported, client cert should be provided using + client_encrypted_cert_source instead. In order to use the provided client + cert, `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable must be + set to `true`. + More details on the environment variables are here: + https://google.aip.dev/auth/4114 + adc_cert_path: str, client certificate file path to save the application + default client certificate for mTLS. This field is required if you want to + use the default client certificate. `GOOGLE_API_USE_CLIENT_CERTIFICATE` + environment variable must be set to `true` in order to use this field, + otherwise this field doesn't nothing. + More details on the environment variables are here: + https://google.aip.dev/auth/4114 + adc_key_path: str, client encrypted private key file path to save the + application default client encrypted private key for mTLS. This field is + required if you want to use the default client certificate. + `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable must be set to + `true` in order to use this field, otherwise this field doesn't nothing. + More details on the environment variables are here: + https://google.aip.dev/auth/4114 + always_use_jwt_access: Boolean, whether always use self signed JWT for service + account credentials. This only applies to + google.oauth2.service_account.Credentials. + + Returns: + A Resource object with methods for interacting with the service. + + Raises: + google.auth.exceptions.MutualTLSChannelError: if there are any problems + setting up mutual TLS channel. + """ + + if client_options is None: + client_options = google.api_core.client_options.ClientOptions() + if isinstance(client_options, collections.abc.Mapping): + client_options = google.api_core.client_options.from_dict(client_options) + + if http is not None: + # if http is passed, the user cannot provide credentials + banned_options = [ + (credentials, "credentials"), + (client_options.credentials_file, "client_options.credentials_file"), + ] + for option, name in banned_options: + if option is not None: + raise ValueError( + "Arguments http and {} are mutually exclusive".format(name) + ) + + if isinstance(service, str): + service = json.loads(service) + elif isinstance(service, bytes): + service = json.loads(service.decode("utf-8")) + + if "rootUrl" not in service and isinstance(http, (HttpMock, HttpMockSequence)): + logger.error( + "You are using HttpMock or HttpMockSequence without" + + "having the service discovery doc in cache. Try calling " + + "build() without mocking once first to populate the " + + "cache." + ) + raise InvalidJsonError() + + # If an API Endpoint is provided on client options, use that as the base URL + base = urllib.parse.urljoin(service["rootUrl"], service["servicePath"]) + universe_domain = None + if HAS_UNIVERSE: + universe_domain_env = os.getenv(GOOGLE_CLOUD_UNIVERSE_DOMAIN, None) + universe_domain = universe.determine_domain( + client_options.universe_domain, universe_domain_env + ) + base = base.replace(universe.DEFAULT_UNIVERSE, universe_domain) + else: + client_universe = getattr(client_options, "universe_domain", None) + if client_universe: + raise APICoreVersionError + + audience_for_self_signed_jwt = base + if client_options.api_endpoint: + base = client_options.api_endpoint + + schema = Schemas(service) + + # If the http client is not specified, then we must construct an http client + # to make requests. If the service has scopes, then we also need to setup + # authentication. + if http is None: + # Does the service require scopes? + scopes = list( + service.get("auth", {}).get("oauth2", {}).get("scopes", {}).keys() + ) + + # If so, then the we need to setup authentication if no developerKey is + # specified. + if scopes and not developerKey: + # Make sure the user didn't pass multiple credentials + if client_options.credentials_file and credentials: + raise google.api_core.exceptions.DuplicateCredentialArgs( + "client_options.credentials_file and credentials are mutually exclusive." + ) + # Check for credentials file via client options + if client_options.credentials_file: + credentials = _auth.credentials_from_file( + client_options.credentials_file, + scopes=client_options.scopes, + quota_project_id=client_options.quota_project_id, + ) + # If the user didn't pass in credentials, attempt to acquire application + # default credentials. + if credentials is None: + credentials = _auth.default_credentials( + scopes=client_options.scopes, + quota_project_id=client_options.quota_project_id, + ) + + # Check google-api-core >= 2.18.0 if credentials' universe != "googleapis.com". + _check_api_core_compatible_with_credentials_universe(credentials) + + # The credentials need to be scoped. + # If the user provided scopes via client_options don't override them + if not client_options.scopes: + credentials = _auth.with_scopes(credentials, scopes) + + # For google-auth service account credentials, enable self signed JWT if + # always_use_jwt_access is true. + if ( + credentials + and isinstance(credentials, service_account.Credentials) + and always_use_jwt_access + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(always_use_jwt_access) + credentials._create_self_signed_jwt(audience_for_self_signed_jwt) + + # If credentials are provided, create an authorized http instance; + # otherwise, skip authentication. + if credentials: + http = _auth.authorized_http(credentials) + + # If the service doesn't require scopes then there is no need for + # authentication. + else: + http = build_http() + + # Obtain client cert and create mTLS http channel if cert exists. + client_cert_to_use = None + if hasattr(mtls, "should_use_client_cert"): + use_client_cert = mtls.should_use_client_cert() + else: + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + use_client_cert = use_client_cert_str == "true" + if use_client_cert_str not in ("true", "false"): + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_CLIENT_CERTIFICATE value. Accepted values: true, false" + ) + if client_options and client_options.client_cert_source: + raise MutualTLSChannelError( + "ClientOptions.client_cert_source is not supported, please use ClientOptions.client_encrypted_cert_source." + ) + if use_client_cert: + if ( + client_options + and hasattr(client_options, "client_encrypted_cert_source") + and client_options.client_encrypted_cert_source + ): + client_cert_to_use = client_options.client_encrypted_cert_source + elif ( + adc_cert_path and adc_key_path and mtls.has_default_client_cert_source() + ): + client_cert_to_use = mtls.default_client_encrypted_cert_source( + adc_cert_path, adc_key_path + ) + if client_cert_to_use: + cert_path, key_path, passphrase = client_cert_to_use() + + # The http object we built could be google_auth_httplib2.AuthorizedHttp + # or httplib2.Http. In the first case we need to extract the wrapped + # httplib2.Http object from google_auth_httplib2.AuthorizedHttp. + http_channel = ( + http.http + if google_auth_httplib2 + and isinstance(http, google_auth_httplib2.AuthorizedHttp) + else http + ) + http_channel.add_certificate(key_path, cert_path, "", passphrase) + + # If user doesn't provide api endpoint via client options, decide which + # api endpoint to use. + if "mtlsRootUrl" in service and ( + not client_options or not client_options.api_endpoint + ): + mtls_endpoint = urllib.parse.urljoin( + service["mtlsRootUrl"], service["servicePath"] + ) + use_mtls_endpoint = os.getenv(GOOGLE_API_USE_MTLS_ENDPOINT, "auto") + + if not use_mtls_endpoint in ("never", "auto", "always"): + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + ) + + # Switch to mTLS endpoint, if environment variable is "always", or + # environment varibable is "auto" and client cert exists. + if use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_to_use + ): + if HAS_UNIVERSE and universe_domain != universe.DEFAULT_UNIVERSE: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {universe.DEFAULT_UNIVERSE}." + ) + base = mtls_endpoint + else: + # Check google-api-core >= 2.18.0 if credentials' universe != "googleapis.com". + http_credentials = getattr(http, "credentials", None) + _check_api_core_compatible_with_credentials_universe(http_credentials) + + if model is None: + features = service.get("features", []) + model = JsonModel("dataWrapper" in features) + + return Resource( + http=http, + baseUrl=base, + model=model, + developerKey=developerKey, + requestBuilder=requestBuilder, + resourceDesc=service, + rootDesc=service, + schema=schema, + universe_domain=universe_domain, + ) + + +def _cast(value, schema_type): + """Convert value to a string based on JSON Schema type. + + See http://tools.ietf.org/html/draft-zyp-json-schema-03 for more details on + JSON Schema. + + Args: + value: any, the value to convert + schema_type: string, the type that value should be interpreted as + + Returns: + A string representation of 'value' based on the schema_type. + """ + if schema_type == "string": + if type(value) == type("") or type(value) == type(""): + return value + else: + return str(value) + elif schema_type == "integer": + return str(int(value)) + elif schema_type == "number": + return str(float(value)) + elif schema_type == "boolean": + return str(bool(value)).lower() + else: + if type(value) == type("") or type(value) == type(""): + return value + else: + return str(value) + + +def _media_size_to_long(maxSize): + """Convert a string media size, such as 10GB or 3TB into an integer. + + Args: + maxSize: string, size as a string, such as 2MB or 7GB. + + Returns: + The size as an integer value. + """ + if len(maxSize) < 2: + return 0 + units = maxSize[-2:].upper() + bit_shift = _MEDIA_SIZE_BIT_SHIFTS.get(units) + if bit_shift is not None: + return int(maxSize[:-2]) << bit_shift + else: + return int(maxSize) + + +def _media_path_url_from_info(root_desc, path_url): + """Creates an absolute media path URL. + + Constructed using the API root URI and service path from the discovery + document and the relative path for the API method. + + Args: + root_desc: Dictionary; the entire original deserialized discovery document. + path_url: String; the relative URL for the API method. Relative to the API + root, which is specified in the discovery document. + + Returns: + String; the absolute URI for media upload for the API method. + """ + return "%(root)supload/%(service_path)s%(path)s" % { + "root": root_desc["rootUrl"], + "service_path": root_desc["servicePath"], + "path": path_url, + } + + +def _fix_up_parameters(method_desc, root_desc, http_method, schema): + """Updates parameters of an API method with values specific to this library. + + Specifically, adds whatever global parameters are specified by the API to the + parameters for the individual method. Also adds parameters which don't + appear in the discovery document, but are available to all discovery based + APIs (these are listed in STACK_QUERY_PARAMETERS). + + SIDE EFFECTS: This updates the parameters dictionary object in the method + description. + + Args: + method_desc: Dictionary with metadata describing an API method. Value comes + from the dictionary of methods stored in the 'methods' key in the + deserialized discovery document. + root_desc: Dictionary; the entire original deserialized discovery document. + http_method: String; the HTTP method used to call the API method described + in method_desc. + schema: Object, mapping of schema names to schema descriptions. + + Returns: + The updated Dictionary stored in the 'parameters' key of the method + description dictionary. + """ + parameters = method_desc.setdefault("parameters", {}) + + # Add in the parameters common to all methods. + for name, description in root_desc.get("parameters", {}).items(): + parameters[name] = description + + # Add in undocumented query parameters. + for name in STACK_QUERY_PARAMETERS: + parameters[name] = STACK_QUERY_PARAMETER_DEFAULT_VALUE.copy() + + # Add 'body' (our own reserved word) to parameters if the method supports + # a request payload. + if http_method in HTTP_PAYLOAD_METHODS and "request" in method_desc: + body = BODY_PARAMETER_DEFAULT_VALUE.copy() + body.update(method_desc["request"]) + parameters["body"] = body + + return parameters + + +def _fix_up_media_upload(method_desc, root_desc, path_url, parameters): + """Adds 'media_body' and 'media_mime_type' parameters if supported by method. + + SIDE EFFECTS: If there is a 'mediaUpload' in the method description, adds + 'media_upload' key to parameters. + + Args: + method_desc: Dictionary with metadata describing an API method. Value comes + from the dictionary of methods stored in the 'methods' key in the + deserialized discovery document. + root_desc: Dictionary; the entire original deserialized discovery document. + path_url: String; the relative URL for the API method. Relative to the API + root, which is specified in the discovery document. + parameters: A dictionary describing method parameters for method described + in method_desc. + + Returns: + Triple (accept, max_size, media_path_url) where: + - accept is a list of strings representing what content types are + accepted for media upload. Defaults to empty list if not in the + discovery document. + - max_size is a long representing the max size in bytes allowed for a + media upload. Defaults to 0L if not in the discovery document. + - media_path_url is a String; the absolute URI for media upload for the + API method. Constructed using the API root URI and service path from + the discovery document and the relative path for the API method. If + media upload is not supported, this is None. + """ + media_upload = method_desc.get("mediaUpload", {}) + accept = media_upload.get("accept", []) + max_size = _media_size_to_long(media_upload.get("maxSize", "")) + media_path_url = None + + if media_upload: + media_path_url = _media_path_url_from_info(root_desc, path_url) + parameters["media_body"] = MEDIA_BODY_PARAMETER_DEFAULT_VALUE.copy() + parameters["media_mime_type"] = MEDIA_MIME_TYPE_PARAMETER_DEFAULT_VALUE.copy() + + return accept, max_size, media_path_url + + +def _fix_up_method_description(method_desc, root_desc, schema): + """Updates a method description in a discovery document. + + SIDE EFFECTS: Changes the parameters dictionary in the method description with + extra parameters which are used locally. + + Args: + method_desc: Dictionary with metadata describing an API method. Value comes + from the dictionary of methods stored in the 'methods' key in the + deserialized discovery document. + root_desc: Dictionary; the entire original deserialized discovery document. + schema: Object, mapping of schema names to schema descriptions. + + Returns: + Tuple (path_url, http_method, method_id, accept, max_size, media_path_url) + where: + - path_url is a String; the relative URL for the API method. Relative to + the API root, which is specified in the discovery document. + - http_method is a String; the HTTP method used to call the API method + described in the method description. + - method_id is a String; the name of the RPC method associated with the + API method, and is in the method description in the 'id' key. + - accept is a list of strings representing what content types are + accepted for media upload. Defaults to empty list if not in the + discovery document. + - max_size is a long representing the max size in bytes allowed for a + media upload. Defaults to 0L if not in the discovery document. + - media_path_url is a String; the absolute URI for media upload for the + API method. Constructed using the API root URI and service path from + the discovery document and the relative path for the API method. If + media upload is not supported, this is None. + """ + path_url = method_desc["path"] + http_method = method_desc["httpMethod"] + method_id = method_desc["id"] + + parameters = _fix_up_parameters(method_desc, root_desc, http_method, schema) + # Order is important. `_fix_up_media_upload` needs `method_desc` to have a + # 'parameters' key and needs to know if there is a 'body' parameter because it + # also sets a 'media_body' parameter. + accept, max_size, media_path_url = _fix_up_media_upload( + method_desc, root_desc, path_url, parameters + ) + + return path_url, http_method, method_id, accept, max_size, media_path_url + + +def _fix_up_media_path_base_url(media_path_url, base_url): + """ + Update the media upload base url if its netloc doesn't match base url netloc. + + This can happen in case the base url was overridden by + client_options.api_endpoint. + + Args: + media_path_url: String; the absolute URI for media upload. + base_url: string, base URL for the API. All requests are relative to this URI. + + Returns: + String; the absolute URI for media upload. + """ + parsed_media_url = urllib.parse.urlparse(media_path_url) + parsed_base_url = urllib.parse.urlparse(base_url) + if parsed_media_url.netloc == parsed_base_url.netloc: + return media_path_url + return urllib.parse.urlunparse( + parsed_media_url._replace(netloc=parsed_base_url.netloc) + ) + + +def _urljoin(base, url): + """Custom urljoin replacement supporting : before / in url.""" + # In general, it's unsafe to simply join base and url. However, for + # the case of discovery documents, we know: + # * base will never contain params, query, or fragment + # * url will never contain a scheme or net_loc. + # In general, this means we can safely join on /; we just need to + # ensure we end up with precisely one / joining base and url. The + # exception here is the case of media uploads, where url will be an + # absolute url. + if url.startswith("http://") or url.startswith("https://"): + return urllib.parse.urljoin(base, url) + new_base = base if base.endswith("/") else base + "/" + new_url = url[1:] if url.startswith("/") else url + return new_base + new_url + + +# TODO(dhermes): Convert this class to ResourceMethod and make it callable +class ResourceMethodParameters(object): + """Represents the parameters associated with a method. + + Attributes: + argmap: Map from method parameter name (string) to query parameter name + (string). + required_params: List of required parameters (represented by parameter + name as string). + repeated_params: List of repeated parameters (represented by parameter + name as string). + pattern_params: Map from method parameter name (string) to regular + expression (as a string). If the pattern is set for a parameter, the + value for that parameter must match the regular expression. + query_params: List of parameters (represented by parameter name as string) + that will be used in the query string. + path_params: Set of parameters (represented by parameter name as string) + that will be used in the base URL path. + param_types: Map from method parameter name (string) to parameter type. Type + can be any valid JSON schema type; valid values are 'any', 'array', + 'boolean', 'integer', 'number', 'object', or 'string'. Reference: + http://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.1 + enum_params: Map from method parameter name (string) to list of strings, + where each list of strings is the list of acceptable enum values. + """ + + def __init__(self, method_desc): + """Constructor for ResourceMethodParameters. + + Sets default values and defers to set_parameters to populate. + + Args: + method_desc: Dictionary with metadata describing an API method. Value + comes from the dictionary of methods stored in the 'methods' key in + the deserialized discovery document. + """ + self.argmap = {} + self.required_params = [] + self.repeated_params = [] + self.pattern_params = {} + self.query_params = [] + # TODO(dhermes): Change path_params to a list if the extra URITEMPLATE + # parsing is gotten rid of. + self.path_params = set() + self.param_types = {} + self.enum_params = {} + + self.set_parameters(method_desc) + + def set_parameters(self, method_desc): + """Populates maps and lists based on method description. + + Iterates through each parameter for the method and parses the values from + the parameter dictionary. + + Args: + method_desc: Dictionary with metadata describing an API method. Value + comes from the dictionary of methods stored in the 'methods' key in + the deserialized discovery document. + """ + parameters = method_desc.get("parameters", {}) + sorted_parameters = OrderedDict(sorted(parameters.items())) + for arg, desc in sorted_parameters.items(): + param = key2param(arg) + self.argmap[param] = arg + + if desc.get("pattern"): + self.pattern_params[param] = desc["pattern"] + if desc.get("enum"): + self.enum_params[param] = desc["enum"] + if desc.get("required"): + self.required_params.append(param) + if desc.get("repeated"): + self.repeated_params.append(param) + if desc.get("location") == "query": + self.query_params.append(param) + if desc.get("location") == "path": + self.path_params.add(param) + self.param_types[param] = desc.get("type", "string") + + # TODO(dhermes): Determine if this is still necessary. Discovery based APIs + # should have all path parameters already marked with + # 'location: path'. + for match in URITEMPLATE.finditer(method_desc["path"]): + for namematch in VARNAME.finditer(match.group(0)): + name = key2param(namematch.group(0)) + self.path_params.add(name) + if name in self.query_params: + self.query_params.remove(name) + + +def createMethod(methodName, methodDesc, rootDesc, schema): + """Creates a method for attaching to a Resource. + + Args: + methodName: string, name of the method to use. + methodDesc: object, fragment of deserialized discovery document that + describes the method. + rootDesc: object, the entire deserialized discovery document. + schema: object, mapping of schema names to schema descriptions. + """ + methodName = fix_method_name(methodName) + ( + pathUrl, + httpMethod, + methodId, + accept, + maxSize, + mediaPathUrl, + ) = _fix_up_method_description(methodDesc, rootDesc, schema) + + parameters = ResourceMethodParameters(methodDesc) + + def method(self, **kwargs): + # Don't bother with doc string, it will be over-written by createMethod. + + # Validate credentials for the configured universe. + self._validate_credentials() + + for name in kwargs: + if name not in parameters.argmap: + raise TypeError("Got an unexpected keyword argument {}".format(name)) + + # Remove args that have a value of None. + keys = list(kwargs.keys()) + for name in keys: + if kwargs[name] is None: + del kwargs[name] + + for name in parameters.required_params: + if name not in kwargs: + # temporary workaround for non-paging methods incorrectly requiring + # page token parameter (cf. drive.changes.watch vs. drive.changes.list) + if name not in _PAGE_TOKEN_NAMES or _findPageTokenName( + _methodProperties(methodDesc, schema, "response") + ): + raise TypeError('Missing required parameter "%s"' % name) + + for name, regex in parameters.pattern_params.items(): + if name in kwargs: + if isinstance(kwargs[name], str): + pvalues = [kwargs[name]] + else: + pvalues = kwargs[name] + for pvalue in pvalues: + if re.match(regex, pvalue) is None: + raise TypeError( + 'Parameter "%s" value "%s" does not match the pattern "%s"' + % (name, pvalue, regex) + ) + + for name, enums in parameters.enum_params.items(): + if name in kwargs: + # We need to handle the case of a repeated enum + # name differently, since we want to handle both + # arg='value' and arg=['value1', 'value2'] + if name in parameters.repeated_params and not isinstance( + kwargs[name], str + ): + values = kwargs[name] + else: + values = [kwargs[name]] + for value in values: + if value not in enums: + raise TypeError( + 'Parameter "%s" value "%s" is not an allowed value in "%s"' + % (name, value, str(enums)) + ) + + actual_query_params = {} + actual_path_params = {} + for key, value in kwargs.items(): + to_type = parameters.param_types.get(key, "string") + # For repeated parameters we cast each member of the list. + if key in parameters.repeated_params and type(value) == type([]): + cast_value = [_cast(x, to_type) for x in value] + else: + cast_value = _cast(value, to_type) + if key in parameters.query_params: + actual_query_params[parameters.argmap[key]] = cast_value + if key in parameters.path_params: + actual_path_params[parameters.argmap[key]] = cast_value + body_value = kwargs.get("body", None) + media_filename = kwargs.get("media_body", None) + media_mime_type = kwargs.get("media_mime_type", None) + + if self._developerKey: + actual_query_params["key"] = self._developerKey + + model = self._model + if methodName.endswith("_media"): + model = MediaModel() + elif "response" not in methodDesc: + model = RawModel() + + api_version = methodDesc.get("apiVersion", None) + + headers = {} + headers, params, query, body = model.request( + headers, actual_path_params, actual_query_params, body_value, api_version + ) + + expanded_url = uritemplate.expand(pathUrl, params) + url = _urljoin(self._baseUrl, expanded_url + query) + + resumable = None + multipart_boundary = "" + + if media_filename: + # Ensure we end up with a valid MediaUpload object. + if isinstance(media_filename, str): + if media_mime_type is None: + logger.warning( + "media_mime_type argument not specified: trying to auto-detect for %s", + media_filename, + ) + media_mime_type, _ = mimetypes.guess_type(media_filename) + if media_mime_type is None: + raise UnknownFileType(media_filename) + if not mimeparse.best_match([media_mime_type], ",".join(accept)): + raise UnacceptableMimeTypeError(media_mime_type) + media_upload = MediaFileUpload(media_filename, mimetype=media_mime_type) + elif isinstance(media_filename, MediaUpload): + media_upload = media_filename + else: + raise TypeError("media_filename must be str or MediaUpload.") + + # Check the maxSize + if media_upload.size() is not None and media_upload.size() > maxSize > 0: + raise MediaUploadSizeError("Media larger than: %s" % maxSize) + + # Use the media path uri for media uploads + expanded_url = uritemplate.expand(mediaPathUrl, params) + url = _urljoin(self._baseUrl, expanded_url + query) + url = _fix_up_media_path_base_url(url, self._baseUrl) + if media_upload.resumable(): + url = _add_query_parameter(url, "uploadType", "resumable") + + if media_upload.resumable(): + # This is all we need to do for resumable, if the body exists it gets + # sent in the first request, otherwise an empty body is sent. + resumable = media_upload + else: + # A non-resumable upload + if body is None: + # This is a simple media upload + headers["content-type"] = media_upload.mimetype() + body = media_upload.getbytes(0, media_upload.size()) + url = _add_query_parameter(url, "uploadType", "media") + else: + # This is a multipart/related upload. + msgRoot = MIMEMultipart("related") + # msgRoot should not write out it's own headers + setattr(msgRoot, "_write_headers", lambda self: None) + + # attach the body as one part + msg = MIMENonMultipart(*headers["content-type"].split("/")) + msg.set_payload(body) + msgRoot.attach(msg) + + # attach the media as the second part + msg = MIMENonMultipart(*media_upload.mimetype().split("/")) + msg["Content-Transfer-Encoding"] = "binary" + + payload = media_upload.getbytes(0, media_upload.size()) + msg.set_payload(payload) + msgRoot.attach(msg) + # encode the body: note that we can't use `as_string`, because + # it plays games with `From ` lines. + fp = io.BytesIO() + g = _BytesGenerator(fp, mangle_from_=False) + g.flatten(msgRoot, unixfrom=False) + body = fp.getvalue() + + multipart_boundary = msgRoot.get_boundary() + headers["content-type"] = ( + "multipart/related; " 'boundary="%s"' + ) % multipart_boundary + url = _add_query_parameter(url, "uploadType", "multipart") + + logger.debug("URL being requested: %s %s" % (httpMethod, url)) + return self._requestBuilder( + self._http, + model.response, + url, + method=httpMethod, + body=body, + headers=headers, + methodId=methodId, + resumable=resumable, + ) + + docs = [methodDesc.get("description", DEFAULT_METHOD_DOC), "\n\n"] + if len(parameters.argmap) > 0: + docs.append("Args:\n") + + # Skip undocumented params and params common to all methods. + skip_parameters = list(rootDesc.get("parameters", {}).keys()) + skip_parameters.extend(STACK_QUERY_PARAMETERS) + + all_args = list(parameters.argmap.keys()) + args_ordered = [key2param(s) for s in methodDesc.get("parameterOrder", [])] + + # Move body to the front of the line. + if "body" in all_args: + args_ordered.append("body") + + for name in sorted(all_args): + if name not in args_ordered: + args_ordered.append(name) + + for arg in args_ordered: + if arg in skip_parameters: + continue + + repeated = "" + if arg in parameters.repeated_params: + repeated = " (repeated)" + required = "" + if arg in parameters.required_params: + required = " (required)" + paramdesc = methodDesc["parameters"][parameters.argmap[arg]] + paramdoc = paramdesc.get("description", "A parameter") + if "$ref" in paramdesc: + docs.append( + (" %s: object, %s%s%s\n The object takes the form of:\n\n%s\n\n") + % ( + arg, + paramdoc, + required, + repeated, + schema.prettyPrintByName(paramdesc["$ref"]), + ) + ) + else: + paramtype = paramdesc.get("type", "string") + docs.append( + " %s: %s, %s%s%s\n" % (arg, paramtype, paramdoc, required, repeated) + ) + enum = paramdesc.get("enum", []) + enumDesc = paramdesc.get("enumDescriptions", []) + if enum and enumDesc: + docs.append(" Allowed values\n") + for (name, desc) in zip(enum, enumDesc): + docs.append(" %s - %s\n" % (name, desc)) + if "response" in methodDesc: + if methodName.endswith("_media"): + docs.append("\nReturns:\n The media object as a string.\n\n ") + else: + docs.append("\nReturns:\n An object of the form:\n\n ") + docs.append(schema.prettyPrintSchema(methodDesc["response"])) + + setattr(method, "__doc__", "".join(docs)) + return (methodName, method) + + +def createNextMethod( + methodName, + pageTokenName="pageToken", + nextPageTokenName="nextPageToken", + isPageTokenParameter=True, +): + """Creates any _next methods for attaching to a Resource. + + The _next methods allow for easy iteration through list() responses. + + Args: + methodName: string, name of the method to use. + pageTokenName: string, name of request page token field. + nextPageTokenName: string, name of response page token field. + isPageTokenParameter: Boolean, True if request page token is a query + parameter, False if request page token is a field of the request body. + """ + methodName = fix_method_name(methodName) + + def methodNext(self, previous_request, previous_response): + """Retrieves the next page of results. + + Args: + previous_request: The request for the previous page. (required) + previous_response: The response from the request for the previous page. (required) + + Returns: + A request object that you can call 'execute()' on to request the next + page. Returns None if there are no more items in the collection. + """ + # Retrieve nextPageToken from previous_response + # Use as pageToken in previous_request to create new request. + + nextPageToken = previous_response.get(nextPageTokenName, None) + if not nextPageToken: + return None + + request = copy.copy(previous_request) + + if isPageTokenParameter: + # Replace pageToken value in URI + request.uri = _add_query_parameter( + request.uri, pageTokenName, nextPageToken + ) + logger.debug("Next page request URL: %s %s" % (methodName, request.uri)) + else: + # Replace pageToken value in request body + model = self._model + body = model.deserialize(request.body) + body[pageTokenName] = nextPageToken + request.body = model.serialize(body) + request.body_size = len(request.body) + if "content-length" in request.headers: + del request.headers["content-length"] + logger.debug("Next page request body: %s %s" % (methodName, body)) + + return request + + return (methodName, methodNext) + + +class Resource(object): + """A class for interacting with a resource.""" + + def __init__( + self, + http, + baseUrl, + model, + requestBuilder, + developerKey, + resourceDesc, + rootDesc, + schema, + universe_domain=universe.DEFAULT_UNIVERSE if HAS_UNIVERSE else "", + ): + """Build a Resource from the API description. + + Args: + http: httplib2.Http, Object to make http requests with. + baseUrl: string, base URL for the API. All requests are relative to this + URI. + model: googleapiclient.Model, converts to and from the wire format. + requestBuilder: class or callable that instantiates an + googleapiclient.HttpRequest object. + developerKey: string, key obtained from + https://code.google.com/apis/console + resourceDesc: object, section of deserialized discovery document that + describes a resource. Note that the top level discovery document + is considered a resource. + rootDesc: object, the entire deserialized discovery document. + schema: object, mapping of schema names to schema descriptions. + universe_domain: string, the universe for the API. The default universe + is "googleapis.com". + """ + self._dynamic_attrs = [] + + self._http = http + self._baseUrl = baseUrl + self._model = model + self._developerKey = developerKey + self._requestBuilder = requestBuilder + self._resourceDesc = resourceDesc + self._rootDesc = rootDesc + self._schema = schema + self._universe_domain = universe_domain + self._credentials_validated = False + + self._set_service_methods() + + def _set_dynamic_attr(self, attr_name, value): + """Sets an instance attribute and tracks it in a list of dynamic attributes. + + Args: + attr_name: string; The name of the attribute to be set + value: The value being set on the object and tracked in the dynamic cache. + """ + self._dynamic_attrs.append(attr_name) + self.__dict__[attr_name] = value + + def __getstate__(self): + """Trim the state down to something that can be pickled. + + Uses the fact that the instance variable _dynamic_attrs holds attrs that + will be wiped and restored on pickle serialization. + """ + state_dict = copy.copy(self.__dict__) + for dynamic_attr in self._dynamic_attrs: + del state_dict[dynamic_attr] + del state_dict["_dynamic_attrs"] + return state_dict + + def __setstate__(self, state): + """Reconstitute the state of the object from being pickled. + + Uses the fact that the instance variable _dynamic_attrs holds attrs that + will be wiped and restored on pickle serialization. + """ + self.__dict__.update(state) + self._dynamic_attrs = [] + self._set_service_methods() + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc, exc_tb): + self.close() + + def close(self): + """Close httplib2 connections.""" + # httplib2 leaves sockets open by default. + # Cleanup using the `close` method. + # https://github.com/httplib2/httplib2/issues/148 + self._http.close() + + def _set_service_methods(self): + self._add_basic_methods(self._resourceDesc, self._rootDesc, self._schema) + self._add_nested_resources(self._resourceDesc, self._rootDesc, self._schema) + self._add_next_methods(self._resourceDesc, self._schema) + + def _add_basic_methods(self, resourceDesc, rootDesc, schema): + # If this is the root Resource, add a new_batch_http_request() method. + if resourceDesc == rootDesc: + batch_uri = "%s%s" % ( + rootDesc["rootUrl"], + rootDesc.get("batchPath", "batch"), + ) + + def new_batch_http_request(callback=None): + """Create a BatchHttpRequest object based on the discovery document. + + Args: + callback: callable, A callback to be called for each response, of the + form callback(id, response, exception). The first parameter is the + request id, and the second is the deserialized response object. The + third is an apiclient.errors.HttpError exception object if an HTTP + error occurred while processing the request, or None if no error + occurred. + + Returns: + A BatchHttpRequest object based on the discovery document. + """ + return BatchHttpRequest(callback=callback, batch_uri=batch_uri) + + self._set_dynamic_attr("new_batch_http_request", new_batch_http_request) + + # Add basic methods to Resource + if "methods" in resourceDesc: + for methodName, methodDesc in resourceDesc["methods"].items(): + fixedMethodName, method = createMethod( + methodName, methodDesc, rootDesc, schema + ) + self._set_dynamic_attr( + fixedMethodName, method.__get__(self, self.__class__) + ) + # Add in _media methods. The functionality of the attached method will + # change when it sees that the method name ends in _media. + if methodDesc.get("supportsMediaDownload", False): + fixedMethodName, method = createMethod( + methodName + "_media", methodDesc, rootDesc, schema + ) + self._set_dynamic_attr( + fixedMethodName, method.__get__(self, self.__class__) + ) + + def _add_nested_resources(self, resourceDesc, rootDesc, schema): + # Add in nested resources + if "resources" in resourceDesc: + + def createResourceMethod(methodName, methodDesc): + """Create a method on the Resource to access a nested Resource. + + Args: + methodName: string, name of the method to use. + methodDesc: object, fragment of deserialized discovery document that + describes the method. + """ + methodName = fix_method_name(methodName) + + def methodResource(self): + return Resource( + http=self._http, + baseUrl=self._baseUrl, + model=self._model, + developerKey=self._developerKey, + requestBuilder=self._requestBuilder, + resourceDesc=methodDesc, + rootDesc=rootDesc, + schema=schema, + universe_domain=self._universe_domain, + ) + + setattr(methodResource, "__doc__", "A collection resource.") + setattr(methodResource, "__is_resource__", True) + + return (methodName, methodResource) + + for methodName, methodDesc in resourceDesc["resources"].items(): + fixedMethodName, method = createResourceMethod(methodName, methodDesc) + self._set_dynamic_attr( + fixedMethodName, method.__get__(self, self.__class__) + ) + + def _add_next_methods(self, resourceDesc, schema): + # Add _next() methods if and only if one of the names 'pageToken' or + # 'nextPageToken' occurs among the fields of both the method's response + # type either the method's request (query parameters) or request body. + if "methods" not in resourceDesc: + return + for methodName, methodDesc in resourceDesc["methods"].items(): + nextPageTokenName = _findPageTokenName( + _methodProperties(methodDesc, schema, "response") + ) + if not nextPageTokenName: + continue + isPageTokenParameter = True + pageTokenName = _findPageTokenName(methodDesc.get("parameters", {})) + if not pageTokenName: + isPageTokenParameter = False + pageTokenName = _findPageTokenName( + _methodProperties(methodDesc, schema, "request") + ) + if not pageTokenName: + continue + fixedMethodName, method = createNextMethod( + methodName + "_next", + pageTokenName, + nextPageTokenName, + isPageTokenParameter, + ) + self._set_dynamic_attr( + fixedMethodName, method.__get__(self, self.__class__) + ) + + def _validate_credentials(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + UniverseMismatchError: If the configured universe domain is not valid. + """ + credentials = getattr(self._http, "credentials", None) + + self._credentials_validated = ( + ( + self._credentials_validated + or universe.compare_domains(self._universe_domain, credentials) + ) + if HAS_UNIVERSE + else True + ) + return self._credentials_validated + + +def _findPageTokenName(fields): + """Search field names for one like a page token. + + Args: + fields: container of string, names of fields. + + Returns: + First name that is either 'pageToken' or 'nextPageToken' if one exists, + otherwise None. + """ + return next( + (tokenName for tokenName in _PAGE_TOKEN_NAMES if tokenName in fields), None + ) + + +def _methodProperties(methodDesc, schema, name): + """Get properties of a field in a method description. + + Args: + methodDesc: object, fragment of deserialized discovery document that + describes the method. + schema: object, mapping of schema names to schema descriptions. + name: string, name of top-level field in method description. + + Returns: + Object representing fragment of deserialized discovery document + corresponding to 'properties' field of object corresponding to named field + in method description, if it exists, otherwise empty dict. + """ + desc = methodDesc.get(name, {}) + if "$ref" in desc: + desc = schema.get(desc["$ref"], {}) + return desc.get("properties", {}) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/googleapiclient/errors.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/googleapiclient/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..288594a68a5647ff5179bccc0adcf18a697d4c41 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/googleapiclient/errors.py @@ -0,0 +1,197 @@ +# Copyright 2014 Google Inc. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Errors for the library. + +All exceptions defined by the library +should be defined in this file. +""" +from __future__ import absolute_import + +__author__ = "jcgregorio@google.com (Joe Gregorio)" + +import json + +from googleapiclient import _helpers as util + + +class Error(Exception): + """Base error for this module.""" + + pass + + +class HttpError(Error): + """HTTP data was invalid or unexpected.""" + + @util.positional(3) + def __init__(self, resp, content, uri=None): + self.resp = resp + if not isinstance(content, bytes): + raise TypeError("HTTP content should be bytes") + self.content = content + self.uri = uri + self.error_details = "" + self.reason = self._get_reason() + + @property + def status_code(self): + """Return the HTTP status code from the response content.""" + return self.resp.status + + def _get_reason(self): + """Calculate the reason for the error from the response content.""" + reason = self.resp.reason + try: + try: + data = json.loads(self.content.decode("utf-8")) + except json.JSONDecodeError: + # In case it is not json + data = self.content.decode("utf-8") + if isinstance(data, dict): + reason = data["error"]["message"] + error_detail_keyword = next( + ( + kw + for kw in ["detail", "details", "errors", "message"] + if kw in data["error"] + ), + "", + ) + if error_detail_keyword: + self.error_details = data["error"][error_detail_keyword] + elif isinstance(data, list) and len(data) > 0: + first_error = data[0] + reason = first_error["error"]["message"] + if "details" in first_error["error"]: + self.error_details = first_error["error"]["details"] + else: + self.error_details = data + except (ValueError, KeyError, TypeError): + pass + if reason is None: + reason = "" + return reason.strip() + + def __repr__(self): + if self.error_details: + return '' % ( + self.resp.status, + self.uri, + self.reason, + self.error_details, + ) + elif self.uri: + return '' % ( + self.resp.status, + self.uri, + self.reason, + ) + else: + return '' % (self.resp.status, self.reason) + + __str__ = __repr__ + + +class InvalidJsonError(Error): + """The JSON returned could not be parsed.""" + + pass + + +class UnknownFileType(Error): + """File type unknown or unexpected.""" + + pass + + +class UnknownLinkType(Error): + """Link type unknown or unexpected.""" + + pass + + +class UnknownApiNameOrVersion(Error): + """No API with that name and version exists.""" + + pass + + +class UnacceptableMimeTypeError(Error): + """That is an unacceptable mimetype for this operation.""" + + pass + + +class MediaUploadSizeError(Error): + """Media is larger than the method can accept.""" + + pass + + +class ResumableUploadError(HttpError): + """Error occurred during resumable upload.""" + + pass + + +class InvalidChunkSizeError(Error): + """The given chunksize is not valid.""" + + pass + + +class InvalidNotificationError(Error): + """The channel Notification is invalid.""" + + pass + + +class BatchError(HttpError): + """Error occurred during batch operations.""" + + @util.positional(2) + def __init__(self, reason, resp=None, content=None): + self.resp = resp + self.content = content + self.reason = reason + + def __repr__(self): + if getattr(self.resp, "status", None) is None: + return '' % (self.reason) + else: + return '' % (self.resp.status, self.reason) + + __str__ = __repr__ + + +class UnexpectedMethodError(Error): + """Exception raised by RequestMockBuilder on unexpected calls.""" + + @util.positional(1) + def __init__(self, methodId=None): + """Constructor for an UnexpectedMethodError.""" + super(UnexpectedMethodError, self).__init__( + "Received unexpected call %s" % methodId + ) + + +class UnexpectedBodyError(Error): + """Exception raised by RequestMockBuilder on unexpected bodies.""" + + def __init__(self, expected, provided): + """Constructor for an UnexpectedMethodError.""" + super(UnexpectedBodyError, self).__init__( + "Expected: [%s] - Provided: [%s]" % (expected, provided) + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/googleapiclient/http.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/googleapiclient/http.py new file mode 100644 index 0000000000000000000000000000000000000000..187f6f5dac856e27d583e66ca805d80e26f8f6df --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/googleapiclient/http.py @@ -0,0 +1,1962 @@ +# Copyright 2014 Google Inc. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 to encapsulate a single HTTP request. + +The classes implement a command pattern, with every +object supporting an execute() method that does the +actual HTTP request. +""" +from __future__ import absolute_import + +__author__ = "jcgregorio@google.com (Joe Gregorio)" + +import copy +import http.client as http_client +import io +import json +import logging +import mimetypes +import os +import random +import socket +import time +import urllib +import uuid + +import httplib2 + +# TODO(issue 221): Remove this conditional import jibbajabba. +try: + import ssl +except ImportError: + _ssl_SSLError = object() +else: + _ssl_SSLError = ssl.SSLError + +from email.generator import Generator +from email.mime.multipart import MIMEMultipart +from email.mime.nonmultipart import MIMENonMultipart +from email.parser import FeedParser + +from googleapiclient import _auth +from googleapiclient import _helpers as util +from googleapiclient.errors import ( + BatchError, + HttpError, + InvalidChunkSizeError, + ResumableUploadError, + UnexpectedBodyError, + UnexpectedMethodError, +) +from googleapiclient.model import JsonModel + +LOGGER = logging.getLogger(__name__) + +DEFAULT_CHUNK_SIZE = 100 * 1024 * 1024 + +MAX_URI_LENGTH = 2048 + +MAX_BATCH_LIMIT = 1000 + +_TOO_MANY_REQUESTS = 429 + +DEFAULT_HTTP_TIMEOUT_SEC = 60 + +_LEGACY_BATCH_URI = "https://www.googleapis.com/batch" + + +def _should_retry_response(resp_status, content): + """Determines whether a response should be retried. + + Args: + resp_status: The response status received. + content: The response content body. + + Returns: + True if the response should be retried, otherwise False. + """ + reason = None + + # Retry on 5xx errors. + if resp_status >= 500: + return True + + # Retry on 429 errors. + if resp_status == _TOO_MANY_REQUESTS: + return True + + # For 403 errors, we have to check for the `reason` in the response to + # determine if we should retry. + if resp_status == http_client.FORBIDDEN: + # If there's no details about the 403 type, don't retry. + if not content: + return False + + # Content is in JSON format. + try: + data = json.loads(content.decode("utf-8")) + if isinstance(data, dict): + # There are many variations of the error json so we need + # to determine the keyword which has the error detail. Make sure + # that the order of the keywords below isn't changed as it can + # break user code. If the "errors" key exists, we must use that + # first. + # See Issue #1243 + # https://github.com/googleapis/google-api-python-client/issues/1243 + error_detail_keyword = next( + ( + kw + for kw in ["errors", "status", "message"] + if kw in data["error"] + ), + "", + ) + + if error_detail_keyword: + reason = data["error"][error_detail_keyword] + + if isinstance(reason, list) and len(reason) > 0: + reason = reason[0] + if "reason" in reason: + reason = reason["reason"] + else: + reason = data[0]["error"]["errors"]["reason"] + except (UnicodeDecodeError, ValueError, KeyError): + LOGGER.warning("Invalid JSON content from response: %s", content) + return False + + LOGGER.warning('Encountered 403 Forbidden with reason "%s"', reason) + + # Only retry on rate limit related failures. + if reason in ("userRateLimitExceeded", "rateLimitExceeded"): + return True + + # Everything else is a success or non-retriable so break. + return False + + +def _retry_request( + http, num_retries, req_type, sleep, rand, uri, method, *args, **kwargs +): + """Retries an HTTP request multiple times while handling errors. + + If after all retries the request still fails, last error is either returned as + return value (for HTTP 5xx errors) or thrown (for ssl.SSLError). + + Args: + http: Http object to be used to execute request. + num_retries: Maximum number of retries. + req_type: Type of the request (used for logging retries). + sleep, rand: Functions to sleep for random time between retries. + uri: URI to be requested. + method: HTTP method to be used. + args, kwargs: Additional arguments passed to http.request. + + Returns: + resp, content - Response from the http request (may be HTTP 5xx). + """ + resp = None + content = None + exception = None + for retry_num in range(num_retries + 1): + if retry_num > 0: + # Sleep before retrying. + sleep_time = rand() * 2**retry_num + LOGGER.warning( + "Sleeping %.2f seconds before retry %d of %d for %s: %s %s, after %s", + sleep_time, + retry_num, + num_retries, + req_type, + method, + uri, + resp.status if resp else exception, + ) + sleep(sleep_time) + + try: + exception = None + resp, content = http.request(uri, method, *args, **kwargs) + # Retry on SSL errors and socket timeout errors. + except _ssl_SSLError as ssl_error: + exception = ssl_error + except socket.timeout as socket_timeout: + # Needs to be before socket.error as it's a subclass of OSError + # socket.timeout has no errorcode + exception = socket_timeout + except ConnectionError as connection_error: + # Needs to be before socket.error as it's a subclass of OSError + exception = connection_error + except OSError as socket_error: + # errno's contents differ by platform, so we have to match by name. + # Some of these same errors may have been caught above, e.g. ECONNRESET *should* be + # raised as a ConnectionError, but some libraries will raise it as a socket.error + # with an errno corresponding to ECONNRESET + if socket.errno.errorcode.get(socket_error.errno) not in { + "WSAETIMEDOUT", + "ETIMEDOUT", + "EPIPE", + "ECONNABORTED", + "ECONNREFUSED", + "ECONNRESET", + }: + raise + exception = socket_error + except httplib2.ServerNotFoundError as server_not_found_error: + exception = server_not_found_error + + if exception: + if retry_num == num_retries: + raise exception + else: + continue + + if not _should_retry_response(resp.status, content): + break + + return resp, content + + +class MediaUploadProgress(object): + """Status of a resumable upload.""" + + def __init__(self, resumable_progress, total_size): + """Constructor. + + Args: + resumable_progress: int, bytes sent so far. + total_size: int, total bytes in complete upload, or None if the total + upload size isn't known ahead of time. + """ + self.resumable_progress = resumable_progress + self.total_size = total_size + + def progress(self): + """Percent of upload completed, as a float. + + Returns: + the percentage complete as a float, returning 0.0 if the total size of + the upload is unknown. + """ + if self.total_size is not None and self.total_size != 0: + return float(self.resumable_progress) / float(self.total_size) + else: + return 0.0 + + +class MediaDownloadProgress(object): + """Status of a resumable download.""" + + def __init__(self, resumable_progress, total_size): + """Constructor. + + Args: + resumable_progress: int, bytes received so far. + total_size: int, total bytes in complete download. + """ + self.resumable_progress = resumable_progress + self.total_size = total_size + + def progress(self): + """Percent of download completed, as a float. + + Returns: + the percentage complete as a float, returning 0.0 if the total size of + the download is unknown. + """ + if self.total_size is not None and self.total_size != 0: + return float(self.resumable_progress) / float(self.total_size) + else: + return 0.0 + + +class MediaUpload(object): + """Describes a media object to upload. + + Base class that defines the interface of MediaUpload subclasses. + + Note that subclasses of MediaUpload may allow you to control the chunksize + when uploading a media object. It is important to keep the size of the chunk + as large as possible to keep the upload efficient. Other factors may influence + the size of the chunk you use, particularly if you are working in an + environment where individual HTTP requests may have a hardcoded time limit, + such as under certain classes of requests under Google App Engine. + + Streams are io.Base compatible objects that support seek(). Some MediaUpload + subclasses support using streams directly to upload data. Support for + streaming may be indicated by a MediaUpload sub-class and if appropriate for a + platform that stream will be used for uploading the media object. The support + for streaming is indicated by has_stream() returning True. The stream() method + should return an io.Base object that supports seek(). On platforms where the + underlying httplib module supports streaming, for example Python 2.6 and + later, the stream will be passed into the http library which will result in + less memory being used and possibly faster uploads. + + If you need to upload media that can't be uploaded using any of the existing + MediaUpload sub-class then you can sub-class MediaUpload for your particular + needs. + """ + + def chunksize(self): + """Chunk size for resumable uploads. + + Returns: + Chunk size in bytes. + """ + raise NotImplementedError() + + def mimetype(self): + """Mime type of the body. + + Returns: + Mime type. + """ + return "application/octet-stream" + + def size(self): + """Size of upload. + + Returns: + Size of the body, or None of the size is unknown. + """ + return None + + def resumable(self): + """Whether this upload is resumable. + + Returns: + True if resumable upload or False. + """ + return False + + def getbytes(self, begin, end): + """Get bytes from the media. + + Args: + begin: int, offset from beginning of file. + length: int, number of bytes to read, starting at begin. + + Returns: + A string of bytes read. May be shorter than length if EOF was reached + first. + """ + raise NotImplementedError() + + def has_stream(self): + """Does the underlying upload support a streaming interface. + + Streaming means it is an io.IOBase subclass that supports seek, i.e. + seekable() returns True. + + Returns: + True if the call to stream() will return an instance of a seekable io.Base + subclass. + """ + return False + + def stream(self): + """A stream interface to the data being uploaded. + + Returns: + The returned value is an io.IOBase subclass that supports seek, i.e. + seekable() returns True. + """ + raise NotImplementedError() + + @util.positional(1) + def _to_json(self, strip=None): + """Utility function for creating a JSON representation of a MediaUpload. + + Args: + strip: array, An array of names of members to not include in the JSON. + + Returns: + string, a JSON representation of this instance, suitable to pass to + from_json(). + """ + t = type(self) + d = copy.copy(self.__dict__) + if strip is not None: + for member in strip: + del d[member] + d["_class"] = t.__name__ + d["_module"] = t.__module__ + return json.dumps(d) + + def to_json(self): + """Create a JSON representation of an instance of MediaUpload. + + Returns: + string, a JSON representation of this instance, suitable to pass to + from_json(). + """ + return self._to_json() + + @classmethod + def new_from_json(cls, s): + """Utility class method to instantiate a MediaUpload subclass from a JSON + representation produced by to_json(). + + Args: + s: string, JSON from to_json(). + + Returns: + An instance of the subclass of MediaUpload that was serialized with + to_json(). + """ + data = json.loads(s) + # Find and call the right classmethod from_json() to restore the object. + module = data["_module"] + m = __import__(module, fromlist=module.split(".")[:-1]) + kls = getattr(m, data["_class"]) + from_json = getattr(kls, "from_json") + return from_json(s) + + +class MediaIoBaseUpload(MediaUpload): + """A MediaUpload for a io.Base objects. + + Note that the Python file object is compatible with io.Base and can be used + with this class also. + + fh = BytesIO('...Some data to upload...') + media = MediaIoBaseUpload(fh, mimetype='image/png', + chunksize=1024*1024, resumable=True) + farm.animals().insert( + id='cow', + name='cow.png', + media_body=media).execute() + + Depending on the platform you are working on, you may pass -1 as the + chunksize, which indicates that the entire file should be uploaded in a single + request. If the underlying platform supports streams, such as Python 2.6 or + later, then this can be very efficient as it avoids multiple connections, and + also avoids loading the entire file into memory before sending it. Note that + Google App Engine has a 5MB limit on request size, so you should never set + your chunksize larger than 5MB, or to -1. + """ + + @util.positional(3) + def __init__(self, fd, mimetype, chunksize=DEFAULT_CHUNK_SIZE, resumable=False): + """Constructor. + + Args: + fd: io.Base or file object, The source of the bytes to upload. MUST be + opened in blocking mode, do not use streams opened in non-blocking mode. + The given stream must be seekable, that is, it must be able to call + seek() on fd. + mimetype: string, Mime-type of the file. + chunksize: int, File will be uploaded in chunks of this many bytes. Only + used if resumable=True. Pass in a value of -1 if the file is to be + uploaded as a single chunk. Note that Google App Engine has a 5MB limit + on request size, so you should never set your chunksize larger than 5MB, + or to -1. + resumable: bool, True if this is a resumable upload. False means upload + in a single request. + """ + super(MediaIoBaseUpload, self).__init__() + self._fd = fd + self._mimetype = mimetype + if not (chunksize == -1 or chunksize > 0): + raise InvalidChunkSizeError() + self._chunksize = chunksize + self._resumable = resumable + + self._fd.seek(0, os.SEEK_END) + self._size = self._fd.tell() + + def chunksize(self): + """Chunk size for resumable uploads. + + Returns: + Chunk size in bytes. + """ + return self._chunksize + + def mimetype(self): + """Mime type of the body. + + Returns: + Mime type. + """ + return self._mimetype + + def size(self): + """Size of upload. + + Returns: + Size of the body, or None of the size is unknown. + """ + return self._size + + def resumable(self): + """Whether this upload is resumable. + + Returns: + True if resumable upload or False. + """ + return self._resumable + + def getbytes(self, begin, length): + """Get bytes from the media. + + Args: + begin: int, offset from beginning of file. + length: int, number of bytes to read, starting at begin. + + Returns: + A string of bytes read. May be shorted than length if EOF was reached + first. + """ + self._fd.seek(begin) + return self._fd.read(length) + + def has_stream(self): + """Does the underlying upload support a streaming interface. + + Streaming means it is an io.IOBase subclass that supports seek, i.e. + seekable() returns True. + + Returns: + True if the call to stream() will return an instance of a seekable io.Base + subclass. + """ + return True + + def stream(self): + """A stream interface to the data being uploaded. + + Returns: + The returned value is an io.IOBase subclass that supports seek, i.e. + seekable() returns True. + """ + return self._fd + + def to_json(self): + """This upload type is not serializable.""" + raise NotImplementedError("MediaIoBaseUpload is not serializable.") + + +class MediaFileUpload(MediaIoBaseUpload): + """A MediaUpload for a file. + + Construct a MediaFileUpload and pass as the media_body parameter of the + method. For example, if we had a service that allowed uploading images: + + media = MediaFileUpload('cow.png', mimetype='image/png', + chunksize=1024*1024, resumable=True) + farm.animals().insert( + id='cow', + name='cow.png', + media_body=media).execute() + + Depending on the platform you are working on, you may pass -1 as the + chunksize, which indicates that the entire file should be uploaded in a single + request. If the underlying platform supports streams, such as Python 2.6 or + later, then this can be very efficient as it avoids multiple connections, and + also avoids loading the entire file into memory before sending it. Note that + Google App Engine has a 5MB limit on request size, so you should never set + your chunksize larger than 5MB, or to -1. + """ + + @util.positional(2) + def __init__( + self, filename, mimetype=None, chunksize=DEFAULT_CHUNK_SIZE, resumable=False + ): + """Constructor. + + Args: + filename: string, Name of the file. + mimetype: string, Mime-type of the file. If None then a mime-type will be + guessed from the file extension. + chunksize: int, File will be uploaded in chunks of this many bytes. Only + used if resumable=True. Pass in a value of -1 if the file is to be + uploaded in a single chunk. Note that Google App Engine has a 5MB limit + on request size, so you should never set your chunksize larger than 5MB, + or to -1. + resumable: bool, True if this is a resumable upload. False means upload + in a single request. + """ + self._fd = None + self._filename = filename + self._fd = open(self._filename, "rb") + if mimetype is None: + # No mimetype provided, make a guess. + mimetype, _ = mimetypes.guess_type(filename) + if mimetype is None: + # Guess failed, use octet-stream. + mimetype = "application/octet-stream" + super(MediaFileUpload, self).__init__( + self._fd, mimetype, chunksize=chunksize, resumable=resumable + ) + + def __del__(self): + if self._fd: + self._fd.close() + + def to_json(self): + """Creating a JSON representation of an instance of MediaFileUpload. + + Returns: + string, a JSON representation of this instance, suitable to pass to + from_json(). + """ + return self._to_json(strip=["_fd"]) + + @staticmethod + def from_json(s): + d = json.loads(s) + return MediaFileUpload( + d["_filename"], + mimetype=d["_mimetype"], + chunksize=d["_chunksize"], + resumable=d["_resumable"], + ) + + +class MediaInMemoryUpload(MediaIoBaseUpload): + """MediaUpload for a chunk of bytes. + + DEPRECATED: Use MediaIoBaseUpload with either io.TextIOBase or io.StringIO for + the stream. + """ + + @util.positional(2) + def __init__( + self, + body, + mimetype="application/octet-stream", + chunksize=DEFAULT_CHUNK_SIZE, + resumable=False, + ): + """Create a new MediaInMemoryUpload. + + DEPRECATED: Use MediaIoBaseUpload with either io.TextIOBase or io.StringIO for + the stream. + + Args: + body: string, Bytes of body content. + mimetype: string, Mime-type of the file or default of + 'application/octet-stream'. + chunksize: int, File will be uploaded in chunks of this many bytes. Only + used if resumable=True. + resumable: bool, True if this is a resumable upload. False means upload + in a single request. + """ + fd = io.BytesIO(body) + super(MediaInMemoryUpload, self).__init__( + fd, mimetype, chunksize=chunksize, resumable=resumable + ) + + +class MediaIoBaseDownload(object): + """ "Download media resources. + + Note that the Python file object is compatible with io.Base and can be used + with this class also. + + + Example: + request = farms.animals().get_media(id='cow') + fh = io.FileIO('cow.png', mode='wb') + downloader = MediaIoBaseDownload(fh, request, chunksize=1024*1024) + + done = False + while done is False: + status, done = downloader.next_chunk() + if status: + print "Download %d%%." % int(status.progress() * 100) + print "Download Complete!" + """ + + @util.positional(3) + def __init__(self, fd, request, chunksize=DEFAULT_CHUNK_SIZE): + """Constructor. + + Args: + fd: io.Base or file object, The stream in which to write the downloaded + bytes. + request: googleapiclient.http.HttpRequest, the media request to perform in + chunks. + chunksize: int, File will be downloaded in chunks of this many bytes. + """ + self._fd = fd + self._request = request + self._uri = request.uri + self._chunksize = chunksize + self._progress = 0 + self._total_size = None + self._done = False + + # Stubs for testing. + self._sleep = time.sleep + self._rand = random.random + + self._headers = {} + for k, v in request.headers.items(): + # allow users to supply custom headers by setting them on the request + # but strip out the ones that are set by default on requests generated by + # API methods like Drive's files().get(fileId=...) + if not k.lower() in ("accept", "accept-encoding", "user-agent"): + self._headers[k] = v + + @util.positional(1) + def next_chunk(self, num_retries=0): + """Get the next chunk of the download. + + Args: + num_retries: Integer, number of times to retry with randomized + exponential backoff. If all retries fail, the raised HttpError + represents the last request. If zero (default), we attempt the + request only once. + + Returns: + (status, done): (MediaDownloadProgress, boolean) + The value of 'done' will be True when the media has been fully + downloaded or the total size of the media is unknown. + + Raises: + googleapiclient.errors.HttpError if the response was not a 2xx. + httplib2.HttpLib2Error if a transport error has occurred. + """ + headers = self._headers.copy() + headers["range"] = "bytes=%d-%d" % ( + self._progress, + self._progress + self._chunksize - 1, + ) + http = self._request.http + + resp, content = _retry_request( + http, + num_retries, + "media download", + self._sleep, + self._rand, + self._uri, + "GET", + headers=headers, + ) + + if resp.status in [200, 206]: + if "content-location" in resp and resp["content-location"] != self._uri: + self._uri = resp["content-location"] + self._progress += len(content) + self._fd.write(content) + + if "content-range" in resp: + content_range = resp["content-range"] + length = content_range.rsplit("/", 1)[1] + self._total_size = int(length) + elif "content-length" in resp: + self._total_size = int(resp["content-length"]) + + if self._total_size is None or self._progress == self._total_size: + self._done = True + return MediaDownloadProgress(self._progress, self._total_size), self._done + elif resp.status == 416: + # 416 is Range Not Satisfiable + # This typically occurs with a zero byte file + content_range = resp["content-range"] + length = content_range.rsplit("/", 1)[1] + self._total_size = int(length) + if self._total_size == 0: + self._done = True + return ( + MediaDownloadProgress(self._progress, self._total_size), + self._done, + ) + raise HttpError(resp, content, uri=self._uri) + + +class _StreamSlice(object): + """Truncated stream. + + Takes a stream and presents a stream that is a slice of the original stream. + This is used when uploading media in chunks. In later versions of Python a + stream can be passed to httplib in place of the string of data to send. The + problem is that httplib just blindly reads to the end of the stream. This + wrapper presents a virtual stream that only reads to the end of the chunk. + """ + + def __init__(self, stream, begin, chunksize): + """Constructor. + + Args: + stream: (io.Base, file object), the stream to wrap. + begin: int, the seek position the chunk begins at. + chunksize: int, the size of the chunk. + """ + self._stream = stream + self._begin = begin + self._chunksize = chunksize + self._stream.seek(begin) + + def read(self, n=-1): + """Read n bytes. + + Args: + n, int, the number of bytes to read. + + Returns: + A string of length 'n', or less if EOF is reached. + """ + # The data left available to read sits in [cur, end) + cur = self._stream.tell() + end = self._begin + self._chunksize + if n == -1 or cur + n > end: + n = end - cur + return self._stream.read(n) + + +class HttpRequest(object): + """Encapsulates a single HTTP request.""" + + @util.positional(4) + def __init__( + self, + http, + postproc, + uri, + method="GET", + body=None, + headers=None, + methodId=None, + resumable=None, + ): + """Constructor for an HttpRequest. + + Args: + http: httplib2.Http, the transport object to use to make a request + postproc: callable, called on the HTTP response and content to transform + it into a data object before returning, or raising an exception + on an error. + uri: string, the absolute URI to send the request to + method: string, the HTTP method to use + body: string, the request body of the HTTP request, + headers: dict, the HTTP request headers + methodId: string, a unique identifier for the API method being called. + resumable: MediaUpload, None if this is not a resumbale request. + """ + self.uri = uri + self.method = method + self.body = body + self.headers = headers or {} + self.methodId = methodId + self.http = http + self.postproc = postproc + self.resumable = resumable + self.response_callbacks = [] + self._in_error_state = False + + # The size of the non-media part of the request. + self.body_size = len(self.body or "") + + # The resumable URI to send chunks to. + self.resumable_uri = None + + # The bytes that have been uploaded. + self.resumable_progress = 0 + + # Stubs for testing. + self._rand = random.random + self._sleep = time.sleep + + @util.positional(1) + def execute(self, http=None, num_retries=0): + """Execute the request. + + Args: + http: httplib2.Http, an http object to be used in place of the + one the HttpRequest request object was constructed with. + num_retries: Integer, number of times to retry with randomized + exponential backoff. If all retries fail, the raised HttpError + represents the last request. If zero (default), we attempt the + request only once. + + Returns: + A deserialized object model of the response body as determined + by the postproc. + + Raises: + googleapiclient.errors.HttpError if the response was not a 2xx. + httplib2.HttpLib2Error if a transport error has occurred. + """ + if http is None: + http = self.http + + if self.resumable: + body = None + while body is None: + _, body = self.next_chunk(http=http, num_retries=num_retries) + return body + + # Non-resumable case. + + if "content-length" not in self.headers: + self.headers["content-length"] = str(self.body_size) + # If the request URI is too long then turn it into a POST request. + # Assume that a GET request never contains a request body. + if len(self.uri) > MAX_URI_LENGTH and self.method == "GET": + self.method = "POST" + self.headers["x-http-method-override"] = "GET" + self.headers["content-type"] = "application/x-www-form-urlencoded" + parsed = urllib.parse.urlparse(self.uri) + self.uri = urllib.parse.urlunparse( + (parsed.scheme, parsed.netloc, parsed.path, parsed.params, None, None) + ) + self.body = parsed.query + self.headers["content-length"] = str(len(self.body)) + + # Handle retries for server-side errors. + resp, content = _retry_request( + http, + num_retries, + "request", + self._sleep, + self._rand, + str(self.uri), + method=str(self.method), + body=self.body, + headers=self.headers, + ) + + for callback in self.response_callbacks: + callback(resp) + if resp.status >= 300: + raise HttpError(resp, content, uri=self.uri) + return self.postproc(resp, content) + + @util.positional(2) + def add_response_callback(self, cb): + """add_response_headers_callback + + Args: + cb: Callback to be called on receiving the response headers, of signature: + + def cb(resp): + # Where resp is an instance of httplib2.Response + """ + self.response_callbacks.append(cb) + + @util.positional(1) + def next_chunk(self, http=None, num_retries=0): + """Execute the next step of a resumable upload. + + Can only be used if the method being executed supports media uploads and + the MediaUpload object passed in was flagged as using resumable upload. + + Example: + + media = MediaFileUpload('cow.png', mimetype='image/png', + chunksize=1000, resumable=True) + request = farm.animals().insert( + id='cow', + name='cow.png', + media_body=media) + + response = None + while response is None: + status, response = request.next_chunk() + if status: + print "Upload %d%% complete." % int(status.progress() * 100) + + + Args: + http: httplib2.Http, an http object to be used in place of the + one the HttpRequest request object was constructed with. + num_retries: Integer, number of times to retry with randomized + exponential backoff. If all retries fail, the raised HttpError + represents the last request. If zero (default), we attempt the + request only once. + + Returns: + (status, body): (ResumableMediaStatus, object) + The body will be None until the resumable media is fully uploaded. + + Raises: + googleapiclient.errors.HttpError if the response was not a 2xx. + httplib2.HttpLib2Error if a transport error has occurred. + """ + if http is None: + http = self.http + + if self.resumable.size() is None: + size = "*" + else: + size = str(self.resumable.size()) + + if self.resumable_uri is None: + start_headers = copy.copy(self.headers) + start_headers["X-Upload-Content-Type"] = self.resumable.mimetype() + if size != "*": + start_headers["X-Upload-Content-Length"] = size + start_headers["content-length"] = str(self.body_size) + + resp, content = _retry_request( + http, + num_retries, + "resumable URI request", + self._sleep, + self._rand, + self.uri, + method=self.method, + body=self.body, + headers=start_headers, + ) + + if resp.status == 200 and "location" in resp: + self.resumable_uri = resp["location"] + else: + raise ResumableUploadError(resp, content) + elif self._in_error_state: + # If we are in an error state then query the server for current state of + # the upload by sending an empty PUT and reading the 'range' header in + # the response. + headers = {"Content-Range": "bytes */%s" % size, "content-length": "0"} + resp, content = http.request(self.resumable_uri, "PUT", headers=headers) + status, body = self._process_response(resp, content) + if body: + # The upload was complete. + return (status, body) + + if self.resumable.has_stream(): + data = self.resumable.stream() + if self.resumable.chunksize() == -1: + data.seek(self.resumable_progress) + chunk_end = self.resumable.size() - self.resumable_progress - 1 + else: + # Doing chunking with a stream, so wrap a slice of the stream. + data = _StreamSlice( + data, self.resumable_progress, self.resumable.chunksize() + ) + chunk_end = min( + self.resumable_progress + self.resumable.chunksize() - 1, + self.resumable.size() - 1, + ) + else: + data = self.resumable.getbytes( + self.resumable_progress, self.resumable.chunksize() + ) + + # A short read implies that we are at EOF, so finish the upload. + if len(data) < self.resumable.chunksize(): + size = str(self.resumable_progress + len(data)) + + chunk_end = self.resumable_progress + len(data) - 1 + + headers = { + # Must set the content-length header here because httplib can't + # calculate the size when working with _StreamSlice. + "Content-Length": str(chunk_end - self.resumable_progress + 1), + } + + # An empty file results in chunk_end = -1 and size = 0 + # sending "bytes 0--1/0" results in an invalid request + # Only add header "Content-Range" if chunk_end != -1 + if chunk_end != -1: + headers["Content-Range"] = "bytes %d-%d/%s" % ( + self.resumable_progress, + chunk_end, + size, + ) + + for retry_num in range(num_retries + 1): + if retry_num > 0: + self._sleep(self._rand() * 2**retry_num) + LOGGER.warning( + "Retry #%d for media upload: %s %s, following status: %d" + % (retry_num, self.method, self.uri, resp.status) + ) + + try: + resp, content = http.request( + self.resumable_uri, method="PUT", body=data, headers=headers + ) + except: + self._in_error_state = True + raise + if not _should_retry_response(resp.status, content): + break + + return self._process_response(resp, content) + + def _process_response(self, resp, content): + """Process the response from a single chunk upload. + + Args: + resp: httplib2.Response, the response object. + content: string, the content of the response. + + Returns: + (status, body): (ResumableMediaStatus, object) + The body will be None until the resumable media is fully uploaded. + + Raises: + googleapiclient.errors.HttpError if the response was not a 2xx or a 308. + """ + if resp.status in [200, 201]: + self._in_error_state = False + return None, self.postproc(resp, content) + elif resp.status == 308: + self._in_error_state = False + # A "308 Resume Incomplete" indicates we are not done. + try: + self.resumable_progress = int(resp["range"].split("-")[1]) + 1 + except KeyError: + # If resp doesn't contain range header, resumable progress is 0 + self.resumable_progress = 0 + if "location" in resp: + self.resumable_uri = resp["location"] + else: + self._in_error_state = True + raise HttpError(resp, content, uri=self.uri) + + return ( + MediaUploadProgress(self.resumable_progress, self.resumable.size()), + None, + ) + + def to_json(self): + """Returns a JSON representation of the HttpRequest.""" + d = copy.copy(self.__dict__) + if d["resumable"] is not None: + d["resumable"] = self.resumable.to_json() + del d["http"] + del d["postproc"] + del d["_sleep"] + del d["_rand"] + + return json.dumps(d) + + @staticmethod + def from_json(s, http, postproc): + """Returns an HttpRequest populated with info from a JSON object.""" + d = json.loads(s) + if d["resumable"] is not None: + d["resumable"] = MediaUpload.new_from_json(d["resumable"]) + return HttpRequest( + http, + postproc, + uri=d["uri"], + method=d["method"], + body=d["body"], + headers=d["headers"], + methodId=d["methodId"], + resumable=d["resumable"], + ) + + @staticmethod + def null_postproc(resp, contents): + return resp, contents + + +class BatchHttpRequest(object): + """Batches multiple HttpRequest objects into a single HTTP request. + + Example: + from googleapiclient.http import BatchHttpRequest + + def list_animals(request_id, response, exception): + \"\"\"Do something with the animals list response.\"\"\" + if exception is not None: + # Do something with the exception. + pass + else: + # Do something with the response. + pass + + def list_farmers(request_id, response, exception): + \"\"\"Do something with the farmers list response.\"\"\" + if exception is not None: + # Do something with the exception. + pass + else: + # Do something with the response. + pass + + service = build('farm', 'v2') + + batch = BatchHttpRequest() + + batch.add(service.animals().list(), list_animals) + batch.add(service.farmers().list(), list_farmers) + batch.execute(http=http) + """ + + @util.positional(1) + def __init__(self, callback=None, batch_uri=None): + """Constructor for a BatchHttpRequest. + + Args: + callback: callable, A callback to be called for each response, of the + form callback(id, response, exception). The first parameter is the + request id, and the second is the deserialized response object. The + third is an googleapiclient.errors.HttpError exception object if an HTTP error + occurred while processing the request, or None if no error occurred. + batch_uri: string, URI to send batch requests to. + """ + if batch_uri is None: + batch_uri = _LEGACY_BATCH_URI + + if batch_uri == _LEGACY_BATCH_URI: + LOGGER.warning( + "You have constructed a BatchHttpRequest using the legacy batch " + "endpoint %s. This endpoint will be turned down on August 12, 2020. " + "Please provide the API-specific endpoint or use " + "service.new_batch_http_request(). For more details see " + "https://developers.googleblog.com/2018/03/discontinuing-support-for-json-rpc-and.html" + "and https://developers.google.com/api-client-library/python/guide/batch.", + _LEGACY_BATCH_URI, + ) + self._batch_uri = batch_uri + + # Global callback to be called for each individual response in the batch. + self._callback = callback + + # A map from id to request. + self._requests = {} + + # A map from id to callback. + self._callbacks = {} + + # List of request ids, in the order in which they were added. + self._order = [] + + # The last auto generated id. + self._last_auto_id = 0 + + # Unique ID on which to base the Content-ID headers. + self._base_id = None + + # A map from request id to (httplib2.Response, content) response pairs + self._responses = {} + + # A map of id(Credentials) that have been refreshed. + self._refreshed_credentials = {} + + def _refresh_and_apply_credentials(self, request, http): + """Refresh the credentials and apply to the request. + + Args: + request: HttpRequest, the request. + http: httplib2.Http, the global http object for the batch. + """ + # For the credentials to refresh, but only once per refresh_token + # If there is no http per the request then refresh the http passed in + # via execute() + creds = None + request_credentials = False + + if request.http is not None: + creds = _auth.get_credentials_from_http(request.http) + request_credentials = True + + if creds is None and http is not None: + creds = _auth.get_credentials_from_http(http) + + if creds is not None: + if id(creds) not in self._refreshed_credentials: + _auth.refresh_credentials(creds) + self._refreshed_credentials[id(creds)] = 1 + + # Only apply the credentials if we are using the http object passed in, + # otherwise apply() will get called during _serialize_request(). + if request.http is None or not request_credentials: + _auth.apply_credentials(creds, request.headers) + + def _id_to_header(self, id_): + """Convert an id to a Content-ID header value. + + Args: + id_: string, identifier of individual request. + + Returns: + A Content-ID header with the id_ encoded into it. A UUID is prepended to + the value because Content-ID headers are supposed to be universally + unique. + """ + if self._base_id is None: + self._base_id = uuid.uuid4() + + # NB: we intentionally leave whitespace between base/id and '+', so RFC2822 + # line folding works properly on Python 3; see + # https://github.com/googleapis/google-api-python-client/issues/164 + return "<%s + %s>" % (self._base_id, urllib.parse.quote(id_)) + + def _header_to_id(self, header): + """Convert a Content-ID header value to an id. + + Presumes the Content-ID header conforms to the format that _id_to_header() + returns. + + Args: + header: string, Content-ID header value. + + Returns: + The extracted id value. + + Raises: + BatchError if the header is not in the expected format. + """ + if header[0] != "<" or header[-1] != ">": + raise BatchError("Invalid value for Content-ID: %s" % header) + if "+" not in header: + raise BatchError("Invalid value for Content-ID: %s" % header) + base, id_ = header[1:-1].split(" + ", 1) + + return urllib.parse.unquote(id_) + + def _serialize_request(self, request): + """Convert an HttpRequest object into a string. + + Args: + request: HttpRequest, the request to serialize. + + Returns: + The request as a string in application/http format. + """ + # Construct status line + parsed = urllib.parse.urlparse(request.uri) + request_line = urllib.parse.urlunparse( + ("", "", parsed.path, parsed.params, parsed.query, "") + ) + status_line = request.method + " " + request_line + " HTTP/1.1\n" + major, minor = request.headers.get("content-type", "application/json").split( + "/" + ) + msg = MIMENonMultipart(major, minor) + headers = request.headers.copy() + + if request.http is not None: + credentials = _auth.get_credentials_from_http(request.http) + if credentials is not None: + _auth.apply_credentials(credentials, headers) + + # MIMENonMultipart adds its own Content-Type header. + if "content-type" in headers: + del headers["content-type"] + + for key, value in headers.items(): + msg[key] = value + msg["Host"] = parsed.netloc + msg.set_unixfrom(None) + + if request.body is not None: + msg.set_payload(request.body) + msg["content-length"] = str(len(request.body)) + + # Serialize the mime message. + fp = io.StringIO() + # maxheaderlen=0 means don't line wrap headers. + g = Generator(fp, maxheaderlen=0) + g.flatten(msg, unixfrom=False) + body = fp.getvalue() + + return status_line + body + + def _deserialize_response(self, payload): + """Convert string into httplib2 response and content. + + Args: + payload: string, headers and body as a string. + + Returns: + A pair (resp, content), such as would be returned from httplib2.request. + """ + # Strip off the status line + status_line, payload = payload.split("\n", 1) + protocol, status, reason = status_line.split(" ", 2) + + # Parse the rest of the response + parser = FeedParser() + parser.feed(payload) + msg = parser.close() + msg["status"] = status + + # Create httplib2.Response from the parsed headers. + resp = httplib2.Response(msg) + resp.reason = reason + resp.version = int(protocol.split("/", 1)[1].replace(".", "")) + + content = payload.split("\r\n\r\n", 1)[1] + + return resp, content + + def _new_id(self): + """Create a new id. + + Auto incrementing number that avoids conflicts with ids already used. + + Returns: + string, a new unique id. + """ + self._last_auto_id += 1 + while str(self._last_auto_id) in self._requests: + self._last_auto_id += 1 + return str(self._last_auto_id) + + @util.positional(2) + def add(self, request, callback=None, request_id=None): + """Add a new request. + + Every callback added will be paired with a unique id, the request_id. That + unique id will be passed back to the callback when the response comes back + from the server. The default behavior is to have the library generate it's + own unique id. If the caller passes in a request_id then they must ensure + uniqueness for each request_id, and if they are not an exception is + raised. Callers should either supply all request_ids or never supply a + request id, to avoid such an error. + + Args: + request: HttpRequest, Request to add to the batch. + callback: callable, A callback to be called for this response, of the + form callback(id, response, exception). The first parameter is the + request id, and the second is the deserialized response object. The + third is an googleapiclient.errors.HttpError exception object if an HTTP error + occurred while processing the request, or None if no errors occurred. + request_id: string, A unique id for the request. The id will be passed + to the callback with the response. + + Returns: + None + + Raises: + BatchError if a media request is added to a batch. + KeyError is the request_id is not unique. + """ + + if len(self._order) >= MAX_BATCH_LIMIT: + raise BatchError( + "Exceeded the maximum calls(%d) in a single batch request." + % MAX_BATCH_LIMIT + ) + if request_id is None: + request_id = self._new_id() + if request.resumable is not None: + raise BatchError("Media requests cannot be used in a batch request.") + if request_id in self._requests: + raise KeyError("A request with this ID already exists: %s" % request_id) + self._requests[request_id] = request + self._callbacks[request_id] = callback + self._order.append(request_id) + + def _execute(self, http, order, requests): + """Serialize batch request, send to server, process response. + + Args: + http: httplib2.Http, an http object to be used to make the request with. + order: list, list of request ids in the order they were added to the + batch. + requests: list, list of request objects to send. + + Raises: + httplib2.HttpLib2Error if a transport error has occurred. + googleapiclient.errors.BatchError if the response is the wrong format. + """ + message = MIMEMultipart("mixed") + # Message should not write out it's own headers. + setattr(message, "_write_headers", lambda self: None) + + # Add all the individual requests. + for request_id in order: + request = requests[request_id] + + msg = MIMENonMultipart("application", "http") + msg["Content-Transfer-Encoding"] = "binary" + msg["Content-ID"] = self._id_to_header(request_id) + + body = self._serialize_request(request) + msg.set_payload(body) + message.attach(msg) + + # encode the body: note that we can't use `as_string`, because + # it plays games with `From ` lines. + fp = io.StringIO() + g = Generator(fp, mangle_from_=False) + g.flatten(message, unixfrom=False) + body = fp.getvalue() + + headers = {} + headers["content-type"] = ( + "multipart/mixed; " 'boundary="%s"' + ) % message.get_boundary() + + resp, content = http.request( + self._batch_uri, method="POST", body=body, headers=headers + ) + + if resp.status >= 300: + raise HttpError(resp, content, uri=self._batch_uri) + + # Prepend with a content-type header so FeedParser can handle it. + header = "content-type: %s\r\n\r\n" % resp["content-type"] + # PY3's FeedParser only accepts unicode. So we should decode content + # here, and encode each payload again. + content = content.decode("utf-8") + for_parser = header + content + + parser = FeedParser() + parser.feed(for_parser) + mime_response = parser.close() + + if not mime_response.is_multipart(): + raise BatchError( + "Response not in multipart/mixed format.", resp=resp, content=content + ) + + for part in mime_response.get_payload(): + request_id = self._header_to_id(part["Content-ID"]) + response, content = self._deserialize_response(part.get_payload()) + # We encode content here to emulate normal http response. + if isinstance(content, str): + content = content.encode("utf-8") + self._responses[request_id] = (response, content) + + @util.positional(1) + def execute(self, http=None): + """Execute all the requests as a single batched HTTP request. + + Args: + http: httplib2.Http, an http object to be used in place of the one the + HttpRequest request object was constructed with. If one isn't supplied + then use a http object from the requests in this batch. + + Returns: + None + + Raises: + httplib2.HttpLib2Error if a transport error has occurred. + googleapiclient.errors.BatchError if the response is the wrong format. + """ + # If we have no requests return + if len(self._order) == 0: + return None + + # If http is not supplied use the first valid one given in the requests. + if http is None: + for request_id in self._order: + request = self._requests[request_id] + if request is not None: + http = request.http + break + + if http is None: + raise ValueError("Missing a valid http object.") + + # Special case for OAuth2Credentials-style objects which have not yet been + # refreshed with an initial access_token. + creds = _auth.get_credentials_from_http(http) + if creds is not None: + if not _auth.is_valid(creds): + LOGGER.info("Attempting refresh to obtain initial access_token") + _auth.refresh_credentials(creds) + + self._execute(http, self._order, self._requests) + + # Loop over all the requests and check for 401s. For each 401 request the + # credentials should be refreshed and then sent again in a separate batch. + redo_requests = {} + redo_order = [] + + for request_id in self._order: + resp, content = self._responses[request_id] + if resp["status"] == "401": + redo_order.append(request_id) + request = self._requests[request_id] + self._refresh_and_apply_credentials(request, http) + redo_requests[request_id] = request + + if redo_requests: + self._execute(http, redo_order, redo_requests) + + # Now process all callbacks that are erroring, and raise an exception for + # ones that return a non-2xx response? Or add extra parameter to callback + # that contains an HttpError? + + for request_id in self._order: + resp, content = self._responses[request_id] + + request = self._requests[request_id] + callback = self._callbacks[request_id] + + response = None + exception = None + try: + if resp.status >= 300: + raise HttpError(resp, content, uri=request.uri) + response = request.postproc(resp, content) + except HttpError as e: + exception = e + + if callback is not None: + callback(request_id, response, exception) + if self._callback is not None: + self._callback(request_id, response, exception) + + +class HttpRequestMock(object): + """Mock of HttpRequest. + + Do not construct directly, instead use RequestMockBuilder. + """ + + def __init__(self, resp, content, postproc): + """Constructor for HttpRequestMock + + Args: + resp: httplib2.Response, the response to emulate coming from the request + content: string, the response body + postproc: callable, the post processing function usually supplied by + the model class. See model.JsonModel.response() as an example. + """ + self.resp = resp + self.content = content + self.postproc = postproc + if resp is None: + self.resp = httplib2.Response({"status": 200, "reason": "OK"}) + if "reason" in self.resp: + self.resp.reason = self.resp["reason"] + + def execute(self, http=None): + """Execute the request. + + Same behavior as HttpRequest.execute(), but the response is + mocked and not really from an HTTP request/response. + """ + return self.postproc(self.resp, self.content) + + +class RequestMockBuilder(object): + """A simple mock of HttpRequest + + Pass in a dictionary to the constructor that maps request methodIds to + tuples of (httplib2.Response, content, opt_expected_body) that should be + returned when that method is called. None may also be passed in for the + httplib2.Response, in which case a 200 OK response will be generated. + If an opt_expected_body (str or dict) is provided, it will be compared to + the body and UnexpectedBodyError will be raised on inequality. + + Example: + response = '{"data": {"id": "tag:google.c...' + requestBuilder = RequestMockBuilder( + { + 'plus.activities.get': (None, response), + } + ) + googleapiclient.discovery.build("plus", "v1", requestBuilder=requestBuilder) + + Methods that you do not supply a response for will return a + 200 OK with an empty string as the response content or raise an excpetion + if check_unexpected is set to True. The methodId is taken from the rpcName + in the discovery document. + + For more details see the project wiki. + """ + + def __init__(self, responses, check_unexpected=False): + """Constructor for RequestMockBuilder + + The constructed object should be a callable object + that can replace the class HttpResponse. + + responses - A dictionary that maps methodIds into tuples + of (httplib2.Response, content). The methodId + comes from the 'rpcName' field in the discovery + document. + check_unexpected - A boolean setting whether or not UnexpectedMethodError + should be raised on unsupplied method. + """ + self.responses = responses + self.check_unexpected = check_unexpected + + def __call__( + self, + http, + postproc, + uri, + method="GET", + body=None, + headers=None, + methodId=None, + resumable=None, + ): + """Implements the callable interface that discovery.build() expects + of requestBuilder, which is to build an object compatible with + HttpRequest.execute(). See that method for the description of the + parameters and the expected response. + """ + if methodId in self.responses: + response = self.responses[methodId] + resp, content = response[:2] + if len(response) > 2: + # Test the body against the supplied expected_body. + expected_body = response[2] + if bool(expected_body) != bool(body): + # Not expecting a body and provided one + # or expecting a body and not provided one. + raise UnexpectedBodyError(expected_body, body) + if isinstance(expected_body, str): + expected_body = json.loads(expected_body) + body = json.loads(body) + if body != expected_body: + raise UnexpectedBodyError(expected_body, body) + return HttpRequestMock(resp, content, postproc) + elif self.check_unexpected: + raise UnexpectedMethodError(methodId=methodId) + else: + model = JsonModel(False) + return HttpRequestMock(None, "{}", model.response) + + +class HttpMock(object): + """Mock of httplib2.Http""" + + def __init__(self, filename=None, headers=None): + """ + Args: + filename: string, absolute filename to read response from + headers: dict, header to return with response + """ + if headers is None: + headers = {"status": "200"} + if filename: + with open(filename, "rb") as f: + self.data = f.read() + else: + self.data = None + self.response_headers = headers + self.headers = None + self.uri = None + self.method = None + self.body = None + self.headers = None + + def request( + self, + uri, + method="GET", + body=None, + headers=None, + redirections=1, + connection_type=None, + ): + self.uri = uri + self.method = method + self.body = body + self.headers = headers + return httplib2.Response(self.response_headers), self.data + + def close(self): + return None + + +class HttpMockSequence(object): + """Mock of httplib2.Http + + Mocks a sequence of calls to request returning different responses for each + call. Create an instance initialized with the desired response headers + and content and then use as if an httplib2.Http instance. + + http = HttpMockSequence([ + ({'status': '401'}, ''), + ({'status': '200'}, '{"access_token":"1/3w","expires_in":3600}'), + ({'status': '200'}, 'echo_request_headers'), + ]) + resp, content = http.request("http://examples.com") + + There are special values you can pass in for content to trigger + behavours that are helpful in testing. + + 'echo_request_headers' means return the request headers in the response body + 'echo_request_headers_as_json' means return the request headers in + the response body + 'echo_request_body' means return the request body in the response body + 'echo_request_uri' means return the request uri in the response body + """ + + def __init__(self, iterable): + """ + Args: + iterable: iterable, a sequence of pairs of (headers, body) + """ + self._iterable = iterable + self.follow_redirects = True + self.request_sequence = list() + + def request( + self, + uri, + method="GET", + body=None, + headers=None, + redirections=1, + connection_type=None, + ): + # Remember the request so after the fact this mock can be examined + self.request_sequence.append((uri, method, body, headers)) + resp, content = self._iterable.pop(0) + if isinstance(content, str): + content = content.encode("utf-8") + + if content == b"echo_request_headers": + content = headers + elif content == b"echo_request_headers_as_json": + content = json.dumps(headers) + elif content == b"echo_request_body": + if hasattr(body, "read"): + content = body.read() + else: + content = body + elif content == b"echo_request_uri": + content = uri + if isinstance(content, str): + content = content.encode("utf-8") + return httplib2.Response(resp), content + + +def set_user_agent(http, user_agent): + """Set the user-agent on every request. + + Args: + http - An instance of httplib2.Http + or something that acts like it. + user_agent: string, the value for the user-agent header. + + Returns: + A modified instance of http that was passed in. + + Example: + + h = httplib2.Http() + h = set_user_agent(h, "my-app-name/6.0") + + Most of the time the user-agent will be set doing auth, this is for the rare + cases where you are accessing an unauthenticated endpoint. + """ + request_orig = http.request + + # The closure that will replace 'httplib2.Http.request'. + def new_request( + uri, + method="GET", + body=None, + headers=None, + redirections=httplib2.DEFAULT_MAX_REDIRECTS, + connection_type=None, + ): + """Modify the request headers to add the user-agent.""" + if headers is None: + headers = {} + if "user-agent" in headers: + headers["user-agent"] = user_agent + " " + headers["user-agent"] + else: + headers["user-agent"] = user_agent + resp, content = request_orig( + uri, + method=method, + body=body, + headers=headers, + redirections=redirections, + connection_type=connection_type, + ) + return resp, content + + http.request = new_request + return http + + +def tunnel_patch(http): + """Tunnel PATCH requests over POST. + Args: + http - An instance of httplib2.Http + or something that acts like it. + + Returns: + A modified instance of http that was passed in. + + Example: + + h = httplib2.Http() + h = tunnel_patch(h, "my-app-name/6.0") + + Useful if you are running on a platform that doesn't support PATCH. + Apply this last if you are using OAuth 1.0, as changing the method + will result in a different signature. + """ + request_orig = http.request + + # The closure that will replace 'httplib2.Http.request'. + def new_request( + uri, + method="GET", + body=None, + headers=None, + redirections=httplib2.DEFAULT_MAX_REDIRECTS, + connection_type=None, + ): + """Modify the request headers to add the user-agent.""" + if headers is None: + headers = {} + if method == "PATCH": + if "oauth_token" in headers.get("authorization", ""): + LOGGER.warning( + "OAuth 1.0 request made with Credentials after tunnel_patch." + ) + headers["x-http-method-override"] = "PATCH" + method = "POST" + resp, content = request_orig( + uri, + method=method, + body=body, + headers=headers, + redirections=redirections, + connection_type=connection_type, + ) + return resp, content + + http.request = new_request + return http + + +def build_http(): + """Builds httplib2.Http object + + Returns: + A httplib2.Http object, which is used to make http requests, and which has timeout set by default. + To override default timeout call + + socket.setdefaulttimeout(timeout_in_sec) + + before interacting with this method. + """ + if socket.getdefaulttimeout() is not None: + http_timeout = socket.getdefaulttimeout() + else: + http_timeout = DEFAULT_HTTP_TIMEOUT_SEC + http = httplib2.Http(timeout=http_timeout) + # 308's are used by several Google APIs (Drive, YouTube) + # for Resumable Uploads rather than Permanent Redirects. + # This asks httplib2 to exclude 308s from the status codes + # it treats as redirects + try: + http.redirect_codes = http.redirect_codes - {308} + except AttributeError: + # Apache Beam tests depend on this library and cannot + # currently upgrade their httplib2 version + # http.redirect_codes does not exist in previous versions + # of httplib2, so pass + pass + + return http diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/googleapiclient/mimeparse.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/googleapiclient/mimeparse.py new file mode 100644 index 0000000000000000000000000000000000000000..d3dedee9c53370e9ba67f252d34a7e0cccd2a244 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/googleapiclient/mimeparse.py @@ -0,0 +1,183 @@ +# Copyright 2014 Joe Gregorio +# +# Licensed under the MIT License + +"""MIME-Type Parser + +This module provides basic functions for handling mime-types. It can handle +matching mime-types against a list of media-ranges. See section 14.1 of the +HTTP specification [RFC 2616] for a complete explanation. + + http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1 + +Contents: + - parse_mime_type(): Parses a mime-type into its component parts. + - parse_media_range(): Media-ranges are mime-types with wild-cards and a 'q' + quality parameter. + - quality(): Determines the quality ('q') of a mime-type when + compared against a list of media-ranges. + - quality_parsed(): Just like quality() except the second parameter must be + pre-parsed. + - best_match(): Choose the mime-type with the highest quality ('q') + from a list of candidates. +""" +from __future__ import absolute_import + +from functools import reduce + +__version__ = "0.1.3" +__author__ = "Joe Gregorio" +__email__ = "joe@bitworking.org" +__license__ = "MIT License" +__credits__ = "" + + +def parse_mime_type(mime_type): + """Parses a mime-type into its component parts. + + Carves up a mime-type and returns a tuple of the (type, subtype, params) + where 'params' is a dictionary of all the parameters for the media range. + For example, the media range 'application/xhtml;q=0.5' would get parsed + into: + + ('application', 'xhtml', {'q', '0.5'}) + """ + parts = mime_type.split(";") + params = dict( + [tuple([s.strip() for s in param.split("=", 1)]) for param in parts[1:]] + ) + full_type = parts[0].strip() + # Java URLConnection class sends an Accept header that includes a + # single '*'. Turn it into a legal wildcard. + if full_type == "*": + full_type = "*/*" + (type, subtype) = full_type.split("/") + + return (type.strip(), subtype.strip(), params) + + +def parse_media_range(range): + """Parse a media-range into its component parts. + + Carves up a media range and returns a tuple of the (type, subtype, + params) where 'params' is a dictionary of all the parameters for the media + range. For example, the media range 'application/*;q=0.5' would get parsed + into: + + ('application', '*', {'q', '0.5'}) + + In addition this function also guarantees that there is a value for 'q' + in the params dictionary, filling it in with a proper default if + necessary. + """ + (type, subtype, params) = parse_mime_type(range) + if ( + "q" not in params + or not params["q"] + or not float(params["q"]) + or float(params["q"]) > 1 + or float(params["q"]) < 0 + ): + params["q"] = "1" + + return (type, subtype, params) + + +def fitness_and_quality_parsed(mime_type, parsed_ranges): + """Find the best match for a mime-type amongst parsed media-ranges. + + Find the best match for a given mime-type against a list of media_ranges + that have already been parsed by parse_media_range(). Returns a tuple of + the fitness value and the value of the 'q' quality parameter of the best + match, or (-1, 0) if no match was found. Just as for quality_parsed(), + 'parsed_ranges' must be a list of parsed media ranges. + """ + best_fitness = -1 + best_fit_q = 0 + (target_type, target_subtype, target_params) = parse_media_range(mime_type) + for (type, subtype, params) in parsed_ranges: + type_match = type == target_type or type == "*" or target_type == "*" + subtype_match = ( + subtype == target_subtype or subtype == "*" or target_subtype == "*" + ) + if type_match and subtype_match: + param_matches = reduce( + lambda x, y: x + y, + [ + 1 + for (key, value) in target_params.items() + if key != "q" and key in params and value == params[key] + ], + 0, + ) + fitness = (type == target_type) and 100 or 0 + fitness += (subtype == target_subtype) and 10 or 0 + fitness += param_matches + if fitness > best_fitness: + best_fitness = fitness + best_fit_q = params["q"] + + return best_fitness, float(best_fit_q) + + +def quality_parsed(mime_type, parsed_ranges): + """Find the best match for a mime-type amongst parsed media-ranges. + + Find the best match for a given mime-type against a list of media_ranges + that have already been parsed by parse_media_range(). Returns the 'q' + quality parameter of the best match, 0 if no match was found. This function + bahaves the same as quality() except that 'parsed_ranges' must be a list of + parsed media ranges. + """ + + return fitness_and_quality_parsed(mime_type, parsed_ranges)[1] + + +def quality(mime_type, ranges): + """Return the quality ('q') of a mime-type against a list of media-ranges. + + Returns the quality 'q' of a mime-type when compared against the + media-ranges in ranges. For example: + + >>> quality('text/html','text/*;q=0.3, text/html;q=0.7, + text/html;level=1, text/html;level=2;q=0.4, */*;q=0.5') + 0.7 + + """ + parsed_ranges = [parse_media_range(r) for r in ranges.split(",")] + + return quality_parsed(mime_type, parsed_ranges) + + +def best_match(supported, header): + """Return mime-type with the highest quality ('q') from list of candidates. + + Takes a list of supported mime-types and finds the best match for all the + media-ranges listed in header. The value of header must be a string that + conforms to the format of the HTTP Accept: header. The value of 'supported' + is a list of mime-types. The list of supported mime-types should be sorted + in order of increasing desirability, in case of a situation where there is + a tie. + + >>> best_match(['application/xbel+xml', 'text/xml'], + 'text/*;q=0.5,*/*; q=0.1') + 'text/xml' + """ + split_header = _filter_blank(header.split(",")) + parsed_header = [parse_media_range(r) for r in split_header] + weighted_matches = [] + pos = 0 + for mime_type in supported: + weighted_matches.append( + (fitness_and_quality_parsed(mime_type, parsed_header), pos, mime_type) + ) + pos += 1 + weighted_matches.sort() + + return weighted_matches[-1][0][1] and weighted_matches[-1][2] or "" + + +def _filter_blank(i): + for s in i: + if s.strip(): + yield s diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/googleapiclient/model.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/googleapiclient/model.py new file mode 100644 index 0000000000000000000000000000000000000000..dee1cb7f377bd81acfd9b43b72d20034ee5cb096 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/googleapiclient/model.py @@ -0,0 +1,429 @@ +# Copyright 2014 Google Inc. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Model objects for requests and responses. + +Each API may support one or more serializations, such +as JSON, Atom, etc. The model classes are responsible +for converting between the wire format and the Python +object representation. +""" +from __future__ import absolute_import + +__author__ = "jcgregorio@google.com (Joe Gregorio)" + +import json +import logging +import platform +import urllib +import warnings + +from googleapiclient import version as googleapiclient_version +from googleapiclient.errors import HttpError + +try: + from google.api_core.version_header import API_VERSION_METADATA_KEY + + HAS_API_VERSION = True +except ImportError: + HAS_API_VERSION = False + +_LIBRARY_VERSION = googleapiclient_version.__version__ +_PY_VERSION = platform.python_version() + +LOGGER = logging.getLogger(__name__) + +dump_request_response = False + + +def _abstract(): + raise NotImplementedError("You need to override this function") + + +class Model(object): + """Model base class. + + All Model classes should implement this interface. + The Model serializes and de-serializes between a wire + format such as JSON and a Python object representation. + """ + + def request(self, headers, path_params, query_params, body_value): + """Updates outgoing requests with a serialized body. + + Args: + headers: dict, request headers + path_params: dict, parameters that appear in the request path + query_params: dict, parameters that appear in the query + body_value: object, the request body as a Python object, which must be + serializable. + Returns: + A tuple of (headers, path_params, query, body) + + headers: dict, request headers + path_params: dict, parameters that appear in the request path + query: string, query part of the request URI + body: string, the body serialized in the desired wire format. + """ + _abstract() + + def response(self, resp, content): + """Convert the response wire format into a Python object. + + Args: + resp: httplib2.Response, the HTTP response headers and status + content: string, the body of the HTTP response + + Returns: + The body de-serialized as a Python object. + + Raises: + googleapiclient.errors.HttpError if a non 2xx response is received. + """ + _abstract() + + +class BaseModel(Model): + """Base model class. + + Subclasses should provide implementations for the "serialize" and + "deserialize" methods, as well as values for the following class attributes. + + Attributes: + accept: The value to use for the HTTP Accept header. + content_type: The value to use for the HTTP Content-type header. + no_content_response: The value to return when deserializing a 204 "No + Content" response. + alt_param: The value to supply as the "alt" query parameter for requests. + """ + + accept = None + content_type = None + no_content_response = None + alt_param = None + + def _log_request(self, headers, path_params, query, body): + """Logs debugging information about the request if requested.""" + if dump_request_response: + LOGGER.info("--request-start--") + LOGGER.info("-headers-start-") + for h, v in headers.items(): + LOGGER.info("%s: %s", h, v) + LOGGER.info("-headers-end-") + LOGGER.info("-path-parameters-start-") + for h, v in path_params.items(): + LOGGER.info("%s: %s", h, v) + LOGGER.info("-path-parameters-end-") + LOGGER.info("body: %s", body) + LOGGER.info("query: %s", query) + LOGGER.info("--request-end--") + + def request(self, headers, path_params, query_params, body_value, api_version=None): + """Updates outgoing requests with a serialized body. + + Args: + headers: dict, request headers + path_params: dict, parameters that appear in the request path + query_params: dict, parameters that appear in the query + body_value: object, the request body as a Python object, which must be + serializable by json. + api_version: str, The precise API version represented by this request, + which will result in an API Version header being sent along with the + HTTP request. + Returns: + A tuple of (headers, path_params, query, body) + + headers: dict, request headers + path_params: dict, parameters that appear in the request path + query: string, query part of the request URI + body: string, the body serialized as JSON + """ + query = self._build_query(query_params) + headers["accept"] = self.accept + headers["accept-encoding"] = "gzip, deflate" + if "user-agent" in headers: + headers["user-agent"] += " " + else: + headers["user-agent"] = "" + headers["user-agent"] += "(gzip)" + if "x-goog-api-client" in headers: + headers["x-goog-api-client"] += " " + else: + headers["x-goog-api-client"] = "" + headers["x-goog-api-client"] += "gdcl/%s gl-python/%s" % ( + _LIBRARY_VERSION, + _PY_VERSION, + ) + + if api_version and HAS_API_VERSION: + headers[API_VERSION_METADATA_KEY] = api_version + elif api_version: + warnings.warn( + "The `api_version` argument is ignored as a newer version of " + "`google-api-core` is required to use this feature." + "Please upgrade `google-api-core` to 2.19.0 or newer." + ) + + if body_value is not None: + headers["content-type"] = self.content_type + body_value = self.serialize(body_value) + self._log_request(headers, path_params, query, body_value) + return (headers, path_params, query, body_value) + + def _build_query(self, params): + """Builds a query string. + + Args: + params: dict, the query parameters + + Returns: + The query parameters properly encoded into an HTTP URI query string. + """ + if self.alt_param is not None: + params.update({"alt": self.alt_param}) + astuples = [] + for key, value in params.items(): + if type(value) == type([]): + for x in value: + x = x.encode("utf-8") + astuples.append((key, x)) + else: + if isinstance(value, str) and callable(value.encode): + value = value.encode("utf-8") + astuples.append((key, value)) + return "?" + urllib.parse.urlencode(astuples) + + def _log_response(self, resp, content): + """Logs debugging information about the response if requested.""" + if dump_request_response: + LOGGER.info("--response-start--") + for h, v in resp.items(): + LOGGER.info("%s: %s", h, v) + if content: + LOGGER.info(content) + LOGGER.info("--response-end--") + + def response(self, resp, content): + """Convert the response wire format into a Python object. + + Args: + resp: httplib2.Response, the HTTP response headers and status + content: string, the body of the HTTP response + + Returns: + The body de-serialized as a Python object. + + Raises: + googleapiclient.errors.HttpError if a non 2xx response is received. + """ + self._log_response(resp, content) + # Error handling is TBD, for example, do we retry + # for some operation/error combinations? + if resp.status < 300: + if resp.status == 204: + # A 204: No Content response should be treated differently + # to all the other success states + return self.no_content_response + return self.deserialize(content) + else: + LOGGER.debug("Content from bad request was: %r" % content) + raise HttpError(resp, content) + + def serialize(self, body_value): + """Perform the actual Python object serialization. + + Args: + body_value: object, the request body as a Python object. + + Returns: + string, the body in serialized form. + """ + _abstract() + + def deserialize(self, content): + """Perform the actual deserialization from response string to Python + object. + + Args: + content: string, the body of the HTTP response + + Returns: + The body de-serialized as a Python object. + """ + _abstract() + + +class JsonModel(BaseModel): + """Model class for JSON. + + Serializes and de-serializes between JSON and the Python + object representation of HTTP request and response bodies. + """ + + accept = "application/json" + content_type = "application/json" + alt_param = "json" + + def __init__(self, data_wrapper=False): + """Construct a JsonModel. + + Args: + data_wrapper: boolean, wrap requests and responses in a data wrapper + """ + self._data_wrapper = data_wrapper + + def serialize(self, body_value): + if ( + isinstance(body_value, dict) + and "data" not in body_value + and self._data_wrapper + ): + body_value = {"data": body_value} + return json.dumps(body_value) + + def deserialize(self, content): + try: + content = content.decode("utf-8") + except AttributeError: + pass + try: + body = json.loads(content) + except json.decoder.JSONDecodeError: + body = content + else: + if self._data_wrapper and "data" in body: + body = body["data"] + return body + + @property + def no_content_response(self): + return {} + + +class RawModel(JsonModel): + """Model class for requests that don't return JSON. + + Serializes and de-serializes between JSON and the Python + object representation of HTTP request, and returns the raw bytes + of the response body. + """ + + accept = "*/*" + content_type = "application/json" + alt_param = None + + def deserialize(self, content): + return content + + @property + def no_content_response(self): + return "" + + +class MediaModel(JsonModel): + """Model class for requests that return Media. + + Serializes and de-serializes between JSON and the Python + object representation of HTTP request, and returns the raw bytes + of the response body. + """ + + accept = "*/*" + content_type = "application/json" + alt_param = "media" + + def deserialize(self, content): + return content + + @property + def no_content_response(self): + return "" + + +class ProtocolBufferModel(BaseModel): + """Model class for protocol buffers. + + Serializes and de-serializes the binary protocol buffer sent in the HTTP + request and response bodies. + """ + + accept = "application/x-protobuf" + content_type = "application/x-protobuf" + alt_param = "proto" + + def __init__(self, protocol_buffer): + """Constructs a ProtocolBufferModel. + + The serialized protocol buffer returned in an HTTP response will be + de-serialized using the given protocol buffer class. + + Args: + protocol_buffer: The protocol buffer class used to de-serialize a + response from the API. + """ + self._protocol_buffer = protocol_buffer + + def serialize(self, body_value): + return body_value.SerializeToString() + + def deserialize(self, content): + return self._protocol_buffer.FromString(content) + + @property + def no_content_response(self): + return self._protocol_buffer() + + +def makepatch(original, modified): + """Create a patch object. + + Some methods support PATCH, an efficient way to send updates to a resource. + This method allows the easy construction of patch bodies by looking at the + differences between a resource before and after it was modified. + + Args: + original: object, the original deserialized resource + modified: object, the modified deserialized resource + Returns: + An object that contains only the changes from original to modified, in a + form suitable to pass to a PATCH method. + + Example usage: + item = service.activities().get(postid=postid, userid=userid).execute() + original = copy.deepcopy(item) + item['object']['content'] = 'This is updated.' + service.activities.patch(postid=postid, userid=userid, + body=makepatch(original, item)).execute() + """ + patch = {} + for key, original_value in original.items(): + modified_value = modified.get(key, None) + if modified_value is None: + # Use None to signal that the element is deleted + patch[key] = None + elif original_value != modified_value: + if type(original_value) == type({}): + # Recursively descend objects + patch[key] = makepatch(original_value, modified_value) + else: + # In the case of simple types or arrays we just replace + patch[key] = modified_value + else: + # Don't add anything to patch if there's no change + pass + for key in modified: + if key not in original: + patch[key] = modified[key] + + return patch diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/googleapiclient/sample_tools.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/googleapiclient/sample_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..bdad0a2ae878f43627199c5a7dcdd82cad0a8e8e --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/googleapiclient/sample_tools.py @@ -0,0 +1,108 @@ +# Copyright 2014 Google Inc. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 making samples. + +Consolidates a lot of code commonly repeated in sample applications. +""" +from __future__ import absolute_import + +__author__ = "jcgregorio@google.com (Joe Gregorio)" +__all__ = ["init"] + + +import argparse +import os + +from googleapiclient import discovery +from googleapiclient.http import build_http + + +def init( + argv, name, version, doc, filename, scope=None, parents=[], discovery_filename=None +): + """A common initialization routine for samples. + + Many of the sample applications do the same initialization, which has now + been consolidated into this function. This function uses common idioms found + in almost all the samples, i.e. for an API with name 'apiname', the + credentials are stored in a file named apiname.dat, and the + client_secrets.json file is stored in the same directory as the application + main file. + + Args: + argv: list of string, the command-line parameters of the application. + name: string, name of the API. + version: string, version of the API. + doc: string, description of the application. Usually set to __doc__. + file: string, filename of the application. Usually set to __file__. + parents: list of argparse.ArgumentParser, additional command-line flags. + scope: string, The OAuth scope used. + discovery_filename: string, name of local discovery file (JSON). Use when discovery doc not available via URL. + + Returns: + A tuple of (service, flags), where service is the service object and flags + is the parsed command-line flags. + """ + try: + from oauth2client import client, file, tools + except ImportError: + raise ImportError( + "googleapiclient.sample_tools requires oauth2client. Please install oauth2client and try again." + ) + + if scope is None: + scope = "https://www.googleapis.com/auth/" + name + + # Parser command-line arguments. + parent_parsers = [tools.argparser] + parent_parsers.extend(parents) + parser = argparse.ArgumentParser( + description=doc, + formatter_class=argparse.RawDescriptionHelpFormatter, + parents=parent_parsers, + ) + flags = parser.parse_args(argv[1:]) + + # Name of a file containing the OAuth 2.0 information for this + # application, including client_id and client_secret, which are found + # on the API Access tab on the Google APIs + # Console . + client_secrets = os.path.join(os.path.dirname(filename), "client_secrets.json") + + # Set up a Flow object to be used if we need to authenticate. + flow = client.flow_from_clientsecrets( + client_secrets, scope=scope, message=tools.message_if_missing(client_secrets) + ) + + # Prepare credentials, and authorize HTTP object with them. + # If the credentials don't exist or are invalid run through the native client + # flow. The Storage object will ensure that if successful the good + # credentials will get written back to a file. + storage = file.Storage(name + ".dat") + credentials = storage.get() + if credentials is None or credentials.invalid: + credentials = tools.run_flow(flow, storage, flags) + http = credentials.authorize(http=build_http()) + + if discovery_filename is None: + # Construct a service object via the discovery service. + service = discovery.build(name, version, http=http) + else: + # Construct a service object using a local discovery document file. + with open(discovery_filename) as discovery_file: + service = discovery.build_from_document( + discovery_file.read(), base="https://www.googleapis.com/", http=http + ) + return (service, flags) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/googleapiclient/schema.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/googleapiclient/schema.py new file mode 100644 index 0000000000000000000000000000000000000000..93b07df44ac6cb3ddf47a23218801de2ecdc6614 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/googleapiclient/schema.py @@ -0,0 +1,317 @@ +# Copyright 2014 Google Inc. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Schema processing for discovery based APIs + +Schemas holds an APIs discovery schemas. It can return those schema as +deserialized JSON objects, or pretty print them as prototype objects that +conform to the schema. + +For example, given the schema: + + schema = \"\"\"{ + "Foo": { + "type": "object", + "properties": { + "etag": { + "type": "string", + "description": "ETag of the collection." + }, + "kind": { + "type": "string", + "description": "Type of the collection ('calendar#acl').", + "default": "calendar#acl" + }, + "nextPageToken": { + "type": "string", + "description": "Token used to access the next + page of this result. Omitted if no further results are available." + } + } + } + }\"\"\" + + s = Schemas(schema) + print s.prettyPrintByName('Foo') + + Produces the following output: + + { + "nextPageToken": "A String", # Token used to access the + # next page of this result. Omitted if no further results are available. + "kind": "A String", # Type of the collection ('calendar#acl'). + "etag": "A String", # ETag of the collection. + }, + +The constructor takes a discovery document in which to look up named schema. +""" +from __future__ import absolute_import + +# TODO(jcgregorio) support format, enum, minimum, maximum + +__author__ = "jcgregorio@google.com (Joe Gregorio)" + + +from collections import OrderedDict + +from googleapiclient import _helpers as util + + +class Schemas(object): + """Schemas for an API.""" + + def __init__(self, discovery): + """Constructor. + + Args: + discovery: object, Deserialized discovery document from which we pull + out the named schema. + """ + self.schemas = discovery.get("schemas", {}) + + # Cache of pretty printed schemas. + self.pretty = {} + + @util.positional(2) + def _prettyPrintByName(self, name, seen=None, dent=0): + """Get pretty printed object prototype from the schema name. + + Args: + name: string, Name of schema in the discovery document. + seen: list of string, Names of schema already seen. Used to handle + recursive definitions. + + Returns: + string, A string that contains a prototype object with + comments that conforms to the given schema. + """ + if seen is None: + seen = [] + + if name in seen: + # Do not fall into an infinite loop over recursive definitions. + return "# Object with schema name: %s" % name + seen.append(name) + + if name not in self.pretty: + self.pretty[name] = _SchemaToStruct( + self.schemas[name], seen, dent=dent + ).to_str(self._prettyPrintByName) + + seen.pop() + + return self.pretty[name] + + def prettyPrintByName(self, name): + """Get pretty printed object prototype from the schema name. + + Args: + name: string, Name of schema in the discovery document. + + Returns: + string, A string that contains a prototype object with + comments that conforms to the given schema. + """ + # Return with trailing comma and newline removed. + return self._prettyPrintByName(name, seen=[], dent=0)[:-2] + + @util.positional(2) + def _prettyPrintSchema(self, schema, seen=None, dent=0): + """Get pretty printed object prototype of schema. + + Args: + schema: object, Parsed JSON schema. + seen: list of string, Names of schema already seen. Used to handle + recursive definitions. + + Returns: + string, A string that contains a prototype object with + comments that conforms to the given schema. + """ + if seen is None: + seen = [] + + return _SchemaToStruct(schema, seen, dent=dent).to_str(self._prettyPrintByName) + + def prettyPrintSchema(self, schema): + """Get pretty printed object prototype of schema. + + Args: + schema: object, Parsed JSON schema. + + Returns: + string, A string that contains a prototype object with + comments that conforms to the given schema. + """ + # Return with trailing comma and newline removed. + return self._prettyPrintSchema(schema, dent=0)[:-2] + + def get(self, name, default=None): + """Get deserialized JSON schema from the schema name. + + Args: + name: string, Schema name. + default: object, return value if name not found. + """ + return self.schemas.get(name, default) + + +class _SchemaToStruct(object): + """Convert schema to a prototype object.""" + + @util.positional(3) + def __init__(self, schema, seen, dent=0): + """Constructor. + + Args: + schema: object, Parsed JSON schema. + seen: list, List of names of schema already seen while parsing. Used to + handle recursive definitions. + dent: int, Initial indentation depth. + """ + # The result of this parsing kept as list of strings. + self.value = [] + + # The final value of the parsing. + self.string = None + + # The parsed JSON schema. + self.schema = schema + + # Indentation level. + self.dent = dent + + # Method that when called returns a prototype object for the schema with + # the given name. + self.from_cache = None + + # List of names of schema already seen while parsing. + self.seen = seen + + def emit(self, text): + """Add text as a line to the output. + + Args: + text: string, Text to output. + """ + self.value.extend([" " * self.dent, text, "\n"]) + + def emitBegin(self, text): + """Add text to the output, but with no line terminator. + + Args: + text: string, Text to output. + """ + self.value.extend([" " * self.dent, text]) + + def emitEnd(self, text, comment): + """Add text and comment to the output with line terminator. + + Args: + text: string, Text to output. + comment: string, Python comment. + """ + if comment: + divider = "\n" + " " * (self.dent + 2) + "# " + lines = comment.splitlines() + lines = [x.rstrip() for x in lines] + comment = divider.join(lines) + self.value.extend([text, " # ", comment, "\n"]) + else: + self.value.extend([text, "\n"]) + + def indent(self): + """Increase indentation level.""" + self.dent += 1 + + def undent(self): + """Decrease indentation level.""" + self.dent -= 1 + + def _to_str_impl(self, schema): + """Prototype object based on the schema, in Python code with comments. + + Args: + schema: object, Parsed JSON schema file. + + Returns: + Prototype object based on the schema, in Python code with comments. + """ + stype = schema.get("type") + if stype == "object": + self.emitEnd("{", schema.get("description", "")) + self.indent() + if "properties" in schema: + properties = schema.get("properties", {}) + sorted_properties = OrderedDict(sorted(properties.items())) + for pname, pschema in sorted_properties.items(): + self.emitBegin('"%s": ' % pname) + self._to_str_impl(pschema) + elif "additionalProperties" in schema: + self.emitBegin('"a_key": ') + self._to_str_impl(schema["additionalProperties"]) + self.undent() + self.emit("},") + elif "$ref" in schema: + schemaName = schema["$ref"] + description = schema.get("description", "") + s = self.from_cache(schemaName, seen=self.seen) + parts = s.splitlines() + self.emitEnd(parts[0], description) + for line in parts[1:]: + self.emit(line.rstrip()) + elif stype == "boolean": + value = schema.get("default", "True or False") + self.emitEnd("%s," % str(value), schema.get("description", "")) + elif stype == "string": + value = schema.get("default", "A String") + self.emitEnd('"%s",' % str(value), schema.get("description", "")) + elif stype == "integer": + value = schema.get("default", "42") + self.emitEnd("%s," % str(value), schema.get("description", "")) + elif stype == "number": + value = schema.get("default", "3.14") + self.emitEnd("%s," % str(value), schema.get("description", "")) + elif stype == "null": + self.emitEnd("None,", schema.get("description", "")) + elif stype == "any": + self.emitEnd('"",', schema.get("description", "")) + elif stype == "array": + self.emitEnd("[", schema.get("description")) + self.indent() + self.emitBegin("") + self._to_str_impl(schema["items"]) + self.undent() + self.emit("],") + else: + self.emit("Unknown type! %s" % stype) + self.emitEnd("", "") + + self.string = "".join(self.value) + return self.string + + def to_str(self, from_cache): + """Prototype object based on the schema, in Python code with comments. + + Args: + from_cache: callable(name, seen), Callable that retrieves an object + prototype for a schema with the given name. Seen is a list of schema + names already seen as we recursively descend the schema definition. + + Returns: + Prototype object based on the schema, in Python code with comments. + The lines of the code will all be properly indented. + """ + self.from_cache = from_cache + return self._to_str_impl(self.schema) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/googleapiclient/version.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/googleapiclient/version.py new file mode 100644 index 0000000000000000000000000000000000000000..a853d00bcc739d65618c5e889754827a340f29fd --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/googleapiclient/version.py @@ -0,0 +1,15 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +__version__ = "2.196.0" diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/httplib2-0.31.2.dist-info/INSTALLER b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/httplib2-0.31.2.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/httplib2-0.31.2.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/httplib2-0.31.2.dist-info/METADATA b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/httplib2-0.31.2.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..290797c15382779b59bdfc84618f2d4d12267113 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/httplib2-0.31.2.dist-info/METADATA @@ -0,0 +1,74 @@ +Metadata-Version: 2.4 +Name: httplib2 +Version: 0.31.2 +Summary: A comprehensive HTTP client library. +Home-page: https://github.com/httplib2/httplib2 +Author: Joe Gregorio +Author-email: joe@bitworking.org +License: MIT +Classifier: Development Status :: 4 - Beta +Classifier: Environment :: Web Environment +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Topic :: Internet :: WWW/HTTP +Classifier: Topic :: Software Development :: Libraries +Requires-Python: >=3.6 +License-File: LICENSE +Requires-Dist: pyparsing<4,>=3.1 +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: home-page +Dynamic: license +Dynamic: license-file +Dynamic: requires-dist +Dynamic: requires-python +Dynamic: summary + + + +A comprehensive HTTP client library, ``httplib2`` supports many features left out of other HTTP libraries. + +**HTTP and HTTPS** + HTTPS support is only available if the socket module was compiled with SSL support. + + +**Keep-Alive** + Supports HTTP 1.1 Keep-Alive, keeping the socket open and performing multiple requests over the same connection if possible. + + +**Authentication** + The following three types of HTTP Authentication are supported. These can be used over both HTTP and HTTPS. + + * Digest + * Basic + * WSSE + +**Caching** + The module can optionally operate with a private cache that understands the Cache-Control: + header and uses both the ETag and Last-Modified cache validators. Both file system + and memcached based caches are supported. + + +**All Methods** + The module can handle any HTTP request method, not just GET and POST. + + +**Redirects** + Automatically follows 3XX redirects on GETs. + + +**Compression** + Handles both 'deflate' and 'gzip' types of compression. + + +**Lost update support** + Automatically adds back ETags into PUT requests to resources we have already cached. This implements Section 3.2 of Detecting the Lost Update Problem Using Unreserved Checkout + + +**Unit Tested** + A large and growing set of unit tests. diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/httplib2-0.31.2.dist-info/RECORD b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/httplib2-0.31.2.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..3709f74e2df6cb74c3bdf18c222c670437961513 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/httplib2-0.31.2.dist-info/RECORD @@ -0,0 +1,17 @@ +httplib2-0.31.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +httplib2-0.31.2.dist-info/METADATA,sha256=uuo7PhRTCy_oTXC994rsDkcSCyXHRXFvnrzq542u5-8,2159 +httplib2-0.31.2.dist-info/RECORD,, +httplib2-0.31.2.dist-info/WHEEL,sha256=qELbo2s1Yzl39ZmrAibXA2jjPLUYfnVhUNTlyF1rq0Y,92 +httplib2-0.31.2.dist-info/licenses/LICENSE,sha256=WJ7sOPct8r4gNxHTuMvs6bkIxef_ALw8q39juunjZrQ,1086 +httplib2-0.31.2.dist-info/top_level.txt,sha256=BEY8ChKwagUWmu9x8yN9JObJpZKNeWCr1E-sIECb56I,9 +httplib2/__init__.py,sha256=kBcfsfoowv2ejYqP3fDyVSiHPKL6JKhL-2Bu2npJ5_o,69471 +httplib2/__pycache__/__init__.cpython-310.pyc,, +httplib2/__pycache__/auth.cpython-310.pyc,, +httplib2/__pycache__/certs.cpython-310.pyc,, +httplib2/__pycache__/error.cpython-310.pyc,, +httplib2/__pycache__/iri2uri.cpython-310.pyc,, +httplib2/auth.py,sha256=bw1wOT0cbilWGsN1MAupd9mpS_S8vLDl8vgKrPdH0m0,2038 +httplib2/cacerts.txt,sha256=AbmYP54iGeKRQ1APtfQvHlo9wul2jVmznmbTzy2fTV4,137365 +httplib2/certs.py,sha256=guhfjMNhDdKJEyYBb5ZyLxVO5q1I7Y_P-4BG8MniBk8,971 +httplib2/error.py,sha256=GyqPUvZeKdVLq0f3xg0uX4rjtv7jVGJuPerAdyc-jfk,954 +httplib2/iri2uri.py,sha256=PhIzEzeR6C73l7piwrNAJlVvlWgsqxtJTlFeXgznzQo,4153 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/httplib2-0.31.2.dist-info/WHEEL b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/httplib2-0.31.2.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..fbbd86cb272bc6e329803bf67f442f2a124caa95 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/httplib2-0.31.2.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.10.1) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/httplib2-0.31.2.dist-info/top_level.txt b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/httplib2-0.31.2.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..fb881ece05bf2f998d84be544449ac976da2897c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/httplib2-0.31.2.dist-info/top_level.txt @@ -0,0 +1 @@ +httplib2 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/jiter-0.14.0.dist-info/INSTALLER b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/jiter-0.14.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/jiter-0.14.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/jiter-0.14.0.dist-info/METADATA b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/jiter-0.14.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..0f3ccc978846282e06ead969f7d815c78c3ddfca --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/jiter-0.14.0.dist-info/METADATA @@ -0,0 +1,148 @@ +Metadata-Version: 2.4 +Name: jiter +Version: 0.14.0 +Classifier: Development Status :: 4 - Beta +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +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.14 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: GraalPy +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Information Technology +Classifier: Intended Audience :: System Administrators +Classifier: Operating System :: Unix +Classifier: Operating System :: POSIX :: Linux +Classifier: Environment :: Console +Classifier: Environment :: MacOS X +Classifier: Topic :: File Formats :: JSON +Classifier: Framework :: Pydantic :: 2 +License-File: LICENSE +Summary: Fast iterable JSON parser. +Home-Page: https://github.com/pydantic/jiter/ +Author-email: Samuel Colvin +License-Expression: MIT +Requires-Python: >=3.9 +Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM + +# jiter + +[![CI](https://github.com/pydantic/jiter/workflows/CI/badge.svg?event=push)](https://github.com/pydantic/jiter/actions?query=event%3Apush+branch%3Amain+workflow%3ACI) +[![pypi](https://img.shields.io/pypi/v/jiter.svg)](https://pypi.python.org/pypi/jiter) +[![versions](https://img.shields.io/pypi/pyversions/jiter.svg)](https://github.com/pydantic/jiter) +[![license](https://img.shields.io/github/license/pydantic/jiter.svg)](https://github.com/pydantic/jiter/blob/main/LICENSE) + +This is a standalone version of the JSON parser used in `pydantic-core`. The recommendation is to only use this package directly if you do not use `pydantic`. + +The API is extremely minimal: + +```python +def from_json( + json_data: bytes, + /, + *, + allow_inf_nan: bool = True, + cache_mode: Literal[True, False, 'all', 'keys', 'none'] = 'all', + partial_mode: Literal[True, False, 'off', 'on', 'trailing-strings'] = False, + catch_duplicate_keys: bool = False, + float_mode: Literal['float', 'decimal', 'lossless-float'] = 'float', +) -> Any: + """ + Parse input bytes into a JSON object. + + Arguments: + json_data: The JSON data to parse + allow_inf_nan: Whether to allow infinity (`Infinity` an `-Infinity`) and `NaN` values to float fields. + Defaults to True. + cache_mode: cache Python strings to improve performance at the cost of some memory usage + - True / 'all' - cache all strings + - 'keys' - cache only object keys + - False / 'none' - cache nothing + partial_mode: How to handle incomplete strings: + - False / 'off' - raise an exception if the input is incomplete + - True / 'on' - allow incomplete JSON but discard the last string if it is incomplete + - 'trailing-strings' - allow incomplete JSON, and include the last incomplete string in the output + catch_duplicate_keys: if True, raise an exception if objects contain the same key multiple times + float_mode: How to return floats: as a `float`, `Decimal` or `LosslessFloat` + + Returns: + Python object built from the JSON input. + """ + + +def cache_clear() -> None: + """ + Reset the string cache. + """ + + +def cache_usage() -> int: + """ + get the size of the string cache. + + Returns: + Size of the string cache in bytes. + """ + +``` +## Examples + +The main function provided by Jiter is `from_json()`, which accepts a bytes object containing JSON and returns a Python dictionary, list or other value. + +```python +import jiter + +json_data = b'{"name": "John", "age": 30}' +parsed_data = jiter.from_json(json_data) +print(parsed_data) # Output: {'name': 'John', 'age': 30} +``` + +### Handling Partial JSON + +Incomplete JSON objects can be parsed using the `partial_mode=` parameter. + +```python +import jiter + +partial_json = b'{"name": "John", "age": 30, "city": "New Yor' + +# Raise error on incomplete JSON +try: + jiter.from_json(partial_json, partial_mode=False) +except ValueError as e: + print(f'Error: {e}') + +# Parse incomplete JSON, discarding incomplete last field +result = jiter.from_json(partial_json, partial_mode=True) +print(result) # Output: {'name': 'John', 'age': 30} + +# Parse incomplete JSON, including incomplete last field +result = jiter.from_json(partial_json, partial_mode='trailing-strings') +print(result) # Output: {'name': 'John', 'age': 30, 'city': 'New Yor'} +``` + +### Catching Duplicate Keys + +The `catch_duplicate_keys=True` option can be used to raise a `ValueError` if an object contains duplicate keys. + +```python +import jiter + +json_with_dupes = b'{"foo": 1, "foo": 2}' + +# Default behavior (last value wins) +result = jiter.from_json(json_with_dupes) +print(result) # Output: {'foo': 2} + +# Catch duplicate keys +try: + jiter.from_json(json_with_dupes, catch_duplicate_keys=True) +except ValueError as e: + print(f'Error: {e}') +``` + diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/jiter-0.14.0.dist-info/RECORD b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/jiter-0.14.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..bf4a419fd431e0297420753f00119c88aa0c080b --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/jiter-0.14.0.dist-info/RECORD @@ -0,0 +1,11 @@ +jiter-0.14.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +jiter-0.14.0.dist-info/METADATA,sha256=0lyKL1x9Gu78v5TYL6MguN-TXK0fdIzKLSC8mmIQvZI,5212 +jiter-0.14.0.dist-info/RECORD,, +jiter-0.14.0.dist-info/WHEEL,sha256=jsL9AqN9wHrgjdRkhDDyROu74_A4owfvDSioN563i9w,147 +jiter-0.14.0.dist-info/licenses/LICENSE,sha256=fHE0ufe5eMA_yodVF885jbkfGbu4EJtmhedCqj9XRo4,1091 +jiter-0.14.0.dist-info/sboms/jiter-python.cyclonedx.json,sha256=0n2mOSeLL1tTBA9viSa9onS6L2FZ4QhPGuFJ4KB753I,83375 +jiter/__init__.py,sha256=Fp9HkOixiYYDSiC_80vmiJ_sCoCGT8OAh48yltm0lP0,103 +jiter/__init__.pyi,sha256=UJVBfIIdO79ycPzZZ7wqL6SLBgFmzCMOZv0J6kybmpM,2378 +jiter/__pycache__/__init__.cpython-310.pyc,, +jiter/jiter.cpython-310-x86_64-linux-gnu.so,sha256=Id8CQMJzTMZYFZza652fo0T884BjRa10azx2yHNeysI,839648 +jiter/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/jiter-0.14.0.dist-info/WHEEL b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/jiter-0.14.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..89485cdbb8fc9bb4cc58c2844fefca934048a747 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/jiter-0.14.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: maturin (1.13.1) +Root-Is-Purelib: false +Tag: cp310-cp310-manylinux_2_17_x86_64 +Tag: cp310-cp310-manylinux2014_x86_64 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/jsonschema-4.26.0.dist-info/INSTALLER b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/jsonschema-4.26.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/jsonschema-4.26.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/jsonschema-4.26.0.dist-info/METADATA b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/jsonschema-4.26.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..ba828d2ee3ae2f249d3522ba707b8eb46cf582d7 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/jsonschema-4.26.0.dist-info/METADATA @@ -0,0 +1,170 @@ +Metadata-Version: 2.4 +Name: jsonschema +Version: 4.26.0 +Summary: An implementation of JSON Schema validation for Python +Project-URL: Homepage, https://github.com/python-jsonschema/jsonschema +Project-URL: Documentation, https://python-jsonschema.readthedocs.io/ +Project-URL: Issues, https://github.com/python-jsonschema/jsonschema/issues/ +Project-URL: Funding, https://github.com/sponsors/Julian +Project-URL: Tidelift, https://tidelift.com/subscription/pkg/pypi-jsonschema?utm_source=pypi-jsonschema&utm_medium=referral&utm_campaign=pypi-link +Project-URL: Changelog, https://github.com/python-jsonschema/jsonschema/blob/main/CHANGELOG.rst +Project-URL: Source, https://github.com/python-jsonschema/jsonschema +Author-email: Julian Berman +License-Expression: MIT +License-File: COPYING +Keywords: data validation,json,json schema,jsonschema,validation +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +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 :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: File Formats :: JSON +Classifier: Topic :: File Formats :: JSON :: JSON Schema +Requires-Python: >=3.10 +Requires-Dist: attrs>=22.2.0 +Requires-Dist: jsonschema-specifications>=2023.03.6 +Requires-Dist: referencing>=0.28.4 +Requires-Dist: rpds-py>=0.25.0 +Provides-Extra: format +Requires-Dist: fqdn; extra == 'format' +Requires-Dist: idna; extra == 'format' +Requires-Dist: isoduration; extra == 'format' +Requires-Dist: jsonpointer>1.13; extra == 'format' +Requires-Dist: rfc3339-validator; extra == 'format' +Requires-Dist: rfc3987; extra == 'format' +Requires-Dist: uri-template; extra == 'format' +Requires-Dist: webcolors>=1.11; extra == 'format' +Provides-Extra: format-nongpl +Requires-Dist: fqdn; extra == 'format-nongpl' +Requires-Dist: idna; extra == 'format-nongpl' +Requires-Dist: isoduration; extra == 'format-nongpl' +Requires-Dist: jsonpointer>1.13; extra == 'format-nongpl' +Requires-Dist: rfc3339-validator; extra == 'format-nongpl' +Requires-Dist: rfc3986-validator>0.1.0; extra == 'format-nongpl' +Requires-Dist: rfc3987-syntax>=1.1.0; extra == 'format-nongpl' +Requires-Dist: uri-template; extra == 'format-nongpl' +Requires-Dist: webcolors>=24.6.0; extra == 'format-nongpl' +Description-Content-Type: text/x-rst + +========== +jsonschema +========== + +|PyPI| |Pythons| |CI| |ReadTheDocs| |Precommit| |Zenodo| + +.. |PyPI| image:: https://img.shields.io/pypi/v/jsonschema.svg + :alt: PyPI version + :target: https://pypi.org/project/jsonschema/ + +.. |Pythons| image:: https://img.shields.io/pypi/pyversions/jsonschema.svg + :alt: Supported Python versions + :target: https://pypi.org/project/jsonschema/ + +.. |CI| image:: https://github.com/python-jsonschema/jsonschema/workflows/CI/badge.svg + :alt: Build status + :target: https://github.com/python-jsonschema/jsonschema/actions?query=workflow%3ACI + +.. |ReadTheDocs| image:: https://readthedocs.org/projects/python-jsonschema/badge/?version=stable&style=flat + :alt: ReadTheDocs status + :target: https://python-jsonschema.readthedocs.io/en/stable/ + +.. |Precommit| image:: https://results.pre-commit.ci/badge/github/python-jsonschema/jsonschema/main.svg + :alt: pre-commit.ci status + :target: https://results.pre-commit.ci/latest/github/python-jsonschema/jsonschema/main + +.. |Zenodo| image:: https://zenodo.org/badge/3072629.svg + :alt: Zenodo DOI + :target: https://zenodo.org/badge/latestdoi/3072629 + + +``jsonschema`` is an implementation of the `JSON Schema `_ specification for Python. + +.. code:: python + + >>> from jsonschema import validate + + >>> # A sample schema, like what we'd get from json.load() + >>> schema = { + ... "type" : "object", + ... "properties" : { + ... "price" : {"type" : "number"}, + ... "name" : {"type" : "string"}, + ... }, + ... } + + >>> # If no exception is raised by validate(), the instance is valid. + >>> validate(instance={"name" : "Eggs", "price" : 34.99}, schema=schema) + + >>> validate( + ... instance={"name" : "Eggs", "price" : "Invalid"}, schema=schema, + ... ) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + ValidationError: 'Invalid' is not of type 'number' + +It can also be used from the command line by installing `check-jsonschema `_. + +Features +-------- + +* Full support for `Draft 2020-12 `_, `Draft 2019-09 `_, `Draft 7 `_, `Draft 6 `_, `Draft 4 `_ and `Draft 3 `_ + +* `Lazy validation `_ that can iteratively report *all* validation errors. + +* `Programmatic querying `_ of which properties or items failed validation. + + +Installation +------------ + +``jsonschema`` is available on `PyPI `_. You can install using `pip `_: + +.. code:: bash + + $ pip install jsonschema + + +Extras +====== + +Two extras are available when installing the package, both currently related to ``format`` validation: + + * ``format`` + * ``format-nongpl`` + +They can be used when installing in order to include additional dependencies, e.g.: + +.. code:: bash + + $ pip install jsonschema'[format]' + +Be aware that the mere presence of these dependencies – or even the specification of ``format`` checks in a schema – do *not* activate format checks (as per the specification). +Please read the `format validation documentation `_ for further details. + +About +----- + +I'm Julian Berman. + +``jsonschema`` is on `GitHub `_. + +Get in touch, via GitHub or otherwise, if you've got something to contribute, it'd be most welcome! + +If you feel overwhelmingly grateful, you can also `sponsor me `_. + +And for companies who appreciate ``jsonschema`` and its continued support and growth, ``jsonschema`` is also now supportable via `TideLift `_. + + +Release Information +------------------- + +v4.26.0 +======= + +* Decrease import time by delaying importing of ``urllib.request`` (#1416). diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/jsonschema-4.26.0.dist-info/RECORD b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/jsonschema-4.26.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..14cc9799b5c58b7f8a36ff710796b19ab5b95985 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/jsonschema-4.26.0.dist-info/RECORD @@ -0,0 +1,82 @@ +../../../bin/jsonschema,sha256=-P9IEGdx3wanAINAhTAnn4rOXn7-QtnhKXmwYXCVnAA,247 +jsonschema-4.26.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +jsonschema-4.26.0.dist-info/METADATA,sha256=BbGJhmypipbaOTS_a4NofO0_-FMlJzt34WtwX22LJtI,7592 +jsonschema-4.26.0.dist-info/RECORD,, +jsonschema-4.26.0.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87 +jsonschema-4.26.0.dist-info/entry_points.txt,sha256=vO7rX4Fs_xIVJy2pnAtKgTSxfpnozAVQ0DjCmpMxnWE,51 +jsonschema-4.26.0.dist-info/licenses/COPYING,sha256=T5KgFaE8TRoEC-8BiqE0MLTxvHO0Gxa7hGw0Z2bedDk,1057 +jsonschema/__init__.py,sha256=p-Rw4TS_0OPHZIJyImDWsdWgmd6CPWHMXLq7BuQxTGc,3941 +jsonschema/__main__.py,sha256=iLsZf2upUB3ilBKTlMnyK-HHt2Cnnfkwwxi_c6gLvSA,115 +jsonschema/__pycache__/__init__.cpython-310.pyc,, +jsonschema/__pycache__/__main__.cpython-310.pyc,, +jsonschema/__pycache__/_format.cpython-310.pyc,, +jsonschema/__pycache__/_keywords.cpython-310.pyc,, +jsonschema/__pycache__/_legacy_keywords.cpython-310.pyc,, +jsonschema/__pycache__/_types.cpython-310.pyc,, +jsonschema/__pycache__/_typing.cpython-310.pyc,, +jsonschema/__pycache__/_utils.cpython-310.pyc,, +jsonschema/__pycache__/cli.cpython-310.pyc,, +jsonschema/__pycache__/exceptions.cpython-310.pyc,, +jsonschema/__pycache__/protocols.cpython-310.pyc,, +jsonschema/__pycache__/validators.cpython-310.pyc,, +jsonschema/_format.py,sha256=lrs1U7iSB2ZX9Z2EalsROYeQm1d9kefw2CLo08G8P4s,15568 +jsonschema/_keywords.py,sha256=r8_DrqAfn6QLwQnmXEggveiSU-UaIL2p2nuPINelfFc,14949 +jsonschema/_legacy_keywords.py,sha256=2tWuwRPWbYS7EAl8wBIC_rabGuv1J4dfYLqNEPpShhA,15191 +jsonschema/_types.py,sha256=f_nkTDbrja3E3fsINTC73y_gMXTU210I_H7qK0NN30c,5456 +jsonschema/_typing.py,sha256=pXLnGy3jNtIUTq037kUfq0we17085eHtJwDJ2t--mQE,617 +jsonschema/_utils.py,sha256=Xv6_wKKslBJlwyj9-j2c8JDFw-4z4aWFnVe2pX8h7U4,10659 +jsonschema/benchmarks/__init__.py,sha256=A0sQrxDBVHSyQ-8ru3L11hMXf3q9gVuB9x_YgHb4R9M,70 +jsonschema/benchmarks/__pycache__/__init__.cpython-310.pyc,, +jsonschema/benchmarks/__pycache__/const_vs_enum.cpython-310.pyc,, +jsonschema/benchmarks/__pycache__/contains.cpython-310.pyc,, +jsonschema/benchmarks/__pycache__/import_benchmark.cpython-310.pyc,, +jsonschema/benchmarks/__pycache__/issue232.cpython-310.pyc,, +jsonschema/benchmarks/__pycache__/json_schema_test_suite.cpython-310.pyc,, +jsonschema/benchmarks/__pycache__/nested_schemas.cpython-310.pyc,, +jsonschema/benchmarks/__pycache__/subcomponents.cpython-310.pyc,, +jsonschema/benchmarks/__pycache__/unused_registry.cpython-310.pyc,, +jsonschema/benchmarks/__pycache__/useless_applicator_schemas.cpython-310.pyc,, +jsonschema/benchmarks/__pycache__/useless_keywords.cpython-310.pyc,, +jsonschema/benchmarks/__pycache__/validator_creation.cpython-310.pyc,, +jsonschema/benchmarks/const_vs_enum.py,sha256=DVFi3WDqBalZFOibnjpX1uTSr3Rxa2cPgFcowd7Ukrs,830 +jsonschema/benchmarks/contains.py,sha256=gexQoUrCOwECofbt19BeosQZ7WFL6PDdkX49DWwBlOg,786 +jsonschema/benchmarks/import_benchmark.py,sha256=2DRIOVS6p-bqLn_822B_X5FkIRvsJ2V1CYnV2druzDs,779 +jsonschema/benchmarks/issue232.py,sha256=3LLYLIlBGQnVuyyo2iAv-xky5P6PRFHANx4-zIIQOoE,521 +jsonschema/benchmarks/issue232/issue.json,sha256=eaPOZjMRu5u8RpKrsA9uk7ucPZS5tkKG4D_hkOTQ3Hk,117105 +jsonschema/benchmarks/json_schema_test_suite.py,sha256=PvfabpUYcF4_7csYDTcTauED8rnFEGYbdY5RqTXD08s,320 +jsonschema/benchmarks/nested_schemas.py,sha256=mo07dx-CIgmSOI62CNs4g5xu1FzHklLBpkQoDxWYcKs,1892 +jsonschema/benchmarks/subcomponents.py,sha256=fEyiMzsWeK2pd7DEGCuuY-vzGunwhHczRBWEnBRLKIo,1113 +jsonschema/benchmarks/unused_registry.py,sha256=hwRwONc9cefPtYzkoX_TYRO3GyUojriv0-YQaK3vnj0,940 +jsonschema/benchmarks/useless_applicator_schemas.py,sha256=EVm5-EtOEFoLP_Vt2j4SrCwlx05NhPqNuZQ6LIMP1Dc,3342 +jsonschema/benchmarks/useless_keywords.py,sha256=bj_zKr1oVctFlqyZaObCsYTgFjiiNgPzC0hr1Y868mE,867 +jsonschema/benchmarks/validator_creation.py,sha256=UkUQlLAnussnr_KdCIdad6xx2pXxQLmYtsXoiirKeWQ,285 +jsonschema/cli.py,sha256=av90OtpSxuiko3FAyEHtxpI-NSuX3WMtoQpIx09obJY,8445 +jsonschema/exceptions.py,sha256=b42hUDOfPFcprI4ZlNpjDeLKv8k9vOhgWct2jyDlxzk,15256 +jsonschema/protocols.py,sha256=lgyryVHqFijSFRAz95ch3VN2Fz-oTFyhj9Obcy5P_CI,7198 +jsonschema/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +jsonschema/tests/__pycache__/__init__.cpython-310.pyc,, +jsonschema/tests/__pycache__/_suite.cpython-310.pyc,, +jsonschema/tests/__pycache__/fuzz_validate.cpython-310.pyc,, +jsonschema/tests/__pycache__/test_cli.cpython-310.pyc,, +jsonschema/tests/__pycache__/test_deprecations.cpython-310.pyc,, +jsonschema/tests/__pycache__/test_exceptions.cpython-310.pyc,, +jsonschema/tests/__pycache__/test_format.cpython-310.pyc,, +jsonschema/tests/__pycache__/test_jsonschema_test_suite.cpython-310.pyc,, +jsonschema/tests/__pycache__/test_types.cpython-310.pyc,, +jsonschema/tests/__pycache__/test_utils.cpython-310.pyc,, +jsonschema/tests/__pycache__/test_validators.cpython-310.pyc,, +jsonschema/tests/_suite.py,sha256=2k0X91N7dOHhQc5mrYv40OKf1weioj6RMBqWgLT6-PI,8374 +jsonschema/tests/fuzz_validate.py,sha256=fUA7yTJIihaCwJplkUehZeyB84HcXEcqtY5oPJXIO7I,1114 +jsonschema/tests/test_cli.py,sha256=A89r5LOHy-peLPZA5YDkOaMTWqzQO_w2Tu8WFz_vphM,28544 +jsonschema/tests/test_deprecations.py,sha256=yG6mkRJHpTHbWoxpLC5y5H7fk8erGOs8f_9V4tCBEh8,15754 +jsonschema/tests/test_exceptions.py,sha256=rsEqdjknUz3dEyJb6_DiModPHXsJTEWzDrxUscg8G5o,24301 +jsonschema/tests/test_format.py,sha256=eVm5SMaWF2lOPO28bPAwNvkiQvHCQKy-MnuAgEchfEc,3188 +jsonschema/tests/test_jsonschema_test_suite.py,sha256=tAfxknM65OR9LyDPHu1pkEaombLgjRLnJ6FPiWPdxjg,8461 +jsonschema/tests/test_types.py,sha256=cF51KTDmdsx06MrIc4fXKt0X9fIsVgw5uhT8CamVa8U,6977 +jsonschema/tests/test_utils.py,sha256=sao74o1PyYMxBfqweokQN48CFSS6yhJk5FkCfMJ5PsI,4163 +jsonschema/tests/test_validators.py,sha256=uzl-agyLoZPTufouIHSxFPfPYrdIdjNwjHcD_5NyU4E,87949 +jsonschema/tests/typing/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +jsonschema/tests/typing/__pycache__/__init__.cpython-310.pyc,, +jsonschema/tests/typing/__pycache__/test_all_concrete_validators_match_protocol.cpython-310.pyc,, +jsonschema/tests/typing/test_all_concrete_validators_match_protocol.py,sha256=I5XUl5ZYUSZo3APkF10l8Mnfk09oXKqvXWttGGd3sDk,1238 +jsonschema/validators.py,sha256=l_FxuZW0sMoFUwqTZqElL7F1P5nzy3sQaLbZqrEJb6U,47159 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/jsonschema-4.26.0.dist-info/WHEEL b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/jsonschema-4.26.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..ae8ec1bdaa94d726ceb907542d76cbd5d38cafcd --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/jsonschema-4.26.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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/jsonschema-4.26.0.dist-info/entry_points.txt b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/jsonschema-4.26.0.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..eecef9d8fad351de6b048532776160696a796ef9 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/jsonschema-4.26.0.dist-info/entry_points.txt @@ -0,0 +1,2 @@ +[console_scripts] +jsonschema = jsonschema.cli:main diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/jsonschema_specifications/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/jsonschema_specifications/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a4235741bfdd251e270ce3b26fa7fb1bf4044b78 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/jsonschema_specifications/__init__.py @@ -0,0 +1,12 @@ +""" +The JSON Schema meta-schemas and vocabularies, exposed as a Registry. +""" + +from referencing.jsonschema import EMPTY_REGISTRY as _EMPTY_REGISTRY + +from jsonschema_specifications._core import _schemas + +#: A `referencing.jsonschema.SchemaRegistry` containing all of the official +#: meta-schemas and vocabularies. +REGISTRY = (_schemas() @ _EMPTY_REGISTRY).crawl() +__all__ = ["REGISTRY"] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/jsonschema_specifications/_core.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/jsonschema_specifications/_core.py new file mode 100644 index 0000000000000000000000000000000000000000..e67bd712b3732f20ec353ba1d8b5c806fad2c74a --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/jsonschema_specifications/_core.py @@ -0,0 +1,38 @@ +""" +Load all the JSON Schema specification's official schemas. +""" + +import json + +try: + from importlib.resources import files +except ImportError: + from importlib_resources import ( # type: ignore[import-not-found, no-redef] + files, + ) + +from referencing import Resource + + +def _schemas(): + """ + All schemas we ship. + """ + # importlib.resources.abc.Traversal doesn't have nice ways to do this that + # I'm aware of... + # + # It can't recurse arbitrarily, e.g. no ``.glob()``. + # + # So this takes some liberties given the real layout of what we ship + # (only 2 levels of nesting, no directories within the second level). + + for version in files(__package__).joinpath("schemas").iterdir(): + if version.name.startswith("."): + continue + for child in version.iterdir(): + children = [child] if child.is_file() else child.iterdir() + for path in children: + if path.name.startswith("."): + continue + contents = json.loads(path.read_text(encoding="utf-8")) + yield Resource.from_contents(contents) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/murmurhash/__init__.pxd b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/murmurhash/__init__.pxd new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/murmurhash/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/murmurhash/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..601da1cc9deceba3826946f1a5a53744a33eb806 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/murmurhash/__init__.py @@ -0,0 +1,7 @@ +import os +from .about import * +from .mrmr import hash, hash_unicode, hash_bytes + + +def get_include(): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), "include") diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/murmurhash/about.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/murmurhash/about.py new file mode 100644 index 0000000000000000000000000000000000000000..d9245f158cc2f2ef8a8070f863625c2ba3a6813c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/murmurhash/about.py @@ -0,0 +1,7 @@ +__title__ = "murmurhash" +__version__ = "1.0.15" +__summary__ = "Cython bindings for MurmurHash" +__uri__ = "https://github.com/explosion/murmurhash" +__author__ = "Explosion" +__email__ = "contact@explosion.ai" +__license__ = "MIT" diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/murmurhash/mrmr.pxd b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/murmurhash/mrmr.pxd new file mode 100644 index 0000000000000000000000000000000000000000..341228b25dc1f1f8cea27d7ee5cbd63980dbd869 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/murmurhash/mrmr.pxd @@ -0,0 +1,8 @@ +from libc.stdint cimport uint64_t, int64_t, uint32_t + + +cdef uint32_t hash32(void* key, int length, uint32_t seed) noexcept nogil +cdef uint64_t hash64(void* key, int length, uint64_t seed) noexcept nogil +cdef uint64_t real_hash64(void* key, int length, uint64_t seed) noexcept nogil +cdef void hash128_x86(const void* key, int len, uint32_t seed, void* out) noexcept nogil +cdef void hash128_x64(const void* key, int len, uint32_t seed, void* out) noexcept nogil diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/murmurhash/mrmr.pyx b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/murmurhash/mrmr.pyx new file mode 100644 index 0000000000000000000000000000000000000000..1cd3251c30a9fecb357773a381a69d0a7e630eb7 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/murmurhash/mrmr.pyx @@ -0,0 +1,51 @@ +# cython: freethreading_compatible=True +from libc.stdint cimport uint64_t, int64_t, int32_t + + +cdef extern from "murmurhash/MurmurHash3.h": + void MurmurHash3_x86_32(void * key, uint64_t len, uint64_t seed, void* out) noexcept nogil + void MurmurHash3_x86_128(void * key, int len, uint32_t seed, void* out) noexcept nogil + void MurmurHash3_x64_128(void * key, int len, uint32_t seed, void* out) noexcept nogil + +cdef extern from "murmurhash/MurmurHash2.h": + uint64_t MurmurHash64A(void * key, int length, uint32_t seed) noexcept nogil + uint64_t MurmurHash64B(void * key, int length, uint32_t seed) noexcept nogil + + +cdef uint32_t hash32(void* key, int length, uint32_t seed) noexcept nogil: + cdef int32_t out + MurmurHash3_x86_32(key, length, seed, &out) + return out + + +cdef uint64_t hash64(void* key, int length, uint64_t seed) noexcept nogil: + return MurmurHash64A(key, length, seed) + +cdef uint64_t real_hash64(void* key, int length, uint64_t seed) noexcept nogil: + cdef uint64_t[2] out + MurmurHash3_x86_128(key, length, seed, &out) + return out[1] + + +cdef void hash128_x86(const void* key, int length, uint32_t seed, void* out) noexcept nogil: + MurmurHash3_x86_128(key, length, seed, out) + + +cdef void hash128_x64(const void* key, int length, uint32_t seed, void* out) noexcept nogil: + MurmurHash3_x64_128(key, length, seed, out) + + +cpdef int32_t hash(value, uint32_t seed=0): + if isinstance(value, unicode): + return hash_unicode(value, seed=seed) + else: + return hash_bytes(value, seed=seed) + + +cpdef int32_t hash_unicode(unicode value, uint32_t seed=0): + return hash_bytes(value.encode('utf8'), seed=seed) + + +cpdef int32_t hash_bytes(bytes value, uint32_t seed=0): + cdef char* chars = value + return hash32(chars, len(value), seed) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmes_docker-0.1.0.dist-info/INSTALLER b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmes_docker-0.1.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmes_docker-0.1.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmes_docker-0.1.0.dist-info/METADATA b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmes_docker-0.1.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..c30fb2268d52cfa30a2ec1178966f304489eb68b --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmes_docker-0.1.0.dist-info/METADATA @@ -0,0 +1,314 @@ +Metadata-Version: 2.4 +Name: olmes-docker +Version: 0.1.0 +Summary: Code execution environments for OLMES +Author-email: Allen Institute for Artificial Intelligence +License: 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. + +Requires-Python: <3.14,>=3.9 +Description-Content-Type: text/markdown +License-File: LICENSE +Requires-Dist: docker>=7.0.0 +Requires-Dist: httpx>=0.24.0 +Provides-Extra: dev +Requires-Dist: ruff; extra == "dev" +Requires-Dist: mypy<1.4,>=1.0; extra == "dev" +Requires-Dist: ruff; extra == "dev" +Requires-Dist: mypy<1.4,>=1.0; extra == "dev" +Provides-Extra: all +Dynamic: license-file + +## Code Execution for OLMES + +A simple wrapper for exeucting code generation in OLMES. Environments can be deployed to AWS Lambda, or run locally using Docker. Currently supports [BigCodeBench](src/bcb_execution/README.md), [MultiPL-E](src/multiple_execution/README.md) and [DS-1000](src/ds1000_execution/README.md). + +```bash +pip install -e . +docker --version # ensure docker is running! +``` + +**Quick Start** + +Manage images directly in Python: + +```python +import olmes_docker as od + +# Spin up the image (e.g. for BigCodeBench) +env = od.create_environment( + env_type="bcb", # "bcb", "ds1000", "multipl", ... + host_port=8080, + memory_limit="2g", + cpu_limit=1.0, + auto_start=True +) + +# Get endpoint name +endpoint = env.get_execute_endpoint() +print(f"Endpoint created: {endpoint}") + +# Execute a test case +result = env.execute_code( + solution="def multiply(x, y): return x * y", + test="assert multiply(3, 4) == 12", + entry_point="multiply", + task_id="test_task", + res_id="test_result" +) +print(f"Execution result: {result}") + +# Teardown container +env.stop_container() +``` + +
+additional examples + +```python +# ds1000 +env = od.create_environment( + env_type="ds1000", + host_port=8080, + memory_limit="2g", + cpu_limit=1.0, + auto_start=True +) + +result = env.execute_code( + test=""" + def multiply(x, y): + return x * y + + assert multiply(3, 4) == 12 + """, + res_id="test_result" +) + +# multipl-e +env = od.create_environment( + env_type="multipl", + host_port=8080, + memory_limit="2g", + cpu_limit=1.0, + auto_start=True +) + +result = env.execute_code( + language="python", + completion="def multiply(x, y): return x * y", + test="assert multiply(3, 4) == 12", + res_id="test_result" +) +``` + +
+ +
+ +## Verify Docker + +Each container has a sample payload in `src/[benchmark]/sample_payloads/payload.json`. You can test that each sample payload passes with: + +```sh +python src/test_payloads.py +``` diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmes_docker-0.1.0.dist-info/RECORD b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmes_docker-0.1.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..38c828d8cd47ae552e9626459b573c5424c96161 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmes_docker-0.1.0.dist-info/RECORD @@ -0,0 +1,72 @@ +__pycache__/olmo_docker.cpython-310.pyc,, +bcb_execution/Dockerfile,sha256=QVeIlm0Q2dn48LtlfL_TPcz4kZMRl31Za5FyvtNZBAY,937 +bcb_execution/README.md,sha256=c0a9edwwe2BEudW-dE70OtQA91ftE6KXi38eU0ZyBaI,1911 +bcb_execution/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +bcb_execution/__pycache__/__init__.cpython-310.pyc,, +bcb_execution/__pycache__/app.cpython-310.pyc,, +bcb_execution/__pycache__/execution.cpython-310.pyc,, +bcb_execution/app.py,sha256=F_AeYokXtMsYppHD_B51dXi9UmmAC765hxjjC5BPHCo,2253 +bcb_execution/execution.py,sha256=FGiz_58zn6d8p7zsLdeiRBTQibwoSR2dYc_lTmH41M0,16187 +bcb_execution/sample_payloads/payload.json,sha256=2R3vo5kspi8aHs99bPAUYiPBUugVw0qEe6CyHWfZjTc,2647 +ds1000_execution/Dockerfile,sha256=seBeZhCkZ_1P-cY0LHT55rUIax2YEgLEAaLaMUPen2o,813 +ds1000_execution/README.md,sha256=kR8GCA9nfjiMDlT9eWngoqj6mwFNDrvdqwedIaX2-nc,1942 +ds1000_execution/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +ds1000_execution/__pycache__/__init__.cpython-310.pyc,, +ds1000_execution/__pycache__/app.cpython-310.pyc,, +ds1000_execution/__pycache__/execution.cpython-310.pyc,, +ds1000_execution/app.py,sha256=BQet4X2N4maN2hJEaAPMAS98A6qBw4xe7I8QcQRuOKk,1296 +ds1000_execution/execution.py,sha256=3rGklECUADQzXxF7XxQeMMCZIo26ikpDM8_xo6UFhpA,5767 +ds1000_execution/sample_payloads/payload.json,sha256=g2r1o7jvdDlrA7gKmD-GWy-OGtUbunmxSC0IFvsoATE,1668 +multiple_execution/Dockerfile,sha256=pLFF3aN9Q_XTUsoIE0VXUhNfxybuFm21aP2V98jUdSo,799 +multiple_execution/README.md,sha256=QcQEMDdRP6dmT0XkzOIfCrER5nADVRevoJlWxNXPfjA,1608 +multiple_execution/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +multiple_execution/__pycache__/__init__.cpython-310.pyc,, +multiple_execution/__pycache__/app.cpython-310.pyc,, +multiple_execution/__pycache__/eval.cpython-310.pyc,, +multiple_execution/__pycache__/eval_cpp.cpython-310.pyc,, +multiple_execution/__pycache__/eval_cs.cpython-310.pyc,, +multiple_execution/__pycache__/eval_go.cpython-310.pyc,, +multiple_execution/__pycache__/eval_java.cpython-310.pyc,, +multiple_execution/__pycache__/eval_javascript.cpython-310.pyc,, +multiple_execution/__pycache__/eval_php.cpython-310.pyc,, +multiple_execution/__pycache__/eval_python.cpython-310.pyc,, +multiple_execution/__pycache__/eval_ruby.cpython-310.pyc,, +multiple_execution/__pycache__/eval_rust.cpython-310.pyc,, +multiple_execution/__pycache__/eval_sh.cpython-310.pyc,, +multiple_execution/__pycache__/eval_swift.cpython-310.pyc,, +multiple_execution/__pycache__/eval_ts.cpython-310.pyc,, +multiple_execution/app.py,sha256=J84uoHTV-8lT5ZBcl0ReMRTXDq6g95Pa67gwlvl2DDA,1379 +multiple_execution/eval.py,sha256=lBHaTqEtJCHj-E6rZnQtpOVBwXIpOue0t7TaYeekcBk,3374 +multiple_execution/eval_cpp.py,sha256=m-1s1U1Rpv8vJDb-PRwum--KkfkpqHfKh70WPJVhsp8,1023 +multiple_execution/eval_cs.py,sha256=96tmXbu5OhGaekedU8TsbmmGf4dLGw0_3MsUsLYE848,1930 +multiple_execution/eval_go.py,sha256=1-TGeS-QMK6gM82Kf0qWh-YNpYXo9yWZiTfLct5PwpM,910 +multiple_execution/eval_java.py,sha256=aw8i52v_vZJJ0siAs9Xlt7KjfpNclLJHVjV97zNf4AA,1235 +multiple_execution/eval_javascript.py,sha256=npUiHVI2dWAzd4CO09l42snG5dDFonhnlmlaU01zDVo,1269 +multiple_execution/eval_php.py,sha256=GRz8G4Gpde3FdR9JO6BAqeoIpCKX4TTArLGiRfsluvw,408 +multiple_execution/eval_python.py,sha256=xvQK5VTEjvvMyy4R5ERCRimuiZZp9GiugqRlTpck71Y,460 +multiple_execution/eval_ruby.py,sha256=q1mzjIOKucCZfsL0Lp5a1t7yrP2ipeYdgs-JeTX-ZQE,1215 +multiple_execution/eval_rust.py,sha256=decFmdbqlnva9PGBz3LdlZ9sxZIZwvBbXxYe3253xzk,1511 +multiple_execution/eval_sh.py,sha256=hhooIhd_zoaQDw_0fYuo7LSCeYpilVCDuAeb4z_AH-c,540 +multiple_execution/eval_swift.py,sha256=dd43DZpkyER_2RnO12FHp191_sDU36POmwgdfFf7nMQ,845 +multiple_execution/eval_ts.py,sha256=A2Q3xxuz2-D-MXvo5-vuignjzHpCi5JPUYF8DgDA234,910 +multiple_execution/safe_subprocess/__init__.py,sha256=islMQmKiKASr376YTkvXLhaLqgTSWRCviWb_McWKFeU,2844 +multiple_execution/safe_subprocess/__pycache__/__init__.cpython-310.pyc,, +multiple_execution/sample_payloads/payload_cpp.json,sha256=qQvPEC2vbjQ4lWAX8nMv5M5oCChFF_4kxk59o2Qp_vE,1747 +multiple_execution/sample_payloads/payload_cs.json,sha256=vD-3PpJno7vgvkhSTS_VhQNSrASBR9cb0bzLAd8cQy4,2713 +multiple_execution/sample_payloads/payload_java.json,sha256=yLrysn0W2m5rrB2CI97roa_PT0UgFsqCyy21m-65nl4,812 +multiple_execution/sample_payloads/payload_js.json,sha256=WDN9gL2iIplzrTrbcz6HqAOYftIaYa0dR4mlR3SOXNs,1062 +multiple_execution/sample_payloads/payload_php.json,sha256=AV9WOVtOEqxcYjZHnxn_rC9q6vrwTT6pRpAimqd2Co8,1132 +multiple_execution/sample_payloads/payload_python.json,sha256=jnnKQgiRSH-KLzA7IjOVKQSkOoJ-V-GBH0UIMmoELEY,931 +multiple_execution/sample_payloads/payload_rb.json,sha256=2safPA8hOG9zM-f1vFIuodZ07SYCJFtDNvr8_OzzHR8,1109 +multiple_execution/sample_payloads/payload_rust.json,sha256=_W9pORCUrnop8kTiFI4alJkEZwB43qm3QY_FsRkRyek,301 +multiple_execution/sample_payloads/real_java_payload.json,sha256=3RzOv-EkdS4tjSn3OlzPPQBMFwLsvvWKViSI1GDep2s,1073 +multiple_execution/sample_payloads/real_rust_payload.json,sha256=bc1rZxoteNcoYFtDXocG9zEDSPhiat68r0VxnCDwJ4A,909 +multiple_execution/sample_payloads/v2_real_rust.json,sha256=G7ZZBxSier1FnAEfw49GhcUUZdewoB6cEIkiuxlEKsw,891 +olmes_docker-0.1.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +olmes_docker-0.1.0.dist-info/METADATA,sha256=Qr7jjeJb3WgwQbg1XJAbcfUneXDW25c50ir866zotAc,15543 +olmes_docker-0.1.0.dist-info/RECORD,, +olmes_docker-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91 +olmes_docker-0.1.0.dist-info/direct_url.json,sha256=NFik3eUuVhDkSMzSGWOhGpFm01IOOs-kFKL9TE8qJNM,169 +olmes_docker-0.1.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357 +olmes_docker-0.1.0.dist-info/top_level.txt,sha256=WTRFIxz7eLL6WHRTZrJJa2DLhxp_sbk7McAt2RdlzkQ,62 +olmo_docker.py,sha256=l43ueU0wdtTjgZ4r-Ej5jeAS6tCXkRwXZBwybPIsI1U,18865 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmes_docker-0.1.0.dist-info/WHEEL b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmes_docker-0.1.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..14a883f292bc96b20c2b76a3081991f2676523a9 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmes_docker-0.1.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (82.0.1) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmes_docker-0.1.0.dist-info/direct_url.json b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmes_docker-0.1.0.dist-info/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..5df79c8fbd70db87ac5fd637d423d5da454cf39d --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmes_docker-0.1.0.dist-info/direct_url.json @@ -0,0 +1 @@ +{"url": "https://github.com/allenai/olmes-docker.git", "vcs_info": {"commit_id": "d655f775c983cec17e9c0a98b07d2f95adbd9e2d", "requested_revision": "main", "vcs": "git"}} \ No newline at end of file diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmes_docker-0.1.0.dist-info/top_level.txt b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmes_docker-0.1.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..1849b74d91a44e235bfe44d104da2725fd42e49e --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmes_docker-0.1.0.dist-info/top_level.txt @@ -0,0 +1,4 @@ +bcb_execution +ds1000_execution +multiple_execution +olmo_docker diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo_core/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo_core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo_core/aliases.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo_core/aliases.py new file mode 100644 index 0000000000000000000000000000000000000000..302511156568e4ea4d47b30903cd65cbae9daed6 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo_core/aliases.py @@ -0,0 +1,5 @@ +from os import PathLike +from pathlib import Path +from typing import Union + +PathOrStr = Union[Path, PathLike, str] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo_core/config.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo_core/config.py new file mode 100644 index 0000000000000000000000000000000000000000..c13718e0507e9419192e5c3a52e0eed0e803c650 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo_core/config.py @@ -0,0 +1,341 @@ +import copy +import json +from dataclasses import dataclass, fields, is_dataclass, replace +from enum import Enum +from typing import ( + Any, + Callable, + ClassVar, + Dict, + Generator, + List, + Optional, + Tuple, + Type, + TypeVar, + cast, +) + +import torch +import yaml +from cached_path import cached_path +from omegaconf import OmegaConf as om +from omegaconf.errors import OmegaConfBaseException +from typing_extensions import Self + +from .aliases import PathOrStr +from .exceptions import OLMoConfigurationError + + +class StrEnum(str, Enum): + """ + This is equivalent to Python's :class:`enum.StrEnum` since version 3.11. + We include this here for compatibility with older version of Python. + """ + + def __str__(self) -> str: + return self.value + + def __repr__(self) -> str: + return f"'{str(self)}'" + + +C = TypeVar("C", bound="Config") + + +@dataclass +class Config: + """ + A base class for configuration dataclasses. + + .. important:: + When you subclass this you should still decorate your subclasses with + :func:`@dataclass `. For example:: + + @dataclass + class MyConfig(Config): + ... + + .. important:: + Config classes need to be serializable, so you should only use simple types for your fields. + Though you can use nested configs. + """ + + CLASS_NAME_FIELD = "_CLASS_" + """ + The name of the class name field inject into the dictionary from :meth:`as_dict()` or + :meth:`as_config_dict()`. + """ + + _IGNORE_FIELDS: ClassVar[Tuple[str, ...]] = () + """ + Fields to ignore when loading from config (for backwards compatibility). + """ + + def as_dict( + self, + *, + exclude_none: bool = False, + exclude_private_fields: bool = False, + include_class_name: bool = False, + json_safe: bool = False, + recurse: bool = True, + ) -> Dict[str, Any]: + """ + Convert into a regular Python dictionary. + + :param exclude_none: Don't include values that are ``None``. + :param exclude_private_fields: Don't include private fields. + :param include_class_name: Include a field for the name of the class. + :param json_safe: Output only JSON-safe types. + :param recurse: Recurse into fields that are also configs/dataclasses. + """ + + def iter_fields(d) -> Generator[Tuple[str, Any], None, None]: + for field in fields(d): + value = getattr(d, field.name) + if exclude_none and value is None: + continue + elif exclude_private_fields and field.name.startswith("_"): + continue + else: + yield (field.name, value) + + def as_dict(d: Any, recurse: bool = True) -> Any: + if is_dataclass(d): + if recurse: + out = {k: as_dict(v) for k, v in iter_fields(d)} + else: + out = {k: v for k, v in iter_fields(d)} + if include_class_name: + out[self.CLASS_NAME_FIELD] = f"{d.__class__.__module__}.{d.__class__.__name__}" + return out + elif isinstance(d, dict): + return {k: as_dict(v) for k, v in d.items()} + elif isinstance(d, (list, tuple, set)): + if json_safe: + return [as_dict(x) for x in d] + else: + return d.__class__((as_dict(x) for x in d)) + elif d is None or isinstance(d, (float, int, bool, str)): + return d + elif json_safe: + return str(d) + else: + return d + + return as_dict(self, recurse=recurse) + + def as_config_dict(self) -> Dict[str, Any]: + """ + A convenience wrapper around :meth:`as_dict()` for creating JSON-safe dictionaries suitable + for recording the config. + """ + return self.as_dict( + exclude_none=True, + exclude_private_fields=True, + include_class_name=True, + json_safe=True, + recurse=True, + ) + + def apply(self, func: Callable[["Config"], None]): + """ + Recursively apply a function to every config instance field, including ``self``. + + :param func: The function to apply. + """ + + def apply(d): + if isinstance(d, Config): + func(d) + + if is_dataclass(d): + for field in fields(d): + value = getattr(d, field.name) + apply(value) + elif isinstance(d, dict): + for value in d.values(): + apply(value) + elif isinstance(d, (list, tuple, set)): + for x in d: + apply(x) + + apply(self) + + def validate(self): + """ + Validate fields in ``self``. This may modify ``self`` in-place. + """ + pass + + def merge(self, dotlist: List[str], prefix: Optional[str] = None, strict: bool = True) -> Self: + """ + Merge self with fields from a "dotlist", creating a new object. + + :param dotlist: A list of field attributes with dot notation, e.g. ``foo.bar=1``. + :param prefix: Only use override items in the dotlist that start with a given prefix name, + and strip that prefix (including the subsequent ".") before applying the overrides. + :param strict: Parse the dotlist strictly. + """ + try: + dotlist = _clean_opts(dotlist) + if prefix is not None: + dotlist = [ + o.replace(f"{prefix}.", "", 1) for o in dotlist if o.startswith(f"{prefix}.") + ] + if not strict: + field_names = set(f.name for f in fields(self)) + dotlist = [ + o + for o in dotlist + if any( + [ + o.startswith(f"{name}=") or o.startswith(f"{name}.") + for name in field_names + ] + ) + ] + merge_fields = om.from_dotlist(dotlist) + merged = om.merge(self, merge_fields) + out = cast(Self, om.to_object(merged)) + out.apply(lambda c: c.validate()) + return out + except OmegaConfBaseException as e: + raise OLMoConfigurationError(str(e)) + + def replace(self, **changes) -> Self: + """ + Creates a new object of the same type, replacing fields with values from ``changes``. + """ + return replace(self, **changes) + + def copy(self, deep: bool = True) -> Self: + """ + Creates a new object of the same type, with the same values. + """ + return copy.deepcopy(self) if deep else copy.copy(self) + + @classmethod + def from_dict(cls: Type[C], data: Dict[str, Any], overrides: Optional[List[str]] = None) -> C: + """ + Initialize from a regular Python dictionary. + + :param data: A Python dictionary. + :param overrides: A list of field overrides with dot notation, e.g. ``foo.bar=1``. + """ + from importlib import import_module + + def resolve_cls(cls_name: str) -> Optional[Any]: + if "." in cls_name: + *modules, cls_name = cls_name.split(".") + module_name = ".".join(modules) + module = import_module(module_name) + return getattr(module, cls_name) + else: + return None + + def clean_data(d: Any, prefix: str) -> Any: + if isinstance(d, dict): + # HACK: Try to convert string keys to int if they look like integers. Handles cases + # where integer keys were serialized as strings (eg "block_overrides") + d = {(int(k) if isinstance(k, str) and k.isdigit() else k): v for k, v in d.items()} + + new_dict = { + k: clean_data(v, f"{prefix}.{k}" if prefix else k) + for k, v in d.items() + if k != cls.CLASS_NAME_FIELD + } + if (cls_name := d.get(cls.CLASS_NAME_FIELD)) is not None and ( + cls_o := resolve_cls(cls_name) + ) is not None: + # Remove ignored fields if the class defines any + if cls_o._IGNORE_FIELDS: + new_dict = { + k: v for k, v in new_dict.items() if k not in cls_o._IGNORE_FIELDS + } + schema = om.structured(cls_o) + try: + return om.to_object(om.merge(schema, new_dict)) + except OmegaConfBaseException as e: + if prefix: + msg = f"Failed to construct '{prefix}' in config" + else: + msg = "Error building config" + raise OLMoConfigurationError(msg) from e + return new_dict + elif isinstance(d, (list, tuple, set)): + return d.__class__( + (clean_data(x, f"{prefix}.{i}" if prefix else str(i)) for i, x in enumerate(d)) + ) + else: + return d + + data = clean_data(data, "") + + try: + schema = om.structured(cls) + conf = om.merge(schema, data) + if overrides: + conf = om.merge(conf, om.from_dotlist(_clean_opts(overrides))) + return cast(C, om.to_object(conf)) + except OmegaConfBaseException as e: + raise OLMoConfigurationError(str(e)) + + @classmethod + def from_file(cls: Type[C], path: PathOrStr, overrides: Optional[List[str]] = None) -> C: + path_str = str(path) + if path_str.endswith((".yml", ".yaml")): + return cls.from_yaml(path, overrides=overrides) + elif path_str.endswith(".json"): + return cls.from_json(path, overrides=overrides) + else: + raise OLMoConfigurationError(f"Unsupported config file type: {path}") + + @classmethod + def from_json(cls: Type[C], path: PathOrStr, overrides: Optional[List[str]] = None) -> C: + with cached_path(path).open() as f: + config_dict = json.load(f) + return cls.from_dict(config_dict, overrides=overrides) + + @classmethod + def from_yaml(cls: Type[C], path: PathOrStr, overrides: Optional[List[str]] = None) -> C: + with cached_path(path).open() as f: + config_dict = yaml.safe_load(f) + return cls.from_dict(config_dict, overrides=overrides) + + +def _clean_opts(opts: List[str]) -> List[str]: + return [_clean_opt(s) for s in opts] + + +def _clean_opt(arg: str) -> str: + if "=" not in arg: + arg = f"{arg}=True" + name, val = arg.split("=", 1) + name = name.strip("-").replace("-", "_") + return f"{name}={val}" + + +class DType(StrEnum): + """ + An enumeration of supported PyTorch data types. + """ + + float32 = "float32" + bfloat16 = "bfloat16" + float16 = "float16" + + @classmethod + def from_pt(cls, dtype: torch.dtype) -> "DType": + if dtype == torch.float32: + return DType.float32 + elif dtype == torch.bfloat16: + return DType.bfloat16 + elif dtype == torch.float16: + return DType.float16 + else: + raise NotImplementedError(dtype) + + def as_pt(self) -> torch.dtype: + return getattr(torch, self) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo_core/doc_utils.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo_core/doc_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..00bc4551e7c8c901ba9b5d1b1b82ecbc706ea3a3 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo_core/doc_utils.py @@ -0,0 +1,22 @@ +from typing import TypeVar + +T = TypeVar("T") + + +def beta_feature(f: T) -> T: + """ + Mark a class or function as a beta feature. + """ + if f.__doc__ is None: + f.__doc__ = "" + + f.__doc__ += """ + + .. warning:: + This is a beta feature! The API is subject to change even with minor and patch releases. + If you choose to use this feature please read the `CHANGELOG `_ + before upgrading your version of this library. + + """ + + return f diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo_core/exceptions.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo_core/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..029f03774695ef36923d4db150dac42f48378571 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo_core/exceptions.py @@ -0,0 +1,48 @@ +class OLMoError(Exception): + """ + Base exception for OLMo custom error types. + """ + + +class OLMoInvalidRangeRequestError(OLMoError): + pass + + +class OLMoNetworkError(OLMoError): + pass + + +class OLMoEnvironmentError(OLMoError): + pass + + +class OLMoUserError(OLMoError): + pass + + +class OLMoCheckpointError(OLMoError): + pass + + +class OLMoConfigurationError(OLMoError): + pass + + +class OLMoCLIError(OLMoError): + pass + + +class OLMoThreadError(OLMoError): + pass + + +class BeakerExperimentFailedError(OLMoError): + pass + + +class BeakerInsufficientResourcesError(OLMoError): + pass + + +class OLMoUploadError(OLMoError): + pass diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo_core/io.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo_core/io.py new file mode 100644 index 0000000000000000000000000000000000000000..618cc12e508fa299431c2ee20c5843fdefc0a98b --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo_core/io.py @@ -0,0 +1,1094 @@ +import io +import logging +import os +import pickle +import re +import shutil +import time +from collections import deque +from concurrent.futures import ThreadPoolExecutor, as_completed +from functools import wraps +from pathlib import Path +from typing import Any, Callable, Generator, Optional, Tuple, Type, Union + +try: + from functools import cache +except ImportError: + from functools import lru_cache as cache + +import requests +import torch +from cached_path import cached_path +from cached_path.schemes import S3Client, SchemeClient, add_scheme_client +from requests.adapters import HTTPAdapter +from rich.progress import track + +from .aliases import PathOrStr +from .exceptions import ( + OLMoEnvironmentError, + OLMoInvalidRangeRequestError, + OLMoNetworkError, + OLMoUploadError, +) + +log = logging.getLogger(__name__) + +############################################ +## Unified API for local and remote files ## +############################################ + + +def normalize_path(path: PathOrStr) -> str: + """ + Normalize a path/URL. + + :param path: The path/URL to normalize. + """ + return str(path).rstrip("/").replace("file://", "") + + +def join_path(path1: PathOrStr, path2: PathOrStr) -> PathOrStr: + """ + Join two paths. + + :param path1: The first path. + :param path2: The second path. + + :returns: The joined result. + """ + if is_url(path1): + return f"{normalize_path(path1)}/{normalize_path(path2)}" + else: + return Path(path1) / path2 + + +def resource_path(folder: PathOrStr, fname: str, local_cache: Optional[PathOrStr] = None) -> Path: + """ + Returns an actual path for local or remote file, potentially downloading it if a copy doesn't + exist locally yet. + """ + folder = normalize_path(folder) + if local_cache is not None and (local_path := Path(local_cache) / fname).is_file(): + log.info(f"Found local cache of {fname} at {local_path}") + return local_path + else: + return cached_path(f"{folder}/{fname}", quiet=True) + + +def is_url(path: PathOrStr) -> bool: + """ + Check if a path is a URL. + + :param path: Path-like object to check. + """ + path = normalize_path(path) + return re.match(r"[a-z0-9]+://.*", str(path)) is not None + + +def get_file_size(path: PathOrStr) -> int: + """ + Get the size of a local or remote file in bytes. + + :param path: Path/URL to the file. + """ + path = normalize_path(path) + + if is_url(path): + from urllib.parse import urlparse + + parsed = urlparse(str(path)) + if parsed.scheme == "gs": + return _gcs_file_size(parsed.netloc, parsed.path.strip("/")) + elif parsed.scheme in ("s3", "r2", "weka"): + return _s3_file_size(parsed.scheme, parsed.netloc, parsed.path.strip("/")) + elif parsed.scheme in ("http", "https"): + return _http_file_size(str(path)) + elif parsed.scheme == "file": + return get_file_size(str(path).replace("file://", "", 1)) + else: + raise NotImplementedError(f"file size not implemented for '{parsed.scheme}' files") + else: + return os.stat(path).st_size + + +def get_bytes_range(path: PathOrStr, bytes_start: int, num_bytes: int) -> bytes: + """ + Get a range of bytes from a local or remote file. + + :param source: Path/URL to the file. + :param bytes_start: Byte offset to start at. + :param num_bytes: Number of bytes to get. + """ + path = normalize_path(path) + + if is_url(path): + from urllib.parse import urlparse + + parsed = urlparse(str(path)) + if parsed.scheme == "gs": + return _gcs_get_bytes_range( + parsed.netloc, parsed.path.strip("/"), bytes_start, num_bytes + ) + elif parsed.scheme in ("s3", "r2", "weka"): + return _s3_get_bytes_range( + parsed.scheme, parsed.netloc, parsed.path.strip("/"), bytes_start, num_bytes + ) + elif parsed.scheme in ("http", "https"): + return _http_get_bytes_range(str(path), bytes_start, num_bytes) + elif parsed.scheme == "file": + return get_bytes_range(str(path).replace("file://", "", 1), bytes_start, num_bytes) + else: + raise NotImplementedError(f"file size not implemented for '{parsed.scheme}' files") + else: + with open(path, "rb") as f: + f.seek(bytes_start) + return f.read(num_bytes) + + +def upload(source: PathOrStr, target: str, save_overwrite: bool = False, quiet: bool = False): + """ + Upload source file to a target location on GCS or S3. + + :param source: Path to the file to upload. + :param target: Target URL to upload to. + :param save_overwrite: Overwrite any existing file. + """ + from urllib.parse import urlparse + + source = Path(normalize_path(source)) + assert source.is_file() + num_bytes = get_file_size(source) + if not quiet: + log.info(f"Uploading {_format_bytes(num_bytes)} from '{source}' to '{target}'...") + parsed = urlparse(target) + + if parsed.scheme == "gs": + _gcs_upload(source, parsed.netloc, parsed.path.strip("/"), save_overwrite=save_overwrite) + elif parsed.scheme in ("s3", "r2", "weka"): + _s3_upload( + source, + parsed.scheme, + parsed.netloc, + parsed.path.strip("/"), + save_overwrite=save_overwrite, + ) + else: + raise NotImplementedError(f"Upload not implemented for '{parsed.scheme}' scheme") + + if not quiet: + log.info(f"Uploaded {_format_bytes(num_bytes)} to '{target}'") + + +def copy_file( + source: PathOrStr, target: PathOrStr, save_overwrite: bool = False, quiet: bool = False +): + """ + Copy a file from ``source`` to ``target``. + + :param source: The path/URL to the source file. + :param target: The path/URL to the target location. + :param save_overwrite: Overwrite any existing file. + + :raises FileNotFoundError: If the ``source`` file doesn't exist. + :raises FileExistsError: If the ``target`` already exists and ``save_overwrite=False``. + """ + source = normalize_path(source) + target = normalize_path(target) + local_source = cached_path(source, quiet=True) + if is_url(target): + upload(local_source, target, save_overwrite=save_overwrite, quiet=quiet) + else: + target = Path(target) + if file_exists(target): + if not save_overwrite: + raise FileExistsError(target) + else: + target.unlink(missing_ok=True) + else: + target.parent.mkdir(exist_ok=True, parents=True) + try: + os.link(local_source, target, follow_symlinks=True) + except OSError: + # Can't hard link across devices, so copy instead. + shutil.copyfile(local_source, target, follow_symlinks=True) + + +def copy_dir( + source: PathOrStr, + target: PathOrStr, + save_overwrite: bool = False, + num_threads: Optional[int] = None, + quiet: bool = False, +): + """ + Copy a directory from ``source`` to ``target``. + + :param source: The path/URL to the source directory. + :param target: The path/URL to the target location. + :param save_overwrite: Overwrite any existing files. + :param num_threads: The number of threads to use. + + :raises FileNotFoundError: If the ``source`` dir doesn't exist. + :raises FileExistsError: If any source files already exist in the ``target`` and ``save_overwrite=False``. + """ + source = normalize_path(source) + target = normalize_path(target) + + if num_threads is None: + from .utils import get_default_thread_count + + num_threads = get_default_thread_count() + + with ThreadPoolExecutor(max_workers=num_threads) as executor: + if not quiet: + log.info(f"Collecting source files from '{source}' to copy to '{target}'...") + + futures = [] + for source_path in list_directory(source, recurse=True, include_dirs=False): + assert source_path.startswith(source) + relative_source_path = source_path.replace(source, "", 1).lstrip("/") + target_path = join_path(target, relative_source_path) + futures.append( + executor.submit( + copy_file, source_path, target_path, save_overwrite=save_overwrite, quiet=True + ) + ) + + if not quiet: + log.info(f"Collected {len(futures)} source files to copy") + + deque( + track( + (f.result() for f in as_completed(futures)), + description="Copying source files...", + disable=quiet, + total=len(futures), + ), + maxlen=0, + ) + + +def dir_is_empty(dir: PathOrStr) -> bool: + """ + Check if a local or remote directory is empty. + This also returns true if the directory does not exist. + + :param dir: Path/URL to the directory. + """ + try: + next(list_directory(dir)) + return False + except (StopIteration, FileNotFoundError): + return True + + +def file_exists(path: PathOrStr) -> bool: + """ + Check if a local or remote file exists. + + :param path: Path/URL to a file. + """ + path = normalize_path(path) + + if is_url(path): + from urllib.parse import urlparse + + parsed = urlparse(str(path)) + if parsed.scheme == "gs": + try: + _gcs_file_size(parsed.netloc, parsed.path.strip("/")) + except FileNotFoundError: + return False + else: + return True + elif parsed.scheme in ("s3", "r2", "weka"): + try: + _s3_file_size(parsed.scheme, parsed.netloc, parsed.path.strip("/")) + except FileNotFoundError: + return False + else: + return True + elif parsed.scheme in ("http", "https"): + return _http_file_exists(str(path)) + else: + raise NotImplementedError(f"file_exists not implemented for '{parsed.scheme}' files") + else: + return Path(path).exists() + + +def remove_file(path: PathOrStr): + """ + Remove a local or remote file. + + :param path: The path or URL to the file. + + :raises FileNotFoundError: If the file doesn't exist. + """ + path = normalize_path(path) + + if is_url(path): + from urllib.parse import urlparse + + parsed = urlparse(str(path)) + if parsed.scheme == "gs": + return _gcs_remove_file(parsed.netloc, parsed.path.strip("/")) + elif parsed.scheme in ("s3", "r2", "weka"): + return _s3_remove_file(parsed.scheme, parsed.netloc, parsed.path.strip("/")) + else: + raise NotImplementedError(f"remove_file not implemented for '{parsed.scheme}' files") + else: + Path(path).unlink() + + +def clear_directory(dir: PathOrStr, force: bool = False): + """ + Clear out the contents of a local or remote directory. + + .. warning:: + This function is potentially very destructive! + + By default, for safety, this raise a :class:`ValueError` if you attempt to clear a remote + directory too close to the root of the bucket. Set ``force=True`` to override. + + :param dir: Path/URL to the directory. + :param force: See note about safety. + """ + dir = normalize_path(dir) + + if is_url(dir): + from urllib.parse import urlparse + + parsed = urlparse(str(dir)) + if parsed.scheme in ("s3", "r2", "weka", "gs"): + prefix = parsed.path.strip("/") + # For safety (so people don't accidentally delete a whole bunch of important data), + # ensure prefix is at least 2 folders deep. + if not force and prefix.count("/") < 2: + raise ValueError( + "For safety, clearing a remote directory this close to the root of a bucket is " + "not allowed by default. To override this behavior set ``force=True``." + ) + + if parsed.scheme == "gs": + prefix = parsed.path.strip("/") + return _gcs_clear_directory(parsed.netloc, prefix) + elif parsed.scheme in ("s3", "r2", "weka"): + prefix = parsed.path.strip("/") + return _s3_clear_directory(parsed.scheme, parsed.netloc, prefix) + else: + raise NotImplementedError( + f"clear_directory not implemented for '{parsed.scheme}' folders" + ) + elif Path(dir).is_dir(): + shutil.rmtree(dir, ignore_errors=True) + + +def list_directory( + dir: PathOrStr, recurse: bool = False, include_files: bool = True, include_dirs: bool = True +) -> Generator[str, None, None]: + """ + List the contents of a local or remote directory. + If ``recurse=False``, only the immediate children of the directory are returned, otherwise + every sub-folder is recursed into. + + :param dir: Path/URL to the directory. + :param recurse: Whether to recurse into sub-folders. + :param include_files: Include regular files in the results. + :param include_dirs: Include directories in the results. + + :returns: A generator over paths in the directory. If the ``dir`` is a URL, the results will be + full URLs. If the ``dir`` is a local path, the results will be of the form ``join_path(dir, p)``. + + :raises FileNotFoundError: If the ``source`` file doesn't exist. + """ + dir = normalize_path(dir) + + if not is_url(dir): + for p in Path(dir).iterdir(): + if (p.is_file() and include_files) or (p.is_dir() and include_dirs): + yield str(p) + if recurse and p.is_dir(): + yield from list_directory( + p, recurse=True, include_files=include_files, include_dirs=include_dirs + ) + else: + from urllib.parse import urlparse + + parsed = urlparse(dir) + if parsed.scheme == "gs": + yield from _gcs_list_directory( + parsed.netloc, + parsed.path.strip("/"), + recurse=recurse, + include_files=include_files, + include_dirs=include_dirs, + ) + elif parsed.scheme in ("s3", "r2", "weka"): + yield from _s3_list_directory( + parsed.scheme, + parsed.netloc, + parsed.path.strip("/"), + recurse=recurse, + include_files=include_files, + include_dirs=include_dirs, + ) + else: + raise NotImplementedError( + f"list_directory size not implemented for '{parsed.scheme}' URLs" + ) + + +def glob_directory(pattern: str) -> Generator[str, None, None]: + """ + Similar to ``glob.glob()`` from the standard library, but works with remote directories as well. + + .. warning:: + Only a subset of glob patterns are supported. Specifically, ``*`` and ``**`` wildcards, + which the follow the semantics defined here https://docs.python.org/3/library/pathlib.html#pattern-language. + """ + # Pull out base directory from pattern by finding the first part before any wildcard. + # Split by '/' and take path components until we hit one with a wildcard. + parts = pattern.split("/") + base_parts = [] + for part in parts: + if "*" in part: + break + base_parts.append(part) + dir = "/".join(base_parts) if base_parts else "." + + # Translate the glob pattern into a regex. + # For example, "src/examples/**/*.py" --> "^src/examples/.*[^/]*\\.py$". + pattern_regex = re.compile( + "^" + + re.escape(pattern).replace(r"\*\*/", ".*").replace(r"\*\*", ".*").replace(r"\*", "[^/]*") + + "$" + ) + + for path in list_directory(dir, recurse="**" in pattern): + if pattern_regex.match(path): + yield path + + +def init_client(remote_path: str): + """ + Initialize the right client for the given remote resource. This is helpful to avoid threading issues + with boto3. + """ + if remote_path.startswith("s3://"): + _get_s3_client("s3") + elif remote_path.startswith("r2://"): + _get_s3_client("r2") + elif remote_path.startswith("weka://"): + _get_s3_client("weka") + + +################################### +## Serialization/deserialization ## +################################### + + +def serialize_to_tensor(x: Any) -> torch.Tensor: + """ + Serialize an object to a byte tensor using pickle. + + :param x: The pickeable object to serialize. + """ + serialized_bytes = pickle.dumps(x) + return torch.frombuffer(bytearray(serialized_bytes), dtype=torch.uint8) + + +def deserialize_from_tensor(data: torch.Tensor) -> Any: + """ + Deserialize an object from a byte tensor using pickle. + + :param data: The byte tensor to deserialize. + """ + assert data.dtype == torch.uint8 + return pickle.loads(bytearray([int(x.item()) for x in data.flatten()])) + + +###################### +## Internal helpers ## +###################### + + +def _wait_before_retry(attempt: int): + time.sleep(min(0.5 * 2**attempt, 3.0)) + + +def _format_bytes(num: Union[int, float], suffix="B") -> str: + for unit in ("", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"): + if abs(num) < 1024.0: + return f"{num:3.1f}{unit}{suffix}" + num /= 1024.0 + return f"{num:.1f}Yi{suffix}" + + +def retriable( + max_attempts: int = 3, + retriable_errors: Tuple[Type[Exception], ...] = ( + requests.exceptions.ConnectionError, + requests.exceptions.Timeout, + requests.exceptions.ChunkedEncodingError, + ), + retry_condition: Optional[Callable[[Exception], bool]] = None, +): + def decorator(func): + @wraps(func) + def new_func(*args, **kwargs): + for attempt in range(1, max_attempts + 1): + try: + return func(*args, **kwargs) + except Exception as exc: + if isinstance(exc, retriable_errors) or ( + retry_condition is not None and retry_condition(exc) + ): + if attempt >= max_attempts: + # When torch's DataLoader intercepts exceptions, it may try to re-raise them + # by recalling their constructor with a single message arg. Torch has some + # logic to deal with the absence of a single-parameter constructor, but it + # doesn't gracefully handle other possible failures in calling such a constructor + # This can cause an irrelevant exception (e.g. KeyError: 'error'), resulting + # in us losing the true exception info. To avoid this, we change the exception + # to a type that has a single-parameter constructor. + raise OLMoNetworkError( + f"'{func.__name__}' failed {max_attempts} attempts with: {exc}" + ) from exc + else: + log.warning( + f"'{func.__name__}' failed attempt {attempt} with retriable error: {exc}" + ) + _wait_before_retry(attempt) + else: + raise + + return new_func + + return decorator + + +###################### +## HTTPS IO helpers ## +###################### + + +@cache +def _get_http_session() -> requests.Session: + """ + Get a shared HTTP session with connection pooling. + This prevents resource exhaustion when making many HTTP requests. + """ + session = requests.Session() + # Configure connection pooling to reuse connections + adapter = HTTPAdapter(pool_maxsize=50) + session.mount("http://", adapter) + session.mount("https://", adapter) + return session + + +@retriable() +def _http_file_size(url: str) -> int: + session = _get_http_session() + response = session.head(url, allow_redirects=True) + content_length = response.headers.get("content-length") + if content_length is None: + raise OLMoNetworkError( + f"No content-length header found for {url}. " + f"This can happen when the server is rate-limiting requests or when DDoS protection flags this request. " + f"Headers: {dict(response.headers)}" + ) + return int(content_length) + + +@retriable( + retry_condition=lambda exc: ( + isinstance(exc, requests.exceptions.HTTPError) + and exc.response is not None + and exc.response.status_code == 502 + ), +) +def _http_get_bytes_range(url: str, bytes_start: int, num_bytes: int) -> bytes: + session = _get_http_session() + response = session.get( + url, headers={"Range": f"bytes={bytes_start}-{bytes_start + num_bytes - 1}"} + ) + + if response.status_code == 404: + raise FileNotFoundError(url) + + response.raise_for_status() + + result = response.content + # Some web servers silently ignore range requests and send everything + assert len(result) == num_bytes, f"expected {num_bytes} bytes, got {len(result)}" + + return result + + +@retriable() +def _http_file_exists(url: str) -> bool: + session = _get_http_session() + response = session.head(url) + if response.status_code == 404: + return False + + response.raise_for_status() + return True + + +#################### +## GCS IO helpers ## +#################### + + +@cache +def _get_gcs_client(): + from google.cloud import storage as gcs + + return gcs.Client() + + +def _gcs_is_retriable(exc: Exception) -> bool: + from google.api_core.exceptions import BadRequest, GatewayTimeout + from google.api_core.retry import if_transient_error + from google.auth.exceptions import RefreshError + + return if_transient_error(exc) or isinstance( + exc, + ( + requests.exceptions.Timeout, + BadRequest, # Weird choice, but Google throws this transiently + GatewayTimeout, + RefreshError, + ), + ) + + +def _get_gcs_retry(): + from google.api_core.retry import Retry + + return Retry( + predicate=_gcs_is_retriable, # NOTE: it appears google might ignore this + initial=1.0, + maximum=10.0, + multiplier=2.0, + timeout=600.0, + ) + + +@retriable(retry_condition=_gcs_is_retriable) +def _gcs_file_size(bucket_name: str, key: str) -> int: + from google.api_core.exceptions import NotFound + + storage_client = _get_gcs_client() + bucket = storage_client.bucket(bucket_name) + blob = bucket.blob(key) + try: + blob.reload(retry=_get_gcs_retry()) + except NotFound: + raise FileNotFoundError(f"gs://{bucket_name}/{key}") + assert blob.size is not None + return blob.size + + +@retriable(retry_condition=_gcs_is_retriable) +def _gcs_remove_file(bucket_name: str, key: str): + from google.api_core.exceptions import NotFound + + storage_client = _get_gcs_client() + bucket = storage_client.bucket(bucket_name) + blob = bucket.blob(key) + try: + blob.reload(retry=_get_gcs_retry()) + bucket.delete_blob(blob.name) + except NotFound: + raise FileNotFoundError(f"gs://{bucket_name}/{key}") + + +@retriable(retry_condition=_gcs_is_retriable) +def _gcs_get_bytes_range(bucket_name: str, key: str, bytes_start: int, num_bytes: int) -> bytes: + from google.api_core.exceptions import NotFound + + storage_client = _get_gcs_client() + bucket = storage_client.bucket(bucket_name) + blob = bucket.blob(key) + try: + blob.reload(retry=_get_gcs_retry()) + except NotFound: + raise FileNotFoundError(f"gs://{bucket_name}/{key}") + return blob.download_as_bytes( + start=bytes_start, + end=bytes_start + num_bytes - 1, + retry=_get_gcs_retry(), + checksum=None, # type: ignore + ) + + +@retriable(retry_condition=_gcs_is_retriable) +def _gcs_upload(source: Path, bucket_name: str, key: str, save_overwrite: bool = False): + storage_client = _get_gcs_client() + bucket = storage_client.bucket(bucket_name) + blob = bucket.blob(key) + + if blob.exists(retry=_get_gcs_retry()) and not save_overwrite: + raise FileExistsError( + f"gs://{bucket_name}/{key} already exists. Use save_overwrite to overwrite it." + ) + + try: + blob.upload_from_filename( + source, + # NOTE: mypy and language servers may complain about the type here, but it does + # not in fact need to be a ConditionalRetry, a plain old Retry is fine. + retry=_get_gcs_retry(), # type: ignore + ) + except Exception as e: + raise OLMoUploadError( + f"Failed to upload '{source}' to '{key}' in GCS bucket '{bucket_name}'" + ) from e + + +@retriable(retry_condition=_gcs_is_retriable) +def _gcs_clear_directory(bucket_name: str, prefix: str): + from google.api_core.exceptions import NotFound + + storage_client = _get_gcs_client() + + prefix = prefix.strip("/") + if prefix: + prefix += "/" + + try: + bucket = storage_client.bucket(bucket_name) + blobs = bucket.list_blobs(prefix=prefix, retry=_get_gcs_retry()) + for blob in blobs: + bucket.delete_blob(blob.name) + except NotFound: + return + + +def _gcs_list_directory( + bucket_name: str, + prefix: str, + recurse: bool = False, + include_files: bool = True, + include_dirs: bool = True, +) -> Generator[str, None, None]: + from google.api_core.exceptions import NotFound + + storage_client = _get_gcs_client() + + prefix = prefix.strip("/") + if prefix: + prefix += "/" + + for match_glob in ( + prefix + "*", # only immediate files + prefix + "**/", # only immediate sub-folders + ): + try: + bucket = storage_client.bucket(bucket_name) + blobs = bucket.list_blobs( + prefix=prefix, + delimiter="/", + match_glob=match_glob, + retry=_get_gcs_retry(), + ) + except NotFound: + raise FileNotFoundError(f"gs://{bucket_name}/{prefix}") + + # NOTE: need to iterate over these blobs even if not yielding files, otherwise 'blobs.prefixes' + # won't be populated. + for blob in blobs: + if include_files: + yield f"gs://{bucket_name}/{blob.name}" + + for folder in blobs.prefixes: + if include_dirs: + yield f"gs://{bucket_name}/{folder.strip('/')}" + if recurse: + yield from _gcs_list_directory( + bucket_name, + folder, + recurse=True, + include_files=include_files, + include_dirs=include_dirs, + ) + + +################### +## S3 IO helpers ## +################### + + +@cache +def _get_s3_client(scheme: str): + import boto3 + from botocore import UNSIGNED + from botocore.config import Config + + session = boto3.Session(profile_name=_get_s3_profile_name(scheme)) + + credentials = session.get_credentials() + config = Config(retries={"max_attempts": 10, "mode": "standard"}) + if credentials is None: + config = config.merge(Config(signature_version=UNSIGNED)) + + return session.client( + "s3", + endpoint_url=_get_s3_endpoint_url(scheme), + config=config, + use_ssl=not int(os.environ.get("OLMO_NO_SSL", "0")), + ) + + +def _get_s3_profile_name(scheme: str) -> Optional[str]: + if scheme == "s3": + # For backwards compatibility, we assume S3 uses the default profile if S3_PROFILE is not set. + return os.environ.get("S3_PROFILE") + if scheme == "r2": + profile_name = os.environ.get("R2_PROFILE") + if profile_name is None: + raise OLMoEnvironmentError( + "R2 profile name is not set. Did you forget to set the 'R2_PROFILE' env var?" + ) + + return profile_name + if scheme == "weka": + profile_name = os.environ.get("WEKA_PROFILE") + if profile_name is None: + raise OLMoEnvironmentError( + "WEKA profile name is not set. Did you forget to set the 'WEKA_PROFILE' env var?" + ) + + return profile_name + + raise NotImplementedError(f"Cannot get profile name for scheme {scheme}") + + +def _get_s3_endpoint_url(scheme: str) -> Optional[str]: + if scheme == "s3": + return None + if scheme == "r2": + r2_endpoint_url = os.environ.get("R2_ENDPOINT_URL") + if r2_endpoint_url is None: + raise OLMoEnvironmentError( + "R2 endpoint url is not set. Did you forget to set the 'R2_ENDPOINT_URL' env var?" + ) + + return r2_endpoint_url + if scheme == "weka": + weka_endpoint_url = os.environ.get("WEKA_ENDPOINT_URL") + if weka_endpoint_url is None: + raise OLMoEnvironmentError( + "WEKA endpoint url is not set. Did you forget to set the 'WEKA_ENDPOINT_URL' env var?" + ) + + return weka_endpoint_url + + raise NotImplementedError(f"Cannot get endpoint url for scheme {scheme}") + + +def _s3_retry_condition(err: Exception) -> bool: + import botocore.exceptions as boto_errors + + return isinstance( + err, (boto_errors.ClientError, boto_errors.HTTPClientError, boto_errors.ConnectionError) + ) + + +@retriable(retry_condition=_s3_retry_condition) +def _s3_file_size(scheme: str, bucket_name: str, key: str) -> int: + from botocore.exceptions import ClientError + + try: + return _get_s3_client(scheme).head_object(Bucket=bucket_name, Key=key)["ContentLength"] + except ClientError as e: + if e.response["ResponseMetadata"]["HTTPStatusCode"] == 404: + raise FileNotFoundError(f"{scheme}://{bucket_name}/{key}") from e + else: + raise + + +@retriable(retry_condition=_s3_retry_condition) +def _s3_remove_file(scheme: str, bucket_name: str, key: str): + from botocore.exceptions import ClientError + + try: + return _get_s3_client(scheme).delete_object(Bucket=bucket_name, Key=key) + except ClientError as e: + if e.response["ResponseMetadata"]["HTTPStatusCode"] == 404: + raise FileNotFoundError(f"{scheme}://{bucket_name}/{key}") from e + else: + raise + + +@retriable(retry_condition=_s3_retry_condition) +def _s3_get_bytes_range( + scheme: str, bucket_name: str, key: str, bytes_start: int, num_bytes: int +) -> bytes: + from botocore.exceptions import ClientError + + try: + return ( + _get_s3_client(scheme) + .get_object( + Bucket=bucket_name, + Key=key, + Range=f"bytes={bytes_start}-{bytes_start + num_bytes - 1}", + )["Body"] + .read() + ) + except ClientError as e: + if e.response["ResponseMetadata"]["HTTPStatusCode"] == 404: + raise FileNotFoundError(f"{scheme}://{bucket_name}/{key}") from e + elif e.response["Error"]["Code"] == "InvalidRange": + raise OLMoInvalidRangeRequestError( + f"Invalid range request to '{scheme}://{bucket_name}/{key}' ({bytes_start=}, {num_bytes=})" + ) + else: + raise + + +@retriable(retry_condition=_s3_retry_condition) +def _s3_upload( + source: Path, + scheme: str, + bucket_name: str, + key: str, + save_overwrite: bool = False, +): + from botocore.exceptions import ClientError + + if not save_overwrite: + try: + _get_s3_client(scheme).head_object(Bucket=bucket_name, Key=key) + raise FileExistsError( + f"s3://{bucket_name}/{key} already exists. Use save_overwrite to overwrite it." + ) + except ClientError as e: + if e.response["ResponseMetadata"]["HTTPStatusCode"] == 404: + pass + else: + raise + + _get_s3_client(scheme).upload_file(source, bucket_name, key) + + +@retriable(retry_condition=_s3_retry_condition) +def _s3_clear_directory(scheme: str, bucket_name: str, prefix: str): + from botocore.exceptions import ClientError + + if not prefix.endswith("/"): + prefix = prefix + "/" + + try: + for o in _get_s3_client(scheme).list_objects_v2(Bucket=bucket_name, Prefix=prefix)[ + "Contents" + ]: + _get_s3_client(scheme).delete_object(Bucket=bucket_name, Key=o["Key"]) + return + except ClientError as e: + if e.response["ResponseMetadata"]["HTTPStatusCode"] == 404: + return + except KeyError: + return + + +def _s3_list_directory( + scheme: str, + bucket_name: str, + prefix: str, + recurse: bool = False, + include_files: bool = True, + include_dirs: bool = True, +) -> Generator[str, None, None]: + client = _get_s3_client(scheme) + paginator = client.get_paginator("list_objects_v2") + if not prefix.endswith("/"): + prefix = prefix + "/" + for page in paginator.paginate(Bucket=bucket_name, Prefix=prefix, MaxKeys=50, Delimiter="/"): + if include_files: + for file_item in page.get("Contents", []): + yield f"{scheme}://{bucket_name}/{file_item['Key']}" + for dir_item in page.get("CommonPrefixes", []): + if include_dirs: + yield f"{scheme}://{bucket_name}/{dir_item['Prefix'].strip('/')}" + if recurse: + yield from _s3_list_directory( + scheme, + bucket_name, + dir_item["Prefix"], + recurse=True, + include_files=include_files, + include_dirs=include_dirs, + ) + + +############################################# +## Custom cached path client for 'weka://' ## +############################################# + + +def add_cached_path_clients(): + """ + Add additional cached-path clients. + """ + add_scheme_client(_WekaClient) + + +class _WekaClient(SchemeClient): + recoverable_errors = S3Client.recoverable_errors + + scheme = "weka" + + def __init__(self, resource: str) -> None: + super().__init__(resource) + self.bucket_name, self.path = _WekaClient._split_cloud_path(resource, "weka") + self.s3 = _get_s3_client("weka") + self.object_info = None + + @staticmethod + def _split_cloud_path(url: str, provider: str) -> Tuple[str, str]: + """Split a full s3 path into the bucket name and path.""" + from urllib.parse import urlparse + + parsed = urlparse(url) + if not parsed.netloc or not parsed.path: + raise ValueError("bad {} path {}".format(provider, url)) + bucket_name = parsed.netloc + provider_path = parsed.path + # Remove '/' at beginning of path. + if provider_path.startswith("/"): + provider_path = provider_path[1:] + return bucket_name, provider_path + + def _ensure_object_info(self): + import botocore.exceptions as boto_exceptions + + if self.object_info is None: + try: + self.object_info = self.s3.head_object(Bucket=self.bucket_name, Key=self.path) + except boto_exceptions.ClientError as e: + if e.response["ResponseMetadata"]["HTTPStatusCode"] == 404: + raise FileNotFoundError(f"weka://{self.bucket_name}/{self.path}") from e + raise e + + def get_etag(self) -> Optional[str]: + self._ensure_object_info() + assert self.object_info is not None + return self.object_info.get("ETag") + + def get_size(self) -> Optional[int]: + self._ensure_object_info() + assert self.object_info is not None + return self.object_info.get("ContentLength") + + def get_resource(self, temp_file: io.BufferedWriter) -> None: + self.s3.download_fileobj(Fileobj=temp_file, Bucket=self.bucket_name, Key=self.path) + + def get_bytes_range(self, index: int, length: int) -> bytes: + response = self.s3.get_object( + Bucket=self.bucket_name, Key=self.path, Range=f"bytes={index}-{index + length - 1}" + ) + return response["Body"].read() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo_core/model_ladder.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo_core/model_ladder.py new file mode 100644 index 0000000000000000000000000000000000000000..90915bf1c579f790b1a92800dc2c30c8dba38816 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo_core/model_ladder.py @@ -0,0 +1,487 @@ +""" +Configuration classes for defining model ladder scaling ablations. +""" + +import logging +from abc import ABCMeta, abstractmethod +from dataclasses import dataclass, field + +from olmo_core.data.numpy_dataset import InstanceFilterConfig + +from .config import Config, StrEnum +from .data import ( + DataMix, + NumpyDataLoaderConfig, + NumpyDatasetConfig, + NumpyFSLDatasetConfig, + NumpyPaddedFSLDatasetConfig, + TokenizerConfig, +) +from .doc_utils import beta_feature +from .exceptions import OLMoConfigurationError +from .io import join_path +from .nn.transformer import TransformerConfig +from .optim import CosWithWarmup, OptimConfig +from .train import Duration, TrainerConfig +from .train.callbacks import ( + CheckpointerCallback, + CometCallback, + ConfigSaverCallback, + DownstreamEvaluatorCallbackConfig, + GarbageCollectorCallback, + GPUMemoryMonitorCallback, + LMEvaluatorCallbackConfig, + WandBCallback, +) +from .train.train_module import TransformerTrainModuleConfig + +__all__ = ["ModelSize", "ModelLadder", "RunDuration"] + +log = logging.getLogger(__name__) + + +class ModelSize(StrEnum): + """ + An enumeration of the standard model sizes in the ladder. + :class:`ModelLadder` implementations should produce models that match these sizes + as close as possible, ignoring embeddings. + """ + + size_190M = "190M" + """ + 190M parameters. + """ + size_370M = "370M" + """ + 370M parameters. + """ + size_600M = "600M" + """ + 600M parameters. + """ + size_760M = "760M" + """ + 760M parameters. + """ + size_1B = "1B" + """ + 1B parameters. + """ + size_3B = "3B" + """ + 3B parameters. + """ + size_7B = "7B" + """ + 7B parameters. + """ + size_13B = "13B" + """ + 13B parameters. + """ + + @property + def num_params(self) -> int: + value, unit = int(self[:-1]), self[-1] + if unit == "M": + return value * int(1e6) + elif unit == "B": + return value * int(1e9) + else: + raise NotImplementedError(self) + + +class RunDuration(StrEnum): + """ + An enumeration of the standard training durations for the ladder, in terms of Chinchilla multipliers. + """ + + Cx0_5 = "0.5xC" + """ + Multiplier of 0.5. + """ + + Cx1 = "1xC" + """ + Multiplier of 1. + """ + Cx2 = "2xC" + """ + Multiplier of 2. + """ + Cx5 = "5xC" + """ + Multiplier of 5. + """ + + Cx10 = "10xC" + """ + Multiplier of 10. + """ + + @property + def multiplier(self) -> float: + return float(self.split("xC")[0]) + + +@beta_feature +@dataclass +class ModelLadder(Config, metaclass=ABCMeta): + """ + Base class for defining model ladder experiments. + + At a minimum subclasses must implement: + + - :meth:`get_model_config()` + - :meth:`get_optim_config()` + - :meth:`get_rank_microbatch_size()` + + for every model size defined by :class:`ModelSize`. + """ + + name: str + """ + The name of the ladder runs. + """ + + project: str + """ + The name of the W&B/Comet project to save run data to. + """ + + mix_base_dir: str + """ + The base directory of the training data. + """ + + work_dir: str + """ + The local working directory used for dataset caching. + """ + + save_folder: str + """ + The local or remote folder to save checkpoints to. + """ + + sequence_length: int = 2048 + """ + The target sequence length to train the ladder on. + """ + + tokenizer: TokenizerConfig = field(default_factory=TokenizerConfig.dolma2) + """ + Get the tokenizer config to use throughput the ladder. + """ + + init_seed: int = 2352 + """ + The seed to use when first initializing RNG states. + """ + + data_mix: DataMix = DataMix.OLMoE_mix_0824 + """ + The data mix to train on. + """ + + data_seed: int = 34521 + """ + The seed to use for shuffling the data. + """ + + max_dp_world_size: int = 64 + """ + The maximum data parallel world size that you intent to run with. This is used to set the batch size. + """ + + @property + def model_size(self) -> int: + """ + The size of the model in terms of non-embedding parameters. + """ + return self._model_size + + def get_save_folder(self, size: ModelSize, run_duration: RunDuration) -> str: + return str(join_path(self.save_folder, f"checkpoints/{self.name}-{size}-{run_duration}")) + + @abstractmethod + def _get_model_config(self, *, size: ModelSize) -> TransformerConfig: + """ + Get the model config for a given model size. + + :param size: The target model size. + """ + raise NotImplementedError + + def get_model_config(self, *, size: ModelSize) -> TransformerConfig: + """ + Get the model config for a given model size. + + :param size: The target model size. + """ + model_config = self._get_model_config(size=size) + self._model_size = model_config.num_non_embedding_params + return model_config + + @abstractmethod + def get_optim_config(self) -> OptimConfig: + """ + Get the optimizer config for a given model size. + + :param size: The target model size. + """ + raise NotImplementedError + + def get_dataset_config(self) -> NumpyDatasetConfig: + """ + Get the train dataset config. + + :param kwargs: Extra kwargs to pass to the dataset config constructor. + """ + return NumpyFSLDatasetConfig.from_data_mix( + self.data_mix, + tokenizer=self.tokenizer, + mix_base_dir=self.mix_base_dir, + sequence_length=self.sequence_length, + work_dir=self.work_dir, + instance_filter_config=InstanceFilterConfig( + repetition_max_period=13, + repetition_min_period=1, + repetition_max_count=32, + ), + ) + + def get_data_loader_config(self) -> NumpyDataLoaderConfig: + """ + Get the data loader config. + + :param size: The target model size. + """ + return NumpyDataLoaderConfig( + global_batch_size=self.get_global_batch_size(), + seed=self.data_seed, + num_workers=4, + ) + + @abstractmethod + def get_rank_microbatch_size(self, *, size: ModelSize, gpu_type: str) -> int: + """ + Returns the maximum micro-batch size in tokens per device that should be used for the given + model size. + + :param size: The target model size. + :param gpu_type: The type of GPU as given by ``torch.cuda.get_device_name()``. + """ + raise NotImplementedError + + def get_global_batch_size(self) -> int: + """ + Get the global batch size in tokens for a given model size. + + :param size: The target model size. + """ + # Calculate batch size according to https://api.semanticscholar.org/CorpusID:270764838, + # which assumes a sequence length of 2048. So adjust from there accordingly. + assert self.sequence_length in {2048, 4096, 8192} + seq_len_divisor = self.sequence_length // 2048 + + global_batch_size = 160 * (self.model_size / 108000000) ** (2 / 3) + global_batch_size /= seq_len_divisor + global_batch_size /= self.max_dp_world_size + global_batch_size = round(global_batch_size) + global_batch_size *= self.max_dp_world_size + + return self.sequence_length * global_batch_size + + def get_train_module_config( + self, + *, + size: ModelSize, + run_duration: RunDuration, + gpu_type: str, + dp_world_size: int, + ) -> TransformerTrainModuleConfig: + """ + Build the train module config. + + :param size: The target model size. + :param gpu_type: The type of GPU as given by ``torch.cuda.get_device_name()``. + :param dp_world_size: The data parallel world size. + """ + if dp_world_size > self.max_dp_world_size: + raise OLMoConfigurationError( + f"max_dp_world_size ({self.max_dp_world_size}) must be at least as big as current dp " + f"world size ({dp_world_size})" + ) + + rank_mbz = self.get_rank_microbatch_size(size=size, gpu_type=gpu_type) + if rank_mbz % self.sequence_length != 0: + raise OLMoConfigurationError( + f"rank micro-batch size ({rank_mbz:,d} tokens) must be divisible " + f"by the sequence length ({self.sequence_length:,d})" + ) + + rank_mbz_instances = rank_mbz // self.sequence_length + + global_bz = self.get_global_batch_size() + if global_bz % self.sequence_length != 0: + raise OLMoConfigurationError( + f"global batch size ({rank_mbz:,d} tokens) must be divisible " + f"by the sequence length ({self.sequence_length:,d})" + ) + + global_bz_instances = self.get_global_batch_size() // self.sequence_length + + if global_bz_instances % (rank_mbz_instances * dp_world_size) != 0: + new_rank_mbz_instances = global_bz_instances // dp_world_size + if new_rank_mbz_instances > rank_mbz_instances: + for divisor in range(2, new_rank_mbz_instances + 1): + if ( + new_rank_mbz_instances % divisor == 0 + and new_rank_mbz_instances // divisor < rank_mbz_instances + ): + new_rank_mbz_instances //= divisor + break + else: + raise RuntimeError("shouldn't get here") + + assert new_rank_mbz_instances <= rank_mbz_instances + assert global_bz_instances % (new_rank_mbz_instances * dp_world_size) == 0 + + new_rank_mbz = new_rank_mbz_instances * self.sequence_length + log.warning( + f"Adjusting rank micro-batch size from {rank_mbz:,d} tokens ({rank_mbz_instances:,d} instances) " + f"down to {new_rank_mbz:,d} tokens ({new_rank_mbz_instances:,d} instances) to be compatible " + "with data parallel world size" + ) + rank_mbz = new_rank_mbz + return TransformerTrainModuleConfig( + rank_microbatch_size=rank_mbz, + max_sequence_length=self.sequence_length, + optim=self.get_optim_config(), + max_grad_norm=1.0, + scheduler=CosWithWarmup(warmup_steps=round(self.model_size / global_bz)), + ) + + def get_trainer_config( + self, + *, + size: ModelSize, + run_duration: RunDuration, + gpu_type: str, + dp_world_size: int, + ) -> TrainerConfig: + """ + Build the trainer config. + + :param size: The target model size. + :param gpu_type: The type of GPU as given by ``torch.cuda.get_device_name()``. + :param dp_world_size: The data parallel world size. + """ + del dp_world_size + + from olmo_eval import list_tasks + + config = TrainerConfig( + save_folder=self.get_save_folder(size, run_duration), + metrics_collect_interval=10, + cancel_check_interval=10, + max_duration=Duration.chinchilla_tokens( + multiple=run_duration.multiplier, + model_params=self.model_size, + ), + ) + if gpu_type not in ("cpu", "mps"): + config = config.with_callback("gpu_monitor", GPUMemoryMonitorCallback()) + config = config.with_callback("config_saver", ConfigSaverCallback()) + config = config.with_callback("garbage_collector", GarbageCollectorCallback()) + config = config.with_callback( + "lm_evaluator", + LMEvaluatorCallbackConfig( + eval_dataset=NumpyPaddedFSLDatasetConfig.from_data_mix( + DataMix.v3_small_ppl_validation, + mix_base_dir=self.mix_base_dir, + sequence_length=self.sequence_length, + tokenizer=self.tokenizer, + work_dir=self.work_dir, + ), + eval_interval=500, + ), + ) + config = config.with_callback( + "downstream_evaluator", + DownstreamEvaluatorCallbackConfig( + tasks=[task for task in list_tasks() if "_mc" not in task and "_var" not in task], + tokenizer=self.tokenizer, + eval_interval=500, + ), + ) + config = config.with_callback( + "checkpointer", + CheckpointerCallback( + save_interval=100_000, # large enough value that we won't save until the end + ephemeral_save_interval=250, + save_async=True, + ), + ) + config = config.with_callback( + "comet", + CometCallback( + name=f"{self.name}-{size}-{run_duration}", + workspace="ai2", + project=self.project, + enabled=True, + cancel_check_interval=5, + ), + ) + config = config.with_callback( + "wandb", + WandBCallback( + name=f"{self.name}-{size}-{run_duration}", + entity="ai2", + project=self.project, + enabled=False, + cancel_check_interval=5, + ), + ) + return config + + def validate(self): + """ + Validate the ladder configuration. + + :raises OLMoConfigurationError: If the ladder has any issues. + """ + for size in ModelSize: + # validating to match old ladder sizes. + if size == ModelSize.size_1B: + target_size = 1.3 + elif size == ModelSize.size_3B: + target_size = 3.2 + else: + target_size = int(size[:-1]) + if size.endswith("M"): + target_size = target_size * 10**6 + elif size.endswith("B"): + target_size = target_size * 10**9 + else: + raise NotImplementedError(size) + + model_config = self.get_model_config(size=size) + + # Make sure actual model size is close to target size. + num_params = model_config.num_non_embedding_params + if abs(num_params - target_size) / target_size > 0.05: + raise OLMoConfigurationError( + f"Model size of {num_params:,d} for sequence length {self.sequence_length} is " + f"too far from target size of {size}: {model_config}" + ) + + self.get_optim_config() + self.get_rank_microbatch_size(size=size, gpu_type="H100") + bz_tokens = self.get_global_batch_size() + if bz_tokens % self.sequence_length != 0: + raise OLMoConfigurationError( + f"Batch size of {bz_tokens:,d} tokens for model size {size} " + f"must be divisible by the sequence length ({self.sequence_length})" + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo_core/py.typed b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo_core/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo_core/script_utils.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo_core/script_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..1ae718bf681e6d38563e07b218bb7233d185fe35 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo_core/script_utils.py @@ -0,0 +1,177 @@ +import argparse +import logging +import sys +from dataclasses import dataclass +from typing import Callable, List, Optional, Tuple + +import rich + +from olmo_core.aliases import PathOrStr +from olmo_core.config import Config +from olmo_core.data import NumpyDataLoaderConfig, NumpyDatasetConfig +from olmo_core.distributed.checkpoint import get_checkpoint_metadata, load_state_dict +from olmo_core.io import is_url, join_path, normalize_path +from olmo_core.nn.transformer import TransformerConfig +from olmo_core.train import ( + TrainerConfig, + prepare_training_environment, + teardown_training_environment, +) +from olmo_core.train.callbacks import ConfigSaverCallback +from olmo_core.train.train_module import TransformerTrainModuleConfig +from olmo_core.utils import prepare_cli_environment, seed_all + +log = logging.getLogger(__name__) + + +@dataclass +class ExperimentConfig(Config): + model: TransformerConfig + dataset: NumpyDatasetConfig + data_loader: NumpyDataLoaderConfig + train_module: TransformerTrainModuleConfig + trainer: TrainerConfig + init_seed: int = 12536 + load_path: Optional[str] = None + + +def get_cli_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + prog=sys.argv[0], + usage=f"python {sys.argv[0]} [OPTIONS...] [CONFIG_OVERRIDES...]", + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + parser.add_argument( + "--name", + type=str, + help="""A name to assign the run for logging.""", + ) + parser.add_argument( + "--sequence-length", + type=int, + default=None, + help="""The sequence length to train and eval on. Different scripts have different default + sequence-length values. If a value is not specified here, the default value is used.""", + ) + parser.add_argument( + "--data-root", + type=str, + default="https://olmo-data.org", + help="""The root directory/URL of the data source files. + The default 'https://olmo-data.org' is public, but potentially very slow. + Ai2 employees should prefer '/weka/oe-training-default/ai2-llm' when using a cluster with weka access, + otherwise 'gs://ai2-llm' or 's3://ai2-llm'.""", + ) + parser.add_argument( + "--save-folder", + type=str, + required=True, + help="""A local or remote directory to save checkpoints to. + All ranks should have access to this directory, so when training in a multi-node setup + this could either be a path to a folder on a shared filesystem (such as NFS) or a URL + to cloud storage, like 's3://...' or 'gs://...'.""", + ) + parser.add_argument( + "--work-dir", + type=str, + help="""A local directory to use as a working directory for dataset preprocessing. + If not set this will be inferred from the save folder.""", + ) + parser.add_argument( + "--dry-run", + action="store_true", + help="""Print the config and exit.""", + ) + return parser + + +def _parse_args( + parser: Optional[argparse.ArgumentParser] = None, +) -> Tuple[argparse.Namespace, List[str]]: + parser = parser if parser is not None else get_cli_parser() + opts, overrides = parser.parse_known_args() + if opts.work_dir is None: + if is_url(opts.save_folder): + opts.work_dir = "/tmp/olmo-core/dataset-cache" + else: + opts.work_dir = opts.save_folder + return opts, overrides + + +def main( + config_builder: Callable[[argparse.Namespace, List[str]], ExperimentConfig], + parser: Optional[argparse.ArgumentParser] = None, +) -> None: + opts, overrides = _parse_args(parser) + if opts.dry_run: + prepare_cli_environment() + + config = config_builder(opts, overrides) + + if opts.dry_run: + rich.print(config) + return + + prepare_training_environment(shared_filesystem=not is_url(opts.save_folder)) + + # Set RNG states on all devices. + seed_all(config.init_seed) + + # Build components. + model = config.model.build(init_device="meta") + train_module = config.train_module.build(model) + dataset = config.dataset.build() + data_loader = config.data_loader.build(dataset, dp_process_group=train_module.dp_process_group) + trainer = config.trainer.build(train_module, data_loader) + + # Save config to W&B and each checkpoint dir. + for callback in trainer.callbacks.values(): + if isinstance(callback, ConfigSaverCallback): + callback.config = config.as_config_dict() + break + + # If we have a load path set and there is no checkpoint in the save folder, load the + # checkpoint from the load path. + if not trainer.no_checkpoints and not trainer.maybe_load_checkpoint() and config.load_path: + log.info( + f"Loading checkpoint from {config.load_path} since no checkpoints were found in the save folder..." + ) + trainer.load_checkpoint(config.load_path, load_trainer_state=False) + + # Train. + trainer.fit() + + # Tear-down distributed backend. + teardown_training_environment() + + +def get_lr_from_checkpoint( + path: PathOrStr, param: Optional[str] = None, param_group: Optional[int] = None +) -> float: + path = normalize_path(path) + if not path.endswith("/model_and_optim"): + path = join_path(path, "model_and_optim") + + metadata = get_checkpoint_metadata(path) + if "optim.param_groups.0.params" in metadata.state_dict_metadata: + # unflattened optimizer state + if param is not None: + log.warning( + "'param' will be ignored since the optimizer state in the checkpoint to load is in unflattened format" + ) + if param_group is None: + param_group = 0 + key = f"optim.param_groups.{param_group}.lr" + else: + if param_group is not None: + raise RuntimeError( + "'param_group' is required since the optimizer state in the checkpoint to load is in flattened format" + ) + if param is None: + param = "embeddings.weight" + key = f"optim.param_groups.{param}.lr" + + state_dict = {key: None} + load_state_dict(path, state_dict) + assert state_dict[key] is not None + return float(state_dict[key]) # type: ignore diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo_core/utils.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo_core/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..da79876be6bff970c38499fb3d98ca8d70fa9b57 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo_core/utils.py @@ -0,0 +1,755 @@ +import dataclasses +import gc +import logging +import math +import os +import socket +import sys +import time +import uuid +import warnings +from contextlib import contextmanager +from datetime import datetime, timedelta +from functools import lru_cache +from itertools import cycle, islice +from queue import Queue +from threading import Thread +from typing import Any, Callable, Dict, List, Optional, Sequence, TypeVar, Union, cast + +import rich +import torch +import torch.distributed as dist +from rich.console import Console, ConsoleRenderable +from rich.highlighter import NullHighlighter +from rich.text import Text +from rich.traceback import Traceback + +from .config import StrEnum +from .exceptions import OLMoCLIError, OLMoEnvironmentError, OLMoError, OLMoThreadError + +OLMO_NUM_THREADS_ENV_VAR = "OLMO_NUM_THREADS" +LOG_FILTER_TYPE_ENV_VAR = "LOG_FILTER_TYPE" + + +_log_extra_fields: Dict[str, Any] = {} +_LOGGING_CONFIGURED: bool = False +log = logging.getLogger(__name__) + + +def generate_uuid() -> str: + """ + Generate a unique ID. + """ + return str(uuid.uuid4()) + + +def get_default_thread_count() -> int: + """ + Get the default maximum number of threads allowed. + """ + env_val = os.environ.get(OLMO_NUM_THREADS_ENV_VAR) + if env_val is not None: + try: + return int(env_val) + except ValueError: + raise OLMoEnvironmentError( + f"Invalid value for {OLMO_NUM_THREADS_ENV_VAR} environment variable ('{env_val}')" + ) + else: + return min(16, (os.cpu_count() or 1) + 4) + + +def wait_for(condition: Callable[[], bool], description: str, timeout: float = 10.0): + """Wait for the condition function to return True.""" + start_time = time.monotonic() + while not condition(): + time.sleep(0.5) + if time.monotonic() - start_time > timeout: + raise TimeoutError(f"timed out {description}") + + +def apply_to_tensors(fn, container: Any) -> None: + """ + Recursively apply ``fn`` to all tensors in a container. + """ + if isinstance(container, torch.Tensor): + fn(container) + elif isinstance(container, (list, tuple, set)): + for x in container: + apply_to_tensors(fn, x) + elif isinstance(container, dict): + for k, v in container.items(): + apply_to_tensors(fn, k) + apply_to_tensors(fn, v) + elif hasattr(container, "__dataclass_fields__"): + for f in dataclasses.fields(container): + name = f.name + apply_to_tensors(fn, getattr(container, name)) + elif hasattr(container, "__next__"): + for x in container: + apply_to_tensors(fn, x) + + +T = TypeVar("T") + + +def move_to_device(o: T, device: torch.device, non_blocking: Optional[bool] = None) -> T: + """ + Move a tensor or container of tensors to the given device. + + :param o: The object to move. + :param device: The device to move to. + """ + if non_blocking is None: + non_blocking = device.type not in ("cpu", "mps") + if isinstance(o, torch.Tensor): + return o.to(device, non_blocking=non_blocking) # type: ignore[return-value] + elif isinstance(o, dict): + return {k: move_to_device(v, device) for k, v in o.items()} # type: ignore[return-value] + elif isinstance(o, list): + return [move_to_device(x, device) for x in o] # type: ignore[return-value] + elif isinstance(o, tuple): + return tuple((move_to_device(x, device) for x in o)) # type: ignore[return-value] + else: + return o + + +def mark_dynamic(x: torch.Tensor, dim: Union[int, Sequence[int]], strict: bool = True): + """ + Mark a tensor as having dynamic sizes for ``torch.compile()``. + """ + if strict: + torch._dynamo.mark_dynamic(x, dim) + else: + torch._dynamo.maybe_mark_dynamic(x, dim) + + +def get_default_device() -> torch.device: + """ + Get the default device. + """ + + from .distributed.utils import ( + backend_supports_cpu, + backend_supports_cuda, + is_distributed, + ) + + if is_distributed(): + backend = dist.get_backend() + if backend_supports_cuda(backend): + return torch.device("cuda") + elif backend_supports_cpu(backend): + return torch.device("cpu") + else: + raise NotImplementedError(backend) + elif torch.cuda.is_available(): + return torch.device("cuda") + elif torch.mps.is_available(): + return torch.device("mps") + else: + return torch.device("cpu") + + +def seed_all(seed: int): + """ + Seed all RNG states. + """ + import random + + import numpy as np + + if seed < 0 or seed > 2**32 - 1: + raise ValueError(f"Seed {seed} is invalid. It must be on [0; 2^32 - 1]") + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + # torch.manual_seed may call manual_seed_all but calling it again here + # to make sure it gets called at least once + torch.cuda.manual_seed_all(seed) + + +def same_storage(x: torch.Tensor, y: torch.Tensor) -> bool: + """ + Check if two tensors share the same storage. + """ + x_ptrs = set(e.data_ptr() for e in x.view(-1)) + y_ptrs = set(e.data_ptr() for e in y.view(-1)) + return (x_ptrs <= y_ptrs) or (y_ptrs <= x_ptrs) + + +def gc_cuda(): + """ + Run garbage collection, including emptying the CUDA cache. + """ + gc.collect() + if torch.cuda.is_available(): + torch.cuda.empty_cache() + + +def has_flash_attn() -> bool: + """ + Check if flash-attn is available. + """ + try: + import flash_attn # type: ignore + + del flash_attn + return True + except ModuleNotFoundError: + return False + + +def set_env_var(name: str, value: str, override: bool = False, secret: bool = False): + value_str = "****" if secret else value + if name in os.environ: + if os.environ[name] != value: + if override: + log_or_print(log, f"Overriding env var '{name}' to '{value_str}'", logging.WARNING) + os.environ[name] = value + else: + log_or_print( + log, + f"Will skip setting env var '{name}' since it's already set to '{value_str}'", + logging.WARNING, + ) + else: + log_or_print(log, f"Env var '{name}' already set to '{value_str}'") + else: + log_or_print(log, f"Setting env var '{name}' to '{value_str}'") + os.environ[name] = value + + +def log_or_print(logger: logging.Logger, msg: str, level: int = logging.INFO): + if _LOGGING_CONFIGURED or ( + len(logging.getLogger().handlers) > 0 and logger.getEffectiveLevel() <= level + ): + logger.log(level, msg) + else: + print(msg) + + +class LogFilterType(StrEnum): + """ + Determines which ranks are allowed to emit INFO messages. + """ + + rank0_only = "rank0_only" + """ + INFO messages are only emitted from the global rank 0. + """ + + local_rank0_only = "local_rank0_only" + """ + INFO messages are only emitted from the local (node) rank 0. + """ + + all_ranks = "all_ranks" + """ + All ranks emit INFO messages. + """ + + +def log_extra_field(field_name: str, field_value: Any) -> None: + """ + Add an additional field to each log record. + + .. note:: + For these fields to actually show up in the logs you need to use a formatter/handler + that displays them. + + :param field_name: The name of the field to attach. + :param field_value: The value of the field to attach. + """ + global _log_extra_fields + if field_value is None: + if field_name in _log_extra_fields: + del _log_extra_fields[field_name] + else: + _log_extra_fields[field_name] = field_value + + +def setup_logging( + log_filter_type: LogFilterType = LogFilterType.rank0_only, force: bool = False +) -> None: + """ + Configure logging. + + .. seealso:: + :func:`prepare_cli_environment()` + + :param log_filter_type: Which ranks emit INFO and below messages. + :param force: Force configuring logging even if it was already configured. + """ + global _LOGGING_CONFIGURED + + if _LOGGING_CONFIGURED and not force: + return + + from .distributed.utils import get_local_rank, get_rank + + log_extra_field("hostname", socket.gethostname()) + log_extra_field("local_rank", get_local_rank()) + log_extra_field("global_rank", get_rank()) + + old_log_record_factory = logging.getLogRecordFactory() + + def log_record_factory(*args, **kwargs) -> logging.LogRecord: + record = old_log_record_factory(*args, **kwargs) + for field_name, field_value in _log_extra_fields.items(): + setattr(record, field_name, field_value) + return record + + logging.setLogRecordFactory(log_record_factory) + + handler: logging.Handler + # NOTE: Beaker supports rich logging now. + if os.environ.get("BEAKER_EXPERIMENT_ID") is None and ( + os.environ.get("DEBIAN_FRONTEND", None) == "noninteractive" or not sys.stdout.isatty() + ): + handler = logging.StreamHandler(sys.stdout) + formatter = logging.Formatter( + "%(asctime)s\t%(hostname)s:%(local_rank)s\t%(name)s:%(lineno)s\t%(levelname)s\t%(message)s" + ) + formatter.default_time_format = "%Y-%m-%d %H:%M:%S" + formatter.default_msec_format = "%s.%03d" + handler.setFormatter(formatter) + else: + handler = _RichHandler() + + def rank0_filter(record: logging.LogRecord) -> int: + if record.levelno > logging.INFO: + return 1 + if getattr(record, "global_rank", 0) == 0: + return 1 + else: + return 0 + + def local_rank0_filter(record: logging.LogRecord) -> int: + if record.levelno > logging.INFO: + return 1 + if getattr(record, "local_rank", 0) == 0: + return 1 + else: + return 0 + + if log_filter_type == LogFilterType.rank0_only: + filter = rank0_filter + elif log_filter_type == LogFilterType.local_rank0_only: + filter = local_rank0_filter # type: ignore + elif log_filter_type == LogFilterType.all_ranks: + filter = None + else: + raise ValueError(log_filter_type) + + if filter is not None: + handler.addFilter(filter) # type: ignore + logging.basicConfig(handlers=[handler], level=logging.INFO, force=True) + + logging.captureWarnings(True) + logging.getLogger("urllib3").setLevel(logging.ERROR) + logging.getLogger("google").setLevel(logging.WARNING) + + _LOGGING_CONFIGURED = True + + +def logging_configured() -> bool: + """ + Returns ``True`` if logging has been configured (like with :func:`setup_logging()`), + otherwise returns ``False``. + """ + if _LOGGING_CONFIGURED: + return True + else: + # Otherwise check if the root logger has any handlers. + return len(logging.getLogger().handlers) > 0 + + +def excepthook(exctype, value, traceback): + """ + Used to patch ``sys.excepthook`` in order to log exceptions. Use :func:`install_excepthook()` + to install this. + """ + if issubclass(exctype, KeyboardInterrupt): + sys.__excepthook__(exctype, value, traceback) + elif issubclass(exctype, OLMoCLIError): + rich.get_console().print(f"[yellow]{value}[/]", highlight=False) + elif issubclass(exctype, OLMoError): + rich.get_console().print(Text(f"{exctype.__name__}:", style="red"), value, highlight=False) + else: + log.critical( + "Uncaught %s: %s", exctype.__name__, value, exc_info=(exctype, value, traceback) + ) + + +def install_excepthook(): + """ + Install the custom :func:`excepthook`. + + .. seealso:: + :func:`prepare_cli_environment()` + """ + sys.excepthook = excepthook + + +def filter_warnings(): + """ + Configure warning filters for warnings we don't need to see. + + .. seealso:: + :func:`prepare_cli_environment()` + """ + # Filter internal deprecation warnings from torch + warnings.filterwarnings( + action="ignore", + category=UserWarning, + message="torch.distributed.*_base is a private function and will be deprecated.*", + ) + warnings.filterwarnings( + action="ignore", + category=UserWarning, + message="TypedStorage is deprecated.*", + ) + warnings.filterwarnings( + action="ignore", + category=UserWarning, + message="Please use DTensor instead.*", + ) + warnings.filterwarnings( + action="ignore", + category=UserWarning, + message="Synchronization debug mode is a prototype feature.*", + module="torch.cuda", + ) + warnings.filterwarnings( + action="ignore", + category=UserWarning, + message="TORCH_NCCL_AVOID_RECORD_STREAMS=1 has no effect .*", + ) + warnings.filterwarnings( + action="ignore", + category=FutureWarning, + message="You are using `torch.load` with `weights_only=False`.*", + ) + # flash_attn warnings. + warnings.filterwarnings( + action="ignore", + category=FutureWarning, + module="flash_attn.ops.triton.layer_norm", + ) + # Torchvision warnings. We don't actually use torchvision. + warnings.filterwarnings( + action="ignore", + message="failed to load.*", + module="torchvision.io.image", + ) + + +def set_env_variables(): + """ + Set common needed env vars if they're not already set. + + .. seealso:: + :func:`prepare_cli_environment()` + """ + set_env_var("OMP_NUM_THREADS", "8") + set_env_var("TOKENIZERS_PARALLELISM", "false") + + +def prepare_cli_environment(log_filter_type: Optional[LogFilterType] = None): + """ + Prepare the environment for a script/CLI. + This should be called at the very beginning of the script/command, like at the top + of the ``if __name__ == "__main__": ...`` block. + + Internally this calls: + + - :func:`setup_logging()` + - :func:`install_excepthook()` + - :func:`filter_warnings()` + - :func:`set_env_variables()` + - :func:`~olmo_core.io.add_cached_path_clients()` + + .. tip:: + If you're looking to setup the environment specifically for distributed training, + see :func:`~olmo_core.train.prepare_training_environment` instead. + + :param log_filter_type: Determines which ranks are allowed to emit log messages below the + ``WARNING`` level. You can also configure this through the env var ``LOG_FILTER_TYPE``. + If neither are set, this defaults to "rank0_only". + + .. note:: + All ranks will always emit messages at the ``WARNING`` level or higher. + """ + from .io import add_cached_path_clients + + if log_filter_type is None: + log_filter_type = LogFilterType(os.environ.get(LOG_FILTER_TYPE_ENV_VAR, "rank0_only")) + rich.reconfigure(width=max(rich.get_console().width, 180), soft_wrap=True) + setup_logging(log_filter_type=log_filter_type) + install_excepthook() + filter_warnings() + set_env_variables() + add_cached_path_clients() + + +class _RichHandler(logging.Handler): + """ + A simplified version of rich.logging.RichHandler from + https://github.com/Textualize/rich/blob/master/rich/logging.py + """ + + def __init__( + self, + *, + level: Union[int, str] = logging.NOTSET, + console: Optional[Console] = None, + markup: bool = False, + ) -> None: + super().__init__(level=level) + self.console = console or rich.get_console() + self.highlighter = NullHighlighter() + self.markup = markup + + def emit(self, record: logging.LogRecord) -> None: + try: + if hasattr(record.msg, "__rich__") or hasattr(record.msg, "__rich_console__"): + self.console.print(record.msg) + else: + msg: Any = record.msg + if isinstance(record.msg, str): + msg = self.render_message(record=record, message=record.getMessage()) + renderables = [ + self.get_time_text(record), + self.get_level_text(record), + self.get_location_text(record), + msg, + ] + if record.exc_info is not None: + tb = Traceback.from_exception(*record.exc_info) # type: ignore + renderables.append(tb) + self.console.print(*renderables) + except Exception: + self.handleError(record) + + def render_message(self, *, record: logging.LogRecord, message: str) -> ConsoleRenderable: + use_markup = getattr(record, "markup", self.markup) + message_text = Text.from_markup(message) if use_markup else Text(message) + + highlighter = getattr(record, "highlighter", self.highlighter) + if highlighter: + message_text = highlighter(message_text) + + return message_text + + def get_time_text(self, record: logging.LogRecord) -> Text: + log_time = datetime.fromtimestamp(record.created) + time_str = log_time.strftime("[%Y-%m-%d %X]") + return Text(time_str, style="log.time", end=" ") + + def get_level_text(self, record: logging.LogRecord) -> Text: + level_name = record.levelname + level_text = Text.styled(level_name.ljust(8), f"logging.level.{level_name.lower()}") + level_text.style = "log.level" + level_text.end = " " + return level_text + + def get_location_text(self, record: logging.LogRecord) -> Text: + name_and_line = f"{record.name}:{record.lineno}" if record.name != "root" else "root" + text = f"[{name_and_line}, rank={record.local_rank}]" # type: ignore + return Text(text, style="log.path") + + +def threaded_generator(g, maxsize: int = 16, thread_name: Optional[str] = None): + """ + Wraps a generator ``g`` and runs it in a thread. + """ + q: Queue = Queue(maxsize=maxsize) + + sentinel = object() + + def fill_queue(): + try: + for value in g: + q.put(value) + except Exception as e: + q.put(e) + finally: + q.put(sentinel) + + thread_name = thread_name or repr(g) + thread = Thread(name=thread_name, target=fill_queue, daemon=True) + thread.start() + + for x in iter(q.get, sentinel): + if isinstance(x, Exception): + raise OLMoThreadError(f"generator thread {thread_name} failed") from x + else: + yield x + + +def roundrobin(*iterables): + """ + Call the given iterables in a round-robin fashion. For example: + ``roundrobin('ABC', 'D', 'EF') --> A D E B F C`` + """ + # Adapted from https://docs.python.org/3/library/itertools.html#itertools-recipes + num_active = len(iterables) + nexts = cycle(iter(it).__next__ for it in iterables) + while num_active: + try: + for next in nexts: + yield next() + except StopIteration: + # Remove the iterator we just exhausted from the cycle. + num_active -= 1 + nexts = cycle(islice(nexts, num_active)) + + +def powers_of_2(x: int) -> List[int]: + powers: List[int] = [] + i = 1 + while i <= x: + if i & x: + powers.insert(0, i) + i <<= 1 + return powers + + +def capped_powers_of_2(x: int, cap: int) -> List[int]: + powers = [] + for i in powers_of_2(x): + if i > cap: + assert i % cap == 0 + for _ in range(i // cap): + powers.append(cap) + else: + powers.append(i) + return powers + + +def format_float(value: float) -> str: + if value == 0.0: + return "0.0" + elif value < 0.0001: + return f"{value:.2E}" + elif value > 1000: + return f"{int(value):,d}" + elif value > 100: + return f"{value:.1f}" + elif value > 10: + return f"{value:.2f}" + elif value > 1: + return f"{value:.3f}" + else: + return f"{value:.4f}" + + +def format_timedelta(td: timedelta) -> str: + breakdown = [] + if td.days > 0: + breakdown.append(f"{td.days}d") + + hours = td.seconds // 3600 + if hours > 0: + breakdown.append(f"{hours}h") + + minutes = (td.seconds % 3600) // 60 + if minutes > 0: + breakdown.append(f"{minutes}m") + + seconds = td.seconds % 60 + if seconds > 0: + breakdown.append(f"{seconds}s") + + if breakdown: + return ", ".join(breakdown) + else: + return "0s" + + +def flatten_dict(d: Dict[str, Any]) -> Dict[str, Any]: + """ + Flatten a nested dictionary with strings keys using dot notation. + """ + out = {} + + def add_sub_dict(prefix: str, sub_dict: Dict[str, Any]): + for k, v in sub_dict.items(): + if isinstance(v, dict): + add_sub_dict(f"{prefix}.{k}", v) + else: + out[f"{prefix}.{k}"] = v + + for k, v in d.items(): + if isinstance(v, dict): + add_sub_dict(k, v) + else: + out[k] = v + + return out + + +@contextmanager +def cuda_sync_debug_mode(debug_mode: Union[int, str]): + """ + A context manager for temporarily setting the CUDA sync debug mode. + """ + current_mode: Optional[int] = None + + try: + if torch.cuda.is_available(): + current_mode = torch.cuda.get_sync_debug_mode() + torch.cuda.set_sync_debug_mode(debug_mode) + yield + finally: + if current_mode is not None: + torch.cuda.set_sync_debug_mode(current_mode) + + +def get_element_size(dtype: torch.dtype) -> int: + """ + Get the size in bytes of element of the given PyTorch dtype. + """ + return torch._utils._element_size(dtype) # type: ignore + + +def ensure_multiple_of(x: int, of: int) -> int: + return of * math.ceil(x / of) + + +@lru_cache(maxsize=128) +def log_once(logger: logging.Logger, msg: str, *args, level: int = logging.INFO, **kwargs): + logger.log(level, msg, *args, **kwargs) + + +def info_value_of_dtype(dtype: torch.dtype): + """ + Returns the `finfo` or `iinfo` object of a given PyTorch data type. Does not allow torch.bool. + """ + if dtype == torch.bool: + raise TypeError("Does not support torch.bool") + elif dtype.is_floating_point: + return torch.finfo(dtype) + else: + return torch.iinfo(dtype) + + +def min_value_of_dtype(dtype: torch.dtype): + """ + Returns the minimum value of a given PyTorch data type. Does not allow torch.bool. + """ + return info_value_of_dtype(dtype).min + + +_CUDA_STREAMS: Dict[str, torch.cuda.Stream] = {} + + +def get_or_init_stream(id: str, priority: int = 0) -> torch.cuda.Stream: + global _CUDA_STREAMS + if id in _CUDA_STREAMS: + return _CUDA_STREAMS[id] + else: + stream = cast(torch.cuda.Stream, torch.cuda.Stream(priority=priority)) + _CUDA_STREAMS[id] = stream + return stream diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo_core/version.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo_core/version.py new file mode 100644 index 0000000000000000000000000000000000000000..5f0eeb6966f793906e0dc3b01245c6b7b73a9887 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo_core/version.py @@ -0,0 +1,16 @@ +_MAJOR = "2" +_MINOR = "4" +_PATCH = "0" +_SUFFIX = "" + +VERSION_SHORT = "{0}.{1}".format(_MAJOR, _MINOR) +VERSION = "{0}.{1}.{2}{3}".format(_MAJOR, _MINOR, _PATCH, _SUFFIX) + + +if __name__ == "__main__": + import sys + + if sys.argv[-1] == "short": + print(VERSION_SHORT) + else: + print(VERSION) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/openai-2.36.0.dist-info/INSTALLER b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/openai-2.36.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/openai-2.36.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/openai-2.36.0.dist-info/METADATA b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/openai-2.36.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..e51cdff6e92359ec1a61d48105978b958e44b335 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/openai-2.36.0.dist-info/METADATA @@ -0,0 +1,1012 @@ +Metadata-Version: 2.3 +Name: openai +Version: 2.36.0 +Summary: The official Python library for the openai API +Project-URL: Homepage, https://github.com/openai/openai-python +Project-URL: Repository, https://github.com/openai/openai-python +Author-email: OpenAI +License: Apache-2.0 +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Operating System :: MacOS +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: OS Independent +Classifier: Operating System :: POSIX +Classifier: Operating System :: POSIX :: Linux +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.14 +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Typing :: Typed +Requires-Python: >=3.9 +Requires-Dist: anyio<5,>=3.5.0 +Requires-Dist: distro<2,>=1.7.0 +Requires-Dist: httpx<1,>=0.23.0 +Requires-Dist: jiter<1,>=0.10.0 +Requires-Dist: pydantic<3,>=1.9.0 +Requires-Dist: sniffio +Requires-Dist: tqdm>4 +Requires-Dist: typing-extensions<5,>=4.11 +Requires-Dist: typing-extensions<5,>=4.14 +Provides-Extra: aiohttp +Requires-Dist: aiohttp; extra == 'aiohttp' +Requires-Dist: httpx-aiohttp>=0.1.9; extra == 'aiohttp' +Provides-Extra: datalib +Requires-Dist: numpy>=1; extra == 'datalib' +Requires-Dist: pandas-stubs>=1.1.0.11; extra == 'datalib' +Requires-Dist: pandas>=1.2.3; extra == 'datalib' +Provides-Extra: realtime +Requires-Dist: websockets<16,>=13; extra == 'realtime' +Provides-Extra: voice-helpers +Requires-Dist: numpy>=2.0.2; extra == 'voice-helpers' +Requires-Dist: sounddevice>=0.5.1; extra == 'voice-helpers' +Description-Content-Type: text/markdown + +# OpenAI Python API library + + +[![PyPI version](https://img.shields.io/pypi/v/openai.svg?label=pypi%20(stable))](https://pypi.org/project/openai/) + +The OpenAI Python library provides convenient access to the OpenAI REST API from any Python 3.9+ +application. The library includes type definitions for all request params and response fields, +and offers both synchronous and asynchronous clients powered by [httpx](https://github.com/encode/httpx). + +It is generated from our [OpenAPI specification](https://github.com/openai/openai-openapi) with [Stainless](https://stainlessapi.com/). + +## Documentation + +The REST API documentation can be found on [platform.openai.com](https://platform.openai.com/docs/api-reference). The full API of this library can be found in [api.md](https://github.com/openai/openai-python/tree/main/api.md). + +## Installation + +```sh +# install from PyPI +pip install openai +``` + +## Usage + +The full API of this library can be found in [api.md](https://github.com/openai/openai-python/tree/main/api.md). + +The primary API for interacting with OpenAI models is the [Responses API](https://platform.openai.com/docs/api-reference/responses). You can generate text from the model with the code below. + +```python +import os +from openai import OpenAI + +client = OpenAI( + # This is the default and can be omitted + api_key=os.environ.get("OPENAI_API_KEY"), +) + +response = client.responses.create( + model="gpt-5.2", + instructions="You are a coding assistant that talks like a pirate.", + input="How do I check if a Python object is an instance of a class?", +) + +print(response.output_text) +``` + +The previous standard (supported indefinitely) for generating text is the [Chat Completions API](https://platform.openai.com/docs/api-reference/chat). You can use that API to generate text from the model with the code below. + +```python +from openai import OpenAI + +client = OpenAI() + +completion = client.chat.completions.create( + model="gpt-5.2", + messages=[ + {"role": "developer", "content": "Talk like a pirate."}, + { + "role": "user", + "content": "How do I check if a Python object is an instance of a class?", + }, + ], +) + +print(completion.choices[0].message.content) +``` + +While you can provide an `api_key` keyword argument, +we recommend using [python-dotenv](https://pypi.org/project/python-dotenv/) +to add `OPENAI_API_KEY="My API Key"` to your `.env` file +so that your API key is not stored in source control. +[Get an API key here](https://platform.openai.com/settings/organization/api-keys). + +### Workload Identity Authentication + +For secure, automated environments like cloud-managed Kubernetes, Azure, and Google Cloud Platform, you can use workload identity authentication with short-lived tokens from cloud identity providers instead of long-lived API keys. + +#### Kubernetes (service account tokens) + +```python +from openai import OpenAI +from openai.auth import k8s_service_account_token_provider + +client = OpenAI( + workload_identity={ + "client_id": "your-client-id", + "identity_provider_id": "idp-123", + "service_account_id": "sa-456", + "provider": k8s_service_account_token_provider( + "/var/run/secrets/kubernetes.io/serviceaccount/token" + ), + }, + organization="org-xyz", + project="proj-abc", +) + +response = client.chat.completions.create( + model="gpt-4", + messages=[{"role": "user", "content": "Hello!"}], +) +``` + +#### Azure (managed identity) + +```python +from openai import OpenAI +from openai.auth import azure_managed_identity_token_provider + +client = OpenAI( + workload_identity={ + "client_id": "your-client-id", + "identity_provider_id": "idp-123", + "service_account_id": "sa-456", + "provider": azure_managed_identity_token_provider( + resource="https://management.azure.com/", + ), + }, +) +``` + +#### Google Cloud Platform (compute engine metadata) + +```python +from openai import OpenAI +from openai.auth import gcp_id_token_provider + +client = OpenAI( + workload_identity={ + "client_id": "your-client-id", + "identity_provider_id": "idp-123", + "service_account_id": "sa-456", + "provider": gcp_id_token_provider(audience="https://api.openai.com/v1"), + }, +) +``` + +#### Custom subject token provider + +```python +from openai import OpenAI + + +def get_custom_token() -> str: + return "your-jwt-token" + + +client = OpenAI( + workload_identity={ + "client_id": "your-client-id", + "identity_provider_id": "idp-123", + "service_account_id": "sa-456", + "provider": { + "token_type": "jwt", + "get_token": get_custom_token, + }, + } +) +``` + +You can also customize the token refresh buffer (default is 1200 seconds (20 minutes) before expiration): + +```python +from openai import OpenAI +from openai.auth import k8s_service_account_token_provider + +client = OpenAI( + workload_identity={ + "client_id": "your-client-id", + "identity_provider_id": "idp-123", + "service_account_id": "sa-456", + "provider": k8s_service_account_token_provider("/var/token"), + "refresh_buffer_seconds": 120.0, + } +) +``` + +### Vision + +With an image URL: + +```python +prompt = "What is in this image?" +img_url = "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d5/2023_06_08_Raccoon1.jpg/1599px-2023_06_08_Raccoon1.jpg" + +response = client.responses.create( + model="gpt-5.2", + input=[ + { + "role": "user", + "content": [ + {"type": "input_text", "text": prompt}, + {"type": "input_image", "image_url": f"{img_url}"}, + ], + } + ], +) +``` + +With the image as a base64 encoded string: + +```python +import base64 +from openai import OpenAI + +client = OpenAI() + +prompt = "What is in this image?" +with open("path/to/image.png", "rb") as image_file: + b64_image = base64.b64encode(image_file.read()).decode("utf-8") + +response = client.responses.create( + model="gpt-5.2", + input=[ + { + "role": "user", + "content": [ + {"type": "input_text", "text": prompt}, + {"type": "input_image", "image_url": f"data:image/png;base64,{b64_image}"}, + ], + } + ], +) +``` + +## Async usage + +Simply import `AsyncOpenAI` instead of `OpenAI` and use `await` with each API call: + +```python +import os +import asyncio +from openai import AsyncOpenAI + +client = AsyncOpenAI( + # This is the default and can be omitted + api_key=os.environ.get("OPENAI_API_KEY"), +) + + +async def main() -> None: + response = await client.responses.create( + model="gpt-5.2", input="Explain disestablishmentarianism to a smart five year old." + ) + print(response.output_text) + + +asyncio.run(main()) +``` + +Functionality between the synchronous and asynchronous clients is otherwise identical. + +### With aiohttp + +By default, the async client uses `httpx` for HTTP requests. However, for improved concurrency performance you may also use `aiohttp` as the HTTP backend. + +You can enable this by installing `aiohttp`: + +```sh +# install from PyPI +pip install openai[aiohttp] +``` + +Then you can enable it by instantiating the client with `http_client=DefaultAioHttpClient()`: + +```python +import os +import asyncio +from openai import DefaultAioHttpClient +from openai import AsyncOpenAI + + +async def main() -> None: + async with AsyncOpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + http_client=DefaultAioHttpClient(), + ) as client: + chat_completion = await client.chat.completions.create( + messages=[ + { + "role": "user", + "content": "Say this is a test", + } + ], + model="gpt-5.2", + ) + + +asyncio.run(main()) +``` + +## Streaming responses + +We provide support for streaming responses using Server Side Events (SSE). + +```python +from openai import OpenAI + +client = OpenAI() + +stream = client.responses.create( + model="gpt-5.2", + input="Write a one-sentence bedtime story about a unicorn.", + stream=True, +) + +for event in stream: + print(event) +``` + +The async client uses the exact same interface. + +```python +import asyncio +from openai import AsyncOpenAI + +client = AsyncOpenAI() + + +async def main(): + stream = await client.responses.create( + model="gpt-5.2", + input="Write a one-sentence bedtime story about a unicorn.", + stream=True, + ) + + async for event in stream: + print(event) + + +asyncio.run(main()) +``` + +## Realtime API + +The Realtime API enables you to build low-latency, multi-modal conversational experiences. It currently supports text and audio as both input and output, as well as [function calling](https://platform.openai.com/docs/guides/function-calling) through a WebSocket connection. + +Under the hood the SDK uses the [`websockets`](https://websockets.readthedocs.io/en/stable/) library to manage connections. + +The Realtime API works through a combination of client-sent events and server-sent events. Clients can send events to do things like update session configuration or send text and audio inputs. Server events confirm when audio responses have completed, or when a text response from the model has been received. A full event reference can be found [here](https://platform.openai.com/docs/api-reference/realtime-client-events) and a guide can be found [here](https://platform.openai.com/docs/guides/realtime). + +Basic text based example: + +```py +import asyncio +from openai import AsyncOpenAI + +async def main(): + client = AsyncOpenAI() + + async with client.realtime.connect(model="gpt-realtime") as connection: + await connection.session.update( + session={"type": "realtime", "output_modalities": ["text"]} + ) + + await connection.conversation.item.create( + item={ + "type": "message", + "role": "user", + "content": [{"type": "input_text", "text": "Say hello!"}], + } + ) + await connection.response.create() + + async for event in connection: + if event.type == "response.output_text.delta": + print(event.delta, flush=True, end="") + + elif event.type == "response.output_text.done": + print() + + elif event.type == "response.done": + break + +asyncio.run(main()) +``` + +However the real magic of the Realtime API is handling audio inputs / outputs, see this example [TUI script](https://github.com/openai/openai-python/blob/main/examples/realtime/push_to_talk_app.py) for a fully fledged example. + +### Realtime error handling + +Whenever an error occurs, the Realtime API will send an [`error` event](https://platform.openai.com/docs/guides/realtime-model-capabilities#error-handling) and the connection will stay open and remain usable. This means you need to handle it yourself, as _no errors are raised directly_ by the SDK when an `error` event comes in. + +```py +client = AsyncOpenAI() + +async with client.realtime.connect(model="gpt-realtime") as connection: + ... + async for event in connection: + if event.type == 'error': + print(event.error.type) + print(event.error.code) + print(event.error.event_id) + print(event.error.message) +``` + +## Using types + +Nested request parameters are [TypedDicts](https://docs.python.org/3/library/typing.html#typing.TypedDict). Responses are [Pydantic models](https://docs.pydantic.dev) which also provide helper methods for things like: + +- Serializing back into JSON, `model.to_json()` +- Converting to a dictionary, `model.to_dict()` + +Typed requests and responses provide autocomplete and documentation within your editor. If you would like to see type errors in VS Code to help catch bugs earlier, set `python.analysis.typeCheckingMode` to `basic`. + +## Pagination + +List methods in the OpenAI API are paginated. + +This library provides auto-paginating iterators with each list response, so you do not have to request successive pages manually: + +```python +from openai import OpenAI + +client = OpenAI() + +all_jobs = [] +# Automatically fetches more pages as needed. +for job in client.fine_tuning.jobs.list( + limit=20, +): + # Do something with job here + all_jobs.append(job) +print(all_jobs) +``` + +Or, asynchronously: + +```python +import asyncio +from openai import AsyncOpenAI + +client = AsyncOpenAI() + + +async def main() -> None: + all_jobs = [] + # Iterate through items across all pages, issuing requests as needed. + async for job in client.fine_tuning.jobs.list( + limit=20, + ): + all_jobs.append(job) + print(all_jobs) + + +asyncio.run(main()) +``` + +Alternatively, you can use the `.has_next_page()`, `.next_page_info()`, or `.get_next_page()` methods for more granular control working with pages: + +```python +first_page = await client.fine_tuning.jobs.list( + limit=20, +) +if first_page.has_next_page(): + print(f"will fetch next page using these details: {first_page.next_page_info()}") + next_page = await first_page.get_next_page() + print(f"number of items we just fetched: {len(next_page.data)}") + +# Remove `await` for non-async usage. +``` + +Or just work directly with the returned data: + +```python +first_page = await client.fine_tuning.jobs.list( + limit=20, +) + +print(f"next page cursor: {first_page.after}") # => "next page cursor: ..." +for job in first_page.data: + print(job.id) + +# Remove `await` for non-async usage. +``` + +## Nested params + +Nested parameters are dictionaries, typed using `TypedDict`, for example: + +```python +from openai import OpenAI + +client = OpenAI() + +response = client.chat.responses.create( + input=[ + { + "role": "user", + "content": "How much ?", + } + ], + model="gpt-5.2", + response_format={"type": "json_object"}, +) +``` + +## File uploads + +Request parameters that correspond to file uploads can be passed as `bytes`, or a [`PathLike`](https://docs.python.org/3/library/os.html#os.PathLike) instance or a tuple of `(filename, contents, media type)`. + +```python +from pathlib import Path +from openai import OpenAI + +client = OpenAI() + +client.files.create( + file=Path("input.jsonl"), + purpose="fine-tune", +) +``` + +The async client uses the exact same interface. If you pass a [`PathLike`](https://docs.python.org/3/library/os.html#os.PathLike) instance, the file contents will be read asynchronously automatically. + +## Webhook Verification + +Verifying webhook signatures is _optional but encouraged_. + +For more information about webhooks, see [the API docs](https://platform.openai.com/docs/guides/webhooks). + +### Parsing webhook payloads + +For most use cases, you will likely want to verify the webhook and parse the payload at the same time. To achieve this, we provide the method `client.webhooks.unwrap()`, which parses a webhook request and verifies that it was sent by OpenAI. This method will raise an error if the signature is invalid. + +Note that the `body` parameter must be the raw JSON string sent from the server (do not parse it first). The `.unwrap()` method will parse this JSON for you into an event object after verifying the webhook was sent from OpenAI. + +```python +from openai import OpenAI +from flask import Flask, request + +app = Flask(__name__) +client = OpenAI() # OPENAI_WEBHOOK_SECRET environment variable is used by default + + +@app.route("/webhook", methods=["POST"]) +def webhook(): + request_body = request.get_data(as_text=True) + + try: + event = client.webhooks.unwrap(request_body, request.headers) + + if event.type == "response.completed": + print("Response completed:", event.data) + elif event.type == "response.failed": + print("Response failed:", event.data) + else: + print("Unhandled event type:", event.type) + + return "ok" + except Exception as e: + print("Invalid signature:", e) + return "Invalid signature", 400 + + +if __name__ == "__main__": + app.run(port=8000) +``` + +### Verifying webhook payloads directly + +In some cases, you may want to verify the webhook separately from parsing the payload. If you prefer to handle these steps separately, we provide the method `client.webhooks.verify_signature()` to _only verify_ the signature of a webhook request. Like `.unwrap()`, this method will raise an error if the signature is invalid. + +Note that the `body` parameter must be the raw JSON string sent from the server (do not parse it first). You will then need to parse the body after verifying the signature. + +```python +import json +from openai import OpenAI +from flask import Flask, request + +app = Flask(__name__) +client = OpenAI() # OPENAI_WEBHOOK_SECRET environment variable is used by default + + +@app.route("/webhook", methods=["POST"]) +def webhook(): + request_body = request.get_data(as_text=True) + + try: + client.webhooks.verify_signature(request_body, request.headers) + + # Parse the body after verification + event = json.loads(request_body) + print("Verified event:", event) + + return "ok" + except Exception as e: + print("Invalid signature:", e) + return "Invalid signature", 400 + + +if __name__ == "__main__": + app.run(port=8000) +``` + +## Handling errors + +When the library is unable to connect to the API (for example, due to network connection problems or a timeout), a subclass of `openai.APIConnectionError` is raised. + +When the API returns a non-success status code (that is, 4xx or 5xx +response), a subclass of `openai.APIStatusError` is raised, containing `status_code` and `response` properties. + +All errors inherit from `openai.APIError`. + +```python +import openai +from openai import OpenAI + +client = OpenAI() + +try: + client.fine_tuning.jobs.create( + model="gpt-4o", + training_file="file-abc123", + ) +except openai.APIConnectionError as e: + print("The server could not be reached") + print(e.__cause__) # an underlying Exception, likely raised within httpx. +except openai.RateLimitError as e: + print("A 429 status code was received; we should back off a bit.") +except openai.APIStatusError as e: + print("Another non-200-range status code was received") + print(e.status_code) + print(e.response) +``` + +Error codes are as follows: + +| Status Code | Error Type | +| ----------- | -------------------------- | +| 400 | `BadRequestError` | +| 401 | `AuthenticationError` | +| 403 | `PermissionDeniedError` | +| 404 | `NotFoundError` | +| 422 | `UnprocessableEntityError` | +| 429 | `RateLimitError` | +| >=500 | `InternalServerError` | +| N/A | `APIConnectionError` | + +## Request IDs + +> For more information on debugging requests, see [these docs](https://platform.openai.com/docs/api-reference/debugging-requests) + +All object responses in the SDK provide a `_request_id` property which is added from the `x-request-id` response header so that you can quickly log failing requests and report them back to OpenAI. + +```python +response = await client.responses.create( + model="gpt-5.2", + input="Say 'this is a test'.", +) +print(response._request_id) # req_123 +``` + +Note that unlike other properties that use an `_` prefix, the `_request_id` property +_is_ public. Unless documented otherwise, _all_ other `_` prefix properties, +methods and modules are _private_. + +> [!IMPORTANT] +> If you need to access request IDs for failed requests you must catch the `APIStatusError` exception + +```python +import openai + +try: + completion = await client.chat.completions.create( + messages=[{"role": "user", "content": "Say this is a test"}], model="gpt-5.2" + ) +except openai.APIStatusError as exc: + print(exc.request_id) # req_123 + raise exc +``` + +## Retries + +Certain errors are automatically retried 2 times by default, with a short exponential backoff. +Connection errors (for example, due to a network connectivity problem), 408 Request Timeout, 409 Conflict, +429 Rate Limit, and >=500 Internal errors are all retried by default. + +You can use the `max_retries` option to configure or disable retry settings: + +```python +from openai import OpenAI + +# Configure the default for all requests: +client = OpenAI( + # default is 2 + max_retries=0, +) + +# Or, configure per-request: +client.with_options(max_retries=5).chat.completions.create( + messages=[ + { + "role": "user", + "content": "How can I get the name of the current day in JavaScript?", + } + ], + model="gpt-5.2", +) +``` + +## Timeouts + +By default requests time out after 10 minutes. You can configure this with a `timeout` option, +which accepts a float or an [`httpx.Timeout`](https://www.python-httpx.org/advanced/timeouts/#fine-tuning-the-configuration) object: + +```python +from openai import OpenAI + +# Configure the default for all requests: +client = OpenAI( + # 20 seconds (default is 10 minutes) + timeout=20.0, +) + +# More granular control: +client = OpenAI( + timeout=httpx.Timeout(60.0, read=5.0, write=10.0, connect=2.0), +) + +# Override per-request: +client.with_options(timeout=5.0).chat.completions.create( + messages=[ + { + "role": "user", + "content": "How can I list all files in a directory using Python?", + } + ], + model="gpt-5.2", +) +``` + +On timeout, an `APITimeoutError` is thrown. + +Note that requests that time out are [retried twice by default](https://github.com/openai/openai-python/tree/main/#retries). + +## Advanced + +### Logging + +We use the standard library [`logging`](https://docs.python.org/3/library/logging.html) module. + +You can enable logging by setting the environment variable `OPENAI_LOG` to `info`. + +```shell +$ export OPENAI_LOG=info +``` + +Or to `debug` for more verbose logging. + +### How to tell whether `None` means `null` or missing + +In an API response, a field may be explicitly `null`, or missing entirely; in either case, its value is `None` in this library. You can differentiate the two cases with `.model_fields_set`: + +```py +if response.my_field is None: + if 'my_field' not in response.model_fields_set: + print('Got json like {}, without a "my_field" key present at all.') + else: + print('Got json like {"my_field": null}.') +``` + +### Accessing raw response data (e.g. headers) + +The "raw" Response object can be accessed by prefixing `.with_raw_response.` to any HTTP method call, e.g., + +```py +from openai import OpenAI + +client = OpenAI() +response = client.chat.completions.with_raw_response.create( + messages=[{ + "role": "user", + "content": "Say this is a test", + }], + model="gpt-5.2", +) +print(response.headers.get('X-My-Header')) + +completion = response.parse() # get the object that `chat.completions.create()` would have returned +print(completion) +``` + +These methods return a [`LegacyAPIResponse`](https://github.com/openai/openai-python/tree/main/src/openai/_legacy_response.py) object. This is a legacy class as we're changing it slightly in the next major version. + +For the sync client this will mostly be the same with the exception +of `content` & `text` will be methods instead of properties. In the +async client, all methods will be async. + +A migration script will be provided & the migration in general should +be smooth. + +#### `.with_streaming_response` + +The above interface eagerly reads the full response body when you make the request, which may not always be what you want. + +To stream the response body, use `.with_streaming_response` instead, which requires a context manager and only reads the response body once you call `.read()`, `.text()`, `.json()`, `.iter_bytes()`, `.iter_text()`, `.iter_lines()` or `.parse()`. In the async client, these are async methods. + +As such, `.with_streaming_response` methods return a different [`APIResponse`](https://github.com/openai/openai-python/tree/main/src/openai/_response.py) object, and the async client returns an [`AsyncAPIResponse`](https://github.com/openai/openai-python/tree/main/src/openai/_response.py) object. + +```python +with client.chat.completions.with_streaming_response.create( + messages=[ + { + "role": "user", + "content": "Say this is a test", + } + ], + model="gpt-5.2", +) as response: + print(response.headers.get("X-My-Header")) + + for line in response.iter_lines(): + print(line) +``` + +The context manager is required so that the response will reliably be closed. + +### Making custom/undocumented requests + +This library is typed for convenient access to the documented API. + +If you need to access undocumented endpoints, params, or response properties, the library can still be used. + +#### Undocumented endpoints + +To make requests to undocumented endpoints, you can make requests using `client.get`, `client.post`, and other +http verbs. Options on the client will be respected (such as retries) when making this request. + +```py +import httpx + +response = client.post( + "/foo", + cast_to=httpx.Response, + body={"my_param": True}, +) + +print(response.headers.get("x-foo")) +``` + +#### Undocumented request params + +If you want to explicitly send an extra param, you can do so with the `extra_query`, `extra_body`, and `extra_headers` request +options. + +#### Undocumented response properties + +To access undocumented response properties, you can access the extra fields like `response.unknown_prop`. You +can also get all the extra fields on the Pydantic model as a dict with +[`response.model_extra`](https://docs.pydantic.dev/latest/api/base_model/#pydantic.BaseModel.model_extra). + +### Configuring the HTTP client + +You can directly override the [httpx client](https://www.python-httpx.org/api/#client) to customize it for your use case, including: + +- Support for [proxies](https://www.python-httpx.org/advanced/proxies/) +- Custom [transports](https://www.python-httpx.org/advanced/transports/) +- Additional [advanced](https://www.python-httpx.org/advanced/clients/) functionality + +```python +import httpx +from openai import OpenAI, DefaultHttpxClient + +client = OpenAI( + # Or use the `OPENAI_BASE_URL` env var + base_url="http://my.test.server.example.com:8083/v1", + http_client=DefaultHttpxClient( + proxy="http://my.test.proxy.example.com", + transport=httpx.HTTPTransport(local_address="0.0.0.0"), + ), +) +``` + +You can also customize the client on a per-request basis by using `with_options()`: + +```python +client.with_options(http_client=DefaultHttpxClient(...)) +``` + +### Managing HTTP resources + +By default the library closes underlying HTTP connections whenever the client is [garbage collected](https://docs.python.org/3/reference/datamodel.html#object.__del__). You can manually close the client using the `.close()` method if desired, or with a context manager that closes when exiting. + +```py +from openai import OpenAI + +with OpenAI() as client: + # make requests here + ... + +# HTTP client is now closed +``` + +## Microsoft Azure OpenAI + +To use this library with [Azure OpenAI](https://learn.microsoft.com/azure/ai-services/openai/overview), use the `AzureOpenAI` +class instead of the `OpenAI` class. + +> [!IMPORTANT] +> The Azure API shape differs from the core API shape which means that the static types for responses / params +> won't always be correct. + +```py +from openai import AzureOpenAI + +# gets the API Key from environment variable AZURE_OPENAI_API_KEY +client = AzureOpenAI( + # https://learn.microsoft.com/azure/ai-services/openai/reference#rest-api-versioning + api_version="2023-07-01-preview", + # https://learn.microsoft.com/azure/cognitive-services/openai/how-to/create-resource?pivots=web-portal#create-a-resource + azure_endpoint="https://example-endpoint.openai.azure.com", +) + +completion = client.chat.completions.create( + model="deployment-name", # e.g. gpt-35-instant + messages=[ + { + "role": "user", + "content": "How do I output all files in a directory using Python?", + }, + ], +) +print(completion.to_json()) +``` + +In addition to the options provided in the base `OpenAI` client, the following options are provided: + +- `azure_endpoint` (or the `AZURE_OPENAI_ENDPOINT` environment variable) +- `azure_deployment` +- `api_version` (or the `OPENAI_API_VERSION` environment variable) +- `azure_ad_token` (or the `AZURE_OPENAI_AD_TOKEN` environment variable) +- `azure_ad_token_provider` + +An example of using the client with Microsoft Entra ID (formerly known as Azure Active Directory) can be found [here](https://github.com/openai/openai-python/blob/main/examples/azure_ad.py). + +## Versioning + +This package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backwards-incompatible changes may be released as minor versions: + +1. Changes that only affect static types, without breaking runtime behavior. +2. Changes to library internals which are technically public but not intended or documented for external use. _(Please open a GitHub issue to let us know if you are relying on such internals.)_ +3. Changes that we do not expect to impact the vast majority of users in practice. + +We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience. + +We are keen for your feedback; please open an [issue](https://www.github.com/openai/openai-python/issues) with questions, bugs, or suggestions. + +### Determining the installed version + +If you've upgraded to the latest version but aren't seeing any new features you were expecting then your python environment is likely still using an older version. + +You can determine the version that is being used at runtime with: + +```py +import openai +print(openai.__version__) +``` + +## Requirements + +Python 3.9 or higher. + +## Contributing + +See [the contributing documentation](https://github.com/openai/openai-python/tree/main/./CONTRIBUTING.md). diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/openai-2.36.0.dist-info/RECORD b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/openai-2.36.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..ef44d7ff8d305342b11000d57cd97a1cbe50970f --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/openai-2.36.0.dist-info/RECORD @@ -0,0 +1,2433 @@ +openai-2.36.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +openai-2.36.0.dist-info/METADATA,sha256=ggDe-GmuiHv58EzM1lVk8uPSEdJP1ekJ-hKE1C2cnns,31834 +openai-2.36.0.dist-info/RECORD,, +openai-2.36.0.dist-info/WHEEL,sha256=C2FUgwZgiLbznR-k0b_5k3Ai_1aASOXDss3lzCUsUug,87 +openai-2.36.0.dist-info/licenses/LICENSE,sha256=Y263152pu21RWks_1BeqJmees88WOW3atLxV-nTmFuQ,11336 +openai/__init__.py,sha256=eeBkJtEYTmIc5Do1b03Isx6XXWMyk-LGU29A-wlV9bg,11950 +openai/__pycache__/__init__.cpython-310.pyc,, +openai/__pycache__/_base_client.cpython-310.pyc,, +openai/__pycache__/_client.cpython-310.pyc,, +openai/__pycache__/_compat.cpython-310.pyc,, +openai/__pycache__/_constants.cpython-310.pyc,, +openai/__pycache__/_event_handler.cpython-310.pyc,, +openai/__pycache__/_exceptions.cpython-310.pyc,, +openai/__pycache__/_files.cpython-310.pyc,, +openai/__pycache__/_legacy_response.cpython-310.pyc,, +openai/__pycache__/_models.cpython-310.pyc,, +openai/__pycache__/_module_client.cpython-310.pyc,, +openai/__pycache__/_qs.cpython-310.pyc,, +openai/__pycache__/_resource.cpython-310.pyc,, +openai/__pycache__/_response.cpython-310.pyc,, +openai/__pycache__/_send_queue.cpython-310.pyc,, +openai/__pycache__/_streaming.cpython-310.pyc,, +openai/__pycache__/_types.cpython-310.pyc,, +openai/__pycache__/_version.cpython-310.pyc,, +openai/__pycache__/pagination.cpython-310.pyc,, +openai/__pycache__/version.cpython-310.pyc,, +openai/_base_client.py,sha256=3oo3d9NTEiokLdc3a_gUZo11V2dbgf42uZTT9lpZjIM,76759 +openai/_client.py,sha256=JjAs6pUzqhybHOQzcIl4-g4XBKHY0ybrDt5eA0f-h2o,63584 +openai/_compat.py,sha256=yntbvsd6TcP1hjcLEpqhozb1JW5pZWy81caHiE8rv50,7213 +openai/_constants.py,sha256=WmCwgT4tGmFsSrltb26f3bM8ftUyFYkzh32Ny5yl-So,467 +openai/_event_handler.py,sha256=3EBf9NdrT2RdffU7EZwIjeknvVN6GzhpakMd39r9xmw,2858 +openai/_exceptions.py,sha256=2AMs2jrMGKdThuZB_htX-EUSqiEHJD_kfoyMWx6vEZs,6462 +openai/_extras/__init__.py,sha256=sainrYWujCxIyL24wNpKfMVr-ZyBPlnSZfqXcg2S6Xg,165 +openai/_extras/__pycache__/__init__.cpython-310.pyc,, +openai/_extras/__pycache__/_common.cpython-310.pyc,, +openai/_extras/__pycache__/numpy_proxy.cpython-310.pyc,, +openai/_extras/__pycache__/pandas_proxy.cpython-310.pyc,, +openai/_extras/__pycache__/sounddevice_proxy.cpython-310.pyc,, +openai/_extras/_common.py,sha256=NWWtgbdJsO3hQGQxaXGfVk0LjeIE5AFZ8VS_795hhMc,364 +openai/_extras/numpy_proxy.py,sha256=LyTZkKDdnjz0h1SKLsphrhmXyUsJ_xEUhTFMrCf7k7g,805 +openai/_extras/pandas_proxy.py,sha256=NCEt1Dqwc_0H85YdsWPDE3lPDJtYnBT8G-gJE_BCeEc,637 +openai/_extras/sounddevice_proxy.py,sha256=xDoE21YGu13dSAJJkiOM9Qdb7uOIv5zskaJRX6xciEg,725 +openai/_files.py,sha256=KSk9Arqtx0KIFG3wQlzki3OWVdrMLyVctR4vpNX_h4M,5519 +openai/_legacy_response.py,sha256=PosLYYYw_SAIfQEJUDP9V1HuFkgyXk0bsqi2NMzU0e4,16374 +openai/_models.py,sha256=HGSlLfV9nDRfr8DSaPB8jKmBjuBHHNHoDuNwYz8lVTE,34180 +openai/_module_client.py,sha256=smHSK2bCMAP1PSqh8RHlBsmRPInPIfJY4qe-ME19o54,5478 +openai/_qs.py,sha256=ZSfQv6arGBBoWlcy60zK1zmPE2Ije0i8kzKdnoxWUjU,4833 +openai/_resource.py,sha256=IQihFzFLhGOiGSlT2dO1ESWSTg2XypgbtAldtGdTOqU,1100 +openai/_response.py,sha256=bwodmRyBD5CiLox8d9fjZM3rAgzHBBOxqTuRJnARTUU,29647 +openai/_send_queue.py,sha256=Hfi_EPBRCpQL-KFIt3Wz88YltXkNrPEaUJHUDzRICLw,3034 +openai/_streaming.py,sha256=MXjrtyH0_zzabUeVILor3c3HCW4qmYJ8agvBUP5EU0o,14608 +openai/_types.py,sha256=OUfMgVGaI5CttEeYvgIVyGBouZoxjpXvDiIVI1MjJY8,7913 +openai/_utils/__init__.py,sha256=-N2uXyxcgXx-UFmwiyPhsCI1cIu_e2duStUVTEXixKk,2473 +openai/_utils/__pycache__/__init__.cpython-310.pyc,, +openai/_utils/__pycache__/_compat.cpython-310.pyc,, +openai/_utils/__pycache__/_datetime_parse.cpython-310.pyc,, +openai/_utils/__pycache__/_json.cpython-310.pyc,, +openai/_utils/__pycache__/_logs.cpython-310.pyc,, +openai/_utils/__pycache__/_path.cpython-310.pyc,, +openai/_utils/__pycache__/_proxy.cpython-310.pyc,, +openai/_utils/__pycache__/_reflection.cpython-310.pyc,, +openai/_utils/__pycache__/_resources_proxy.cpython-310.pyc,, +openai/_utils/__pycache__/_streams.cpython-310.pyc,, +openai/_utils/__pycache__/_sync.cpython-310.pyc,, +openai/_utils/__pycache__/_transform.cpython-310.pyc,, +openai/_utils/__pycache__/_typing.cpython-310.pyc,, +openai/_utils/__pycache__/_utils.cpython-310.pyc,, +openai/_utils/_compat.py,sha256=33246eDcl3pwL6kWsEhVuT4Akrd8gZEW9LPTm465ohk,1231 +openai/_utils/_datetime_parse.py,sha256=bABTs0Bc6rabdFvnIwXjEhWL15TcRgWZ_6XGTqN8xUk,4204 +openai/_utils/_json.py,sha256=bl95uuIWwgSfXX-gP1trK_lDAPwJujYfJ05Cxo2SEC4,962 +openai/_utils/_logs.py,sha256=IC5iwPflwelNpJEpWsvK3up-pol5hR8k_VL9fSukk_Y,1351 +openai/_utils/_path.py,sha256=Dk294levuJXP5e4m20YRDDZFPl7zegXvc9Kb3dUCwJI,4701 +openai/_utils/_proxy.py,sha256=aglnj2yBTDyGX9Akk2crZHrl10oqRmceUy2Zp008XEs,1975 +openai/_utils/_reflection.py,sha256=aTXm-W0Kww4PJo5LPkUnQ92N-2UvrK1-D67cJVBlIgw,1426 +openai/_utils/_resources_proxy.py,sha256=AHHZCOgv-2CRqB4B52dB7ySlE5q6QCWj0bsTqNmzikw,589 +openai/_utils/_streams.py,sha256=SMC90diFFecpEg_zgDRVbdR3hSEIgVVij4taD-noMLM,289 +openai/_utils/_sync.py,sha256=HBnZkkBnzxtwOZe0212C4EyoRvxhTVtTrLFDz2_xVCg,1589 +openai/_utils/_transform.py,sha256=hzILp2ijV9J7D-uoEDmadtyCmzMK6DprJP8IlwEg0ZY,15999 +openai/_utils/_typing.py,sha256=N_5PPuFNsaygbtA_npZd98SVN1LQQvFTKL6bkWPBZGU,4786 +openai/_utils/_utils.py,sha256=OpfJAOb8_pKw7td8E1iYujp6GnBoElkpQl1IOMRRcxE,13526 +openai/_version.py,sha256=6IWdi5ajHARvIrSQyXh1DMV3jpxZ4TtR-rBIihNGZCc,159 +openai/auth/__init__.py,sha256=knjdQxuABpOVWQEdvM7KWzZi0jvTUnpRjC25S59VqFA,630 +openai/auth/__pycache__/__init__.cpython-310.pyc,, +openai/auth/__pycache__/_workload.cpython-310.pyc,, +openai/auth/_workload.py,sha256=rr4qa7yEZVmGx8NbykasHR4Lc1s7Zbd7NMjqQSqaPhs,12825 +openai/helpers/__init__.py,sha256=F0x_Pguq1XC2KXZYbfxUG-G_FxJ3mlsi7HaFZ1x-g9A,130 +openai/helpers/__pycache__/__init__.cpython-310.pyc,, +openai/helpers/__pycache__/local_audio_player.cpython-310.pyc,, +openai/helpers/__pycache__/microphone.cpython-310.pyc,, +openai/helpers/local_audio_player.py,sha256=7MWwt1BYEh579z1brnQ2mUEB0Ble4UoGMHDKusOfZJQ,5852 +openai/helpers/microphone.py,sha256=6tIHWZGpRA5XvUoer-nPBvHbrmxK7CWx3_Ta-qp1H54,3341 +openai/lib/.keep,sha256=wuNrz-5SXo3jJaJOJgz4vFHM41YH_g20F5cRQo0vLes,224 +openai/lib/__init__.py,sha256=BMTfMnlbugMgDA1STDIAlx4bI4t4l_8bQmJxd0th0n8,126 +openai/lib/__pycache__/__init__.cpython-310.pyc,, +openai/lib/__pycache__/_old_api.cpython-310.pyc,, +openai/lib/__pycache__/_pydantic.cpython-310.pyc,, +openai/lib/__pycache__/_realtime.cpython-310.pyc,, +openai/lib/__pycache__/_tools.cpython-310.pyc,, +openai/lib/__pycache__/_validators.cpython-310.pyc,, +openai/lib/__pycache__/azure.cpython-310.pyc,, +openai/lib/_old_api.py,sha256=XZnXBrEKuTd70iJirj5mGW35fZoqruJobbBTq6bvg10,1947 +openai/lib/_parsing/__init__.py,sha256=_tOYASbvaNQLj6jf6knPP3_mRFRr1vGJXudxf0npVFo,483 +openai/lib/_parsing/__pycache__/__init__.cpython-310.pyc,, +openai/lib/_parsing/__pycache__/_completions.cpython-310.pyc,, +openai/lib/_parsing/__pycache__/_responses.cpython-310.pyc,, +openai/lib/_parsing/_completions.py,sha256=2Rj_Kujo39aOrE36vV1QmRTjAQpLQFr5lhasYdmTo58,10000 +openai/lib/_parsing/_responses.py,sha256=VMqXRy2COxrSUq28FTWMEIE1b7EmWT8kn3Au1xPa-7k,6430 +openai/lib/_pydantic.py,sha256=Cf0vGwuWdNEuIUg8WNREjWRGApMObgl8DjdLU4f5jAc,5623 +openai/lib/_realtime.py,sha256=4ani2j6lt21SXrC6Ep_GQnLA7eEOo4UoZ8I1JAuqtn0,3980 +openai/lib/_tools.py,sha256=Dc4U2TXKvfAvVUvDS30SDeftrwgGM2vZ85t5ojLHiEg,1969 +openai/lib/_validators.py,sha256=cXJXFuaAl7jeJcYHXXnFa4NHGtHs-_zt3Zs1VVCmQo4,35288 +openai/lib/azure.py,sha256=2TsuxVV-oQdBgDFsYLq5w2vKLpWx6SGNDAQy2BbwsPQ,30522 +openai/lib/streaming/__init__.py,sha256=kD3LpjsqU7caDQDhB-YjTUl9qqbb5sPnGGSI2yQYC70,379 +openai/lib/streaming/__pycache__/__init__.cpython-310.pyc,, +openai/lib/streaming/__pycache__/_assistants.cpython-310.pyc,, +openai/lib/streaming/__pycache__/_deltas.cpython-310.pyc,, +openai/lib/streaming/_assistants.py,sha256=LUWSinmYopQIkQ5xSg73b6BWbkRkQS5JvX62w_V9xSw,40692 +openai/lib/streaming/_deltas.py,sha256=I7B_AznXZwlBmE8Puau7ayTQUx6hMIEVE8FYTQm2fjs,2502 +openai/lib/streaming/chat/__init__.py,sha256=7krL_atOvvpQkY_byWSglSfDsMs5hdoxHmz4Ulq7lcc,1305 +openai/lib/streaming/chat/__pycache__/__init__.cpython-310.pyc,, +openai/lib/streaming/chat/__pycache__/_completions.cpython-310.pyc,, +openai/lib/streaming/chat/__pycache__/_events.cpython-310.pyc,, +openai/lib/streaming/chat/__pycache__/_types.cpython-310.pyc,, +openai/lib/streaming/chat/_completions.py,sha256=3xwZSiM7uA37GqxpSgTNWQbe_inCecJkHYRt4qqNKqQ,30704 +openai/lib/streaming/chat/_events.py,sha256=lstVmM6YR2Cs9drikzrY9JCZn9Nbfym0aKIPtNpxL6w,2618 +openai/lib/streaming/chat/_types.py,sha256=-SYVBNhGkOUoJ-8dotxpCRqPJpfyOQ8hwR2_HrsQCRI,739 +openai/lib/streaming/responses/__init__.py,sha256=MwE1Oc3OIiXjtuRFsuP_k5Ra8pNiqKpc1GZum-8ZRJM,543 +openai/lib/streaming/responses/__pycache__/__init__.cpython-310.pyc,, +openai/lib/streaming/responses/__pycache__/_events.cpython-310.pyc,, +openai/lib/streaming/responses/__pycache__/_responses.cpython-310.pyc,, +openai/lib/streaming/responses/__pycache__/_types.cpython-310.pyc,, +openai/lib/streaming/responses/_events.py,sha256=3UWmeYgg23E3XTkYVlrpXJPnhBM2kmQFoXh3WiT9CrE,5576 +openai/lib/streaming/responses/_responses.py,sha256=Myeo4so-aMFrzEyNCjX0ypYWTWvY5uDelhe2ygC93lY,13614 +openai/lib/streaming/responses/_types.py,sha256=msq1KWj3e3BLn7NKu5j2kzHgj9kShuoitgXEyTmQxus,276 +openai/pagination.py,sha256=VfLIgDsK_PfOcsaJXN6__-LDHJGnMt6mLwcma0lJB1E,6217 +openai/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +openai/resources/__init__.py,sha256=f3QwnZjV9WUZtZwN5u9IMr_6rwxk9vuCNwidaF5EYoE,6762 +openai/resources/__pycache__/__init__.cpython-310.pyc,, +openai/resources/__pycache__/batches.cpython-310.pyc,, +openai/resources/__pycache__/completions.cpython-310.pyc,, +openai/resources/__pycache__/embeddings.cpython-310.pyc,, +openai/resources/__pycache__/files.cpython-310.pyc,, +openai/resources/__pycache__/images.cpython-310.pyc,, +openai/resources/__pycache__/models.cpython-310.pyc,, +openai/resources/__pycache__/moderations.cpython-310.pyc,, +openai/resources/__pycache__/videos.cpython-310.pyc,, +openai/resources/admin/__init__.py,sha256=8UIjC8y1FuZiV8BkpFwHQkyD8uyC3Np8VcrKlR-T0ds,875 +openai/resources/admin/__pycache__/__init__.cpython-310.pyc,, +openai/resources/admin/__pycache__/admin.cpython-310.pyc,, +openai/resources/admin/admin.py,sha256=CciQSqoxW3zm-GhR2ORqfLE4uSm0D6MoMWdqh3JIQm8,3430 +openai/resources/admin/organization/__init__.py,sha256=LuvnwYMuzxI4Qakg_MgMk7TjELob5okXfR6OmFuW_ZU,3918 +openai/resources/admin/organization/__pycache__/__init__.cpython-310.pyc,, +openai/resources/admin/organization/__pycache__/admin_api_keys.cpython-310.pyc,, +openai/resources/admin/organization/__pycache__/audit_logs.cpython-310.pyc,, +openai/resources/admin/organization/__pycache__/certificates.cpython-310.pyc,, +openai/resources/admin/organization/__pycache__/invites.cpython-310.pyc,, +openai/resources/admin/organization/__pycache__/organization.cpython-310.pyc,, +openai/resources/admin/organization/__pycache__/roles.cpython-310.pyc,, +openai/resources/admin/organization/__pycache__/usage.cpython-310.pyc,, +openai/resources/admin/organization/admin_api_keys.py,sha256=AwJSro3ukYFC94yscwr9qC9r6KZltnkhlx64mVMP_ag,17815 +openai/resources/admin/organization/audit_logs.py,sha256=YQjYJkKFnGXBKKDmAsbqLQ9ulEY2R1LuGO7VhncAZUU,15678 +openai/resources/admin/organization/certificates.py,sha256=a2sDatgYNK7-AyXf2MYafK2GFQPCDeYj0YheyrL_nCo,32619 +openai/resources/admin/organization/groups/__init__.py,sha256=-GCrdtwZbcpFGJH6vK-db1_51vV0btP4bv3QgM-BRrk,1138 +openai/resources/admin/organization/groups/__pycache__/__init__.cpython-310.pyc,, +openai/resources/admin/organization/groups/__pycache__/groups.cpython-310.pyc,, +openai/resources/admin/organization/groups/__pycache__/roles.cpython-310.pyc,, +openai/resources/admin/organization/groups/__pycache__/users.cpython-310.pyc,, +openai/resources/admin/organization/groups/groups.py,sha256=eFNkLvlt6_jln_hxTPhl3iJomLUf7a2cJup2mZU91Wc,19926 +openai/resources/admin/organization/groups/roles.py,sha256=1zM73nPtCRW23ZKHYdCUes6B4JRgYRnmhs-SmVeE6pk,15504 +openai/resources/admin/organization/groups/users.py,sha256=3ZvVyuflanRyiRaSnZAh7tIoiqIRQGUH3J5Xa0riePM,15441 +openai/resources/admin/organization/invites.py,sha256=mYtTSALRMKbx2_Y_l5OrHvkXsAJfc7nIw-Lbkf9EAdU,18917 +openai/resources/admin/organization/organization.py,sha256=BSi07Jb-hJbxtGWZscZhS1-Fv1keD8f9-TclycGKzgw,12083 +openai/resources/admin/organization/projects/__init__.py,sha256=9oe1BpFHAhBJFU3tgzkbMeuyTIrNyrH-ii2ZmHdayVw,3197 +openai/resources/admin/organization/projects/__pycache__/__init__.cpython-310.pyc,, +openai/resources/admin/organization/projects/__pycache__/api_keys.cpython-310.pyc,, +openai/resources/admin/organization/projects/__pycache__/certificates.cpython-310.pyc,, +openai/resources/admin/organization/projects/__pycache__/projects.cpython-310.pyc,, +openai/resources/admin/organization/projects/__pycache__/rate_limits.cpython-310.pyc,, +openai/resources/admin/organization/projects/__pycache__/roles.cpython-310.pyc,, +openai/resources/admin/organization/projects/__pycache__/service_accounts.cpython-310.pyc,, +openai/resources/admin/organization/projects/api_keys.py,sha256=2N-MdPs44mwOYsr-TMbfd7cYFfS2WhPiuVOQmw2T6dI,16130 +openai/resources/admin/organization/projects/certificates.py,sha256=7ESFsJlgOourS9svOKYF9yr7PSd1PfdHakqRYF1YNKs,17803 +openai/resources/admin/organization/projects/groups/__init__.py,sha256=-G0gLwk7AhZn_Fi4NTBs6lQd1x7K2HIYexV5I5sNtRM,797 +openai/resources/admin/organization/projects/groups/__pycache__/__init__.cpython-310.pyc,, +openai/resources/admin/organization/projects/groups/__pycache__/groups.cpython-310.pyc,, +openai/resources/admin/organization/projects/groups/__pycache__/roles.cpython-310.pyc,, +openai/resources/admin/organization/projects/groups/groups.py,sha256=c1BJc-Vjgndh9GtAJc1tMa4g45ALDkYDJdZaGPhlgvE,16733 +openai/resources/admin/organization/projects/groups/roles.py,sha256=rI9_NBBURRxZDbnMYbI7BBGAPlOJInslNncZloyAETc,16738 +openai/resources/admin/organization/projects/projects.py,sha256=615bgMLQQkNmHn6OO1I8iPuXj2XtLUiUuUNxTsLHjZ0,31467 +openai/resources/admin/organization/projects/rate_limits.py,sha256=HeHXJ8TZTa1KLafYLcE7U7E0qvCseo7N9BP4W86SZVQ,16309 +openai/resources/admin/organization/projects/roles.py,sha256=-W3_VHYaNdeyDD_rgwVQs5WBT67P-LLpQJZxQxJ8npg,20676 +openai/resources/admin/organization/projects/service_accounts.py,sha256=RlMbmdZcM3q1uOZb4-sh-J54JY_qxnPODzj2XQG1DIM,21230 +openai/resources/admin/organization/projects/users/__init__.py,sha256=c-k5ER-COJnUzgFHOz6GFHvxVuETGrN46pt1nP9GKxE,784 +openai/resources/admin/organization/projects/users/__pycache__/__init__.cpython-310.pyc,, +openai/resources/admin/organization/projects/users/__pycache__/roles.cpython-310.pyc,, +openai/resources/admin/organization/projects/users/__pycache__/users.cpython-310.pyc,, +openai/resources/admin/organization/projects/users/roles.py,sha256=vGkjF8VK3tTslAHBJWjNP9RJzA6v1vr3PXHWOX6qej4,16680 +openai/resources/admin/organization/projects/users/users.py,sha256=rFm5axgLLlApal414PaWxfsTukM1NtUMHxZmH2B9ZPE,25236 +openai/resources/admin/organization/roles.py,sha256=Snj-pLGW_ja0zRWaC7lJOOWpcVr9czJvU5tIhrqE4s4,19127 +openai/resources/admin/organization/usage.py,sha256=xC8Nea8RUlFuse-cj2u_SA-QT_WQh3ZKukAx-UsIDkI,70344 +openai/resources/admin/organization/users/__init__.py,sha256=c-k5ER-COJnUzgFHOz6GFHvxVuETGrN46pt1nP9GKxE,784 +openai/resources/admin/organization/users/__pycache__/__init__.cpython-310.pyc,, +openai/resources/admin/organization/users/__pycache__/roles.cpython-310.pyc,, +openai/resources/admin/organization/users/__pycache__/users.cpython-310.pyc,, +openai/resources/admin/organization/users/roles.py,sha256=DdGMncPkwpAWduZoVAgpxOm_Ug7juM11lIiNtABwT-w,15446 +openai/resources/admin/organization/users/users.py,sha256=G1Ty9e67ii9upCQ38-nKyyQS4vgTUsQXNsD_9iWOI04,20213 +openai/resources/audio/__init__.py,sha256=YM7FHvPKVlj_v6EIgfpUQsb6q4hS2hVQ3gfkgic0sP0,1687 +openai/resources/audio/__pycache__/__init__.cpython-310.pyc,, +openai/resources/audio/__pycache__/audio.cpython-310.pyc,, +openai/resources/audio/__pycache__/speech.cpython-310.pyc,, +openai/resources/audio/__pycache__/transcriptions.cpython-310.pyc,, +openai/resources/audio/__pycache__/translations.cpython-310.pyc,, +openai/resources/audio/audio.py,sha256=_UsPa7eB21y0wAyxtgrsisEVP7xKDCh_sFtYtHO7Wfo,6481 +openai/resources/audio/speech.py,sha256=aUvyWcoqT5PKykIvS9AkWkUpemM3S8bYx2W3NkimOGw,10764 +openai/resources/audio/transcriptions.py,sha256=zXggfe_tHwSlKxq2ZnQh3kgEjMngYGdBETjfdiogYxA,53407 +openai/resources/audio/translations.py,sha256=C8cZRvbNn6EjAX7Nh2GZvC977zAFarN08LaAVtV9TW0,15883 +openai/resources/batches.py,sha256=XahMGrEctq-gBJnDq0piaUwEwa6uqIwqesvig-jhl1k,22407 +openai/resources/beta/__init__.py,sha256=chKjkpkqNxO1Dbl9OsCJNXVC1AbDcvTrvfvvAIh5B5I,1570 +openai/resources/beta/__pycache__/__init__.cpython-310.pyc,, +openai/resources/beta/__pycache__/assistants.cpython-310.pyc,, +openai/resources/beta/__pycache__/beta.cpython-310.pyc,, +openai/resources/beta/assistants.py,sha256=coyuvUX9SlZ0W1EcUNQ9IKZgQvjR1ONdcGSfNF4B-e0,51855 +openai/resources/beta/beta.py,sha256=r1556zGWoMhrap6FSh1biLDhw70cy5xw5uuhrTn7FrQ,6529 +openai/resources/beta/chatkit/__init__.py,sha256=lJAQpi-JogtnSAlOegSae6WfCfgRLMd8rpPBuT9_2FE,1216 +openai/resources/beta/chatkit/__pycache__/__init__.cpython-310.pyc,, +openai/resources/beta/chatkit/__pycache__/chatkit.cpython-310.pyc,, +openai/resources/beta/chatkit/__pycache__/sessions.cpython-310.pyc,, +openai/resources/beta/chatkit/__pycache__/threads.cpython-310.pyc,, +openai/resources/beta/chatkit/chatkit.py,sha256=CleguF_80H_gAsyX_tLoGxFTD7YItZPshRAZ2QAqfzY,4333 +openai/resources/beta/chatkit/sessions.py,sha256=cLCixf_I7mc1jJioii0wBtUSKsI2GmpBjMIHaSEt19I,12564 +openai/resources/beta/chatkit/threads.py,sha256=lrfO9ly5Wp5Rg1Vr8RNW5OZJB136NUQmqj-z5hb4yL8,21132 +openai/resources/beta/realtime/__init__.py,sha256=dOXRjPiDqRJXIFoGKSVjzKh3IwSXnLbwHx4ND5OdnVs,1412 +openai/resources/beta/realtime/__pycache__/__init__.cpython-310.pyc,, +openai/resources/beta/realtime/__pycache__/realtime.cpython-310.pyc,, +openai/resources/beta/realtime/__pycache__/sessions.cpython-310.pyc,, +openai/resources/beta/realtime/__pycache__/transcription_sessions.cpython-310.pyc,, +openai/resources/beta/realtime/realtime.py,sha256=tuiq_0PdFmC2p-LNOfQNrVuDEMlLAHKEgeAsPsHLUHU,43694 +openai/resources/beta/realtime/sessions.py,sha256=EQva_qI71CgS35qkK9TGxuibviHwUQ6VzErIzunP4gU,22098 +openai/resources/beta/realtime/transcription_sessions.py,sha256=uTDGEat50lojdD0N8slnZu2RVzMP96rlicpDp4tpl34,14124 +openai/resources/beta/threads/__init__.py,sha256=fQ_qdUVSfouVS5h47DlTb5mamChT4K-v-siPuuAB6do,1177 +openai/resources/beta/threads/__pycache__/__init__.cpython-310.pyc,, +openai/resources/beta/threads/__pycache__/messages.cpython-310.pyc,, +openai/resources/beta/threads/__pycache__/threads.cpython-310.pyc,, +openai/resources/beta/threads/messages.py,sha256=M-nsKbr4vXnp13Ojrb7sZrbBijc4bHom86pOzELgRE4,32297 +openai/resources/beta/threads/runs/__init__.py,sha256=2FfDaqwmJJCd-IVpY_CrzWcFvw0KFyQ3cm5jnTfI-DQ,771 +openai/resources/beta/threads/runs/__pycache__/__init__.cpython-310.pyc,, +openai/resources/beta/threads/runs/__pycache__/runs.cpython-310.pyc,, +openai/resources/beta/threads/runs/__pycache__/steps.cpython-310.pyc,, +openai/resources/beta/threads/runs/runs.py,sha256=0eE7tUOG950zIEv8kyuYd2GyUh6ItP-mde-JIcRTmUQ,158496 +openai/resources/beta/threads/runs/steps.py,sha256=mqy622hCVca02BPLxTtCKd-gwXVlnRUkA17ki4ZXMcY,17708 +openai/resources/beta/threads/threads.py,sha256=fBUTc9_bbSlLjas5IK_Dgx8g9nEG7mo3AE1Hu6sfexU,100068 +openai/resources/chat/__init__.py,sha256=8Q9ODRo1wIpFa34VaNwuaWFmxqFxagDtUhIAkQNvxEU,849 +openai/resources/chat/__pycache__/__init__.cpython-310.pyc,, +openai/resources/chat/__pycache__/chat.cpython-310.pyc,, +openai/resources/chat/chat.py,sha256=NdZ-a8Y_lVk7rCBkgGGpWK6JybfpyYTFyJWpcBO9zSE,4072 +openai/resources/chat/completions/__init__.py,sha256=KOi8blzNyHWD7nKgcoW3CxZ4428IcNVP0gCU74HySf8,901 +openai/resources/chat/completions/__pycache__/__init__.cpython-310.pyc,, +openai/resources/chat/completions/__pycache__/completions.cpython-310.pyc,, +openai/resources/chat/completions/__pycache__/messages.cpython-310.pyc,, +openai/resources/chat/completions/completions.py,sha256=WyvqS3w1dxKEZ8mPEJzckflqcLUpcHy_IpSgj29Y7KY,168005 +openai/resources/chat/completions/messages.py,sha256=oosbCESgK4uRX50wDjaYEP1g2-ndixfx3bqdXsy9TJ8,8421 +openai/resources/completions.py,sha256=p0WPy9LowZ3t8nh6aoiv7iJrtUi2QZB5Hmj9U1jKA6Y,60399 +openai/resources/containers/__init__.py,sha256=7VzY-TFwG3x5D_kUCs_iAQaaCKAswt1Jk70KpmnU8Do,849 +openai/resources/containers/__pycache__/__init__.cpython-310.pyc,, +openai/resources/containers/__pycache__/containers.cpython-310.pyc,, +openai/resources/containers/containers.py,sha256=zfshsrQwj-a6kq2qLh3aijOvjbTHfVHc2TqkrC8XTLs,21553 +openai/resources/containers/files/__init__.py,sha256=nDhg0wY7eHRMO-xOErno0mV0Ya_ynlmKAp-4a3nj-us,810 +openai/resources/containers/files/__pycache__/__init__.cpython-310.pyc,, +openai/resources/containers/files/__pycache__/content.cpython-310.pyc,, +openai/resources/containers/files/__pycache__/files.cpython-310.pyc,, +openai/resources/containers/files/content.py,sha256=3ilAFMK5x20lrQqB6XD_LRJZeltgK70Rtpr_wj67new,6898 +openai/resources/containers/files/files.py,sha256=z-Uz6r3xfJob8kpleQpB22ysTt83OTRV8b7UfxHvXAY,22280 +openai/resources/conversations/__init__.py,sha256=Uslb4pakT8pQJGQ29CvoiN-SvN2AgMum-TeIDyYTzQE,888 +openai/resources/conversations/__pycache__/__init__.cpython-310.pyc,, +openai/resources/conversations/__pycache__/conversations.cpython-310.pyc,, +openai/resources/conversations/__pycache__/items.cpython-310.pyc,, +openai/resources/conversations/api.md,sha256=aja7OOHpcYKeuoZV_lBWBT950-4tdVVOf_M2GwRXv3k,3047 +openai/resources/conversations/conversations.py,sha256=CFlGBh1C4MJZXOmBjeSwnPinT-zp4sn2AbaXEfKYziI,20690 +openai/resources/conversations/items.py,sha256=nbKBKITLx40pbDGF4NTx9xbM_5TMiAtANb0kOQrcYnY,25166 +openai/resources/embeddings.py,sha256=uuiEbMjBLjUi8d5zgQjt_cyWIXofIO3w5syZ6o2LtkU,12744 +openai/resources/evals/__init__.py,sha256=DXhYb6mCKKY2bDdS3s4raH1SvwPUyaBFvdHgPEbwRWY,771 +openai/resources/evals/__pycache__/__init__.cpython-310.pyc,, +openai/resources/evals/__pycache__/evals.cpython-310.pyc,, +openai/resources/evals/evals.py,sha256=T-AwQGN3IzqnGBEkqKafx2sxyo59_JrK8nbQRItrF-w,27443 +openai/resources/evals/runs/__init__.py,sha256=7EtKZ43tGlmAOYyDdyFXy80tk2X8AmXb5taTWRRXBXE,850 +openai/resources/evals/runs/__pycache__/__init__.cpython-310.pyc,, +openai/resources/evals/runs/__pycache__/output_items.cpython-310.pyc,, +openai/resources/evals/runs/__pycache__/runs.cpython-310.pyc,, +openai/resources/evals/runs/output_items.py,sha256=CW1t1C-wZlAtvScUXxz_c1VrBgmADpM07lsjBa7G7hc,13351 +openai/resources/evals/runs/runs.py,sha256=E41MfZGL5FeDJ2hAC1aV5fhExgKbyTPCCWNVxEECnr0,26112 +openai/resources/files.py,sha256=aKM9X63c4J_uk7z4CHGDG_MJgtpnbCkCB4w5spwdU6o,33464 +openai/resources/fine_tuning/__init__.py,sha256=RQPC5QfqE-ByhRQbJK-j7ooUrkBO9s9bKt5xkzOL8ls,1597 +openai/resources/fine_tuning/__pycache__/__init__.cpython-310.pyc,, +openai/resources/fine_tuning/__pycache__/fine_tuning.cpython-310.pyc,, +openai/resources/fine_tuning/alpha/__init__.py,sha256=QKAYZscx1Fw3GLD8cVdZAYG9L_i6MnPGeifn8GgcztU,810 +openai/resources/fine_tuning/alpha/__pycache__/__init__.cpython-310.pyc,, +openai/resources/fine_tuning/alpha/__pycache__/alpha.cpython-310.pyc,, +openai/resources/fine_tuning/alpha/__pycache__/graders.cpython-310.pyc,, +openai/resources/fine_tuning/alpha/alpha.py,sha256=V_dcJVRnCQllhZTHf62OchMII2lUiuHMy11Ie6ll_ls,3802 +openai/resources/fine_tuning/alpha/graders.py,sha256=1lwIgxo9uG8wZoHaGnL1DXnHHC5vYcElflJK4kFJRBc,11316 +openai/resources/fine_tuning/checkpoints/__init__.py,sha256=rvsbut5FCQNAr-VjvL-14GFT3Tld49FlFuBJDpfxBug,940 +openai/resources/fine_tuning/checkpoints/__pycache__/__init__.cpython-310.pyc,, +openai/resources/fine_tuning/checkpoints/__pycache__/checkpoints.cpython-310.pyc,, +openai/resources/fine_tuning/checkpoints/__pycache__/permissions.cpython-310.pyc,, +openai/resources/fine_tuning/checkpoints/checkpoints.py,sha256=v6s1-CcegIffX3KL2hY44iTzQR_xVAvwysqd1Xd2kYo,4134 +openai/resources/fine_tuning/checkpoints/permissions.py,sha256=vbllgLfKMHUgBydznWgMpRTfPLlhChme6s_COIPSQz4,25301 +openai/resources/fine_tuning/fine_tuning.py,sha256=7uHBPvrGerktNx4578OwE2e-XkeFlGzWvSu1MlfThQs,5938 +openai/resources/fine_tuning/jobs/__init__.py,sha256=_smlrwijZOCcsDWqKnofLxQM2QLucZzXgboL9zJBPHw,849 +openai/resources/fine_tuning/jobs/__pycache__/__init__.cpython-310.pyc,, +openai/resources/fine_tuning/jobs/__pycache__/checkpoints.cpython-310.pyc,, +openai/resources/fine_tuning/jobs/__pycache__/jobs.cpython-310.pyc,, +openai/resources/fine_tuning/jobs/checkpoints.py,sha256=6PO4Jwo01HhcDoQl-zsLrBKFsYTeK-Nee5G6on5MnK0,7829 +openai/resources/fine_tuning/jobs/jobs.py,sha256=s0jr2b4Snu5v0qUFnfMfoSEaC8dLtFLUpWR-qvPNN4I,39438 +openai/resources/images.py,sha256=9NLnm03g9iE304xBcWA-_CP9HKAucEgzFAKMf3FGVE0,110774 +openai/resources/models.py,sha256=upf3u234j-VCNgeM44T8IN4a69SVmYrmTl_B3QTVCMQ,12097 +openai/resources/moderations.py,sha256=PZNPTKEkuOn6yTHwY45f95IThbH08GlxlpqwCWX8o64,8212 +openai/resources/realtime/__init__.py,sha256=5v7pt2NQKz1j-X1z4bTqupmE3G8O5_G4PYCyw3F3-eo,1269 +openai/resources/realtime/__pycache__/__init__.cpython-310.pyc,, +openai/resources/realtime/__pycache__/calls.cpython-310.pyc,, +openai/resources/realtime/__pycache__/client_secrets.cpython-310.pyc,, +openai/resources/realtime/__pycache__/realtime.cpython-310.pyc,, +openai/resources/realtime/api.md,sha256=0Mee6FhUhts4U8sGRvPPoRSsb-gabFdcQ_e4bxvbvZo,5891 +openai/resources/realtime/calls.py,sha256=N7-Goo3pC41DYn6aWPgQiuVlNIJ3ciWaV1BAB2L5uUw,35986 +openai/resources/realtime/client_secrets.py,sha256=puDk9hTPAuYkiwNHL9w-EfKsZLcvH9uCDHGovgZ0H-c,9456 +openai/resources/realtime/realtime.py,sha256=wqhNu2F0rjh3tKneP9dlTnYOASN7yZzHkM4210qpZvA,68447 +openai/resources/responses/__init__.py,sha256=9LkjQomOIh6B5Qg1HbdCgjMRoCzIBzyRaYNyt3moA38,1322 +openai/resources/responses/__pycache__/__init__.cpython-310.pyc,, +openai/resources/responses/__pycache__/input_items.cpython-310.pyc,, +openai/resources/responses/__pycache__/input_tokens.cpython-310.pyc,, +openai/resources/responses/__pycache__/responses.cpython-310.pyc,, +openai/resources/responses/api.md,sha256=4LSDAG15GoAUaSDgw7JzxPR15dDRC3zn7skIfLGFZ64,6744 +openai/resources/responses/input_items.py,sha256=JxNZFU-767ZCAeF5O3uLuzo0W0poEOUHYpodtg08UNo,8963 +openai/resources/responses/input_tokens.py,sha256=gwYrun_6hu7wkpQ_IFCEUFP2HALy1VPlCtc_qIcf2Z4,14660 +openai/resources/responses/responses.py,sha256=T54wsPRqtmbCfTBBWpfaaYyvCMZs5wL8hHb0ikwr8bk,224621 +openai/resources/skills/__init__.py,sha256=O6Jcz0qgE-Eyn0cH2qF2y1uSHK7Wne3N2v8UR30aB7Y,1203 +openai/resources/skills/__pycache__/__init__.cpython-310.pyc,, +openai/resources/skills/__pycache__/content.cpython-310.pyc,, +openai/resources/skills/__pycache__/skills.cpython-310.pyc,, +openai/resources/skills/content.py,sha256=XvPT-VJofrIloj8_LAvTbpQ8YIC1wae6cuHoPuHauPU,6425 +openai/resources/skills/skills.py,sha256=nFYyJdBXjY7xe09MrL-KXO0E0R5vWSvY07QjDlQjjWo,23823 +openai/resources/skills/versions/__init__.py,sha256=22fGWbCZg6G2wQzG9qdq0h2wWccFCurCYdSMnXhYWBg,849 +openai/resources/skills/versions/__pycache__/__init__.cpython-310.pyc,, +openai/resources/skills/versions/__pycache__/content.cpython-310.pyc,, +openai/resources/skills/versions/__pycache__/versions.cpython-310.pyc,, +openai/resources/skills/versions/content.py,sha256=5Dotn4yXRU65UBuxfwEDnze7FTwjquAgndfkAO89jCA,6882 +openai/resources/skills/versions/versions.py,sha256=rwdMosPqx8Vo1GqKplzOF7UO9miUFZghDoev2E-37qg,21416 +openai/resources/uploads/__init__.py,sha256=HmY3WQgvUI2bN3CjfWHWQOk7UUC6Ozna97_lHhrrRSA,810 +openai/resources/uploads/__pycache__/__init__.cpython-310.pyc,, +openai/resources/uploads/__pycache__/parts.cpython-310.pyc,, +openai/resources/uploads/__pycache__/uploads.cpython-310.pyc,, +openai/resources/uploads/parts.py,sha256=ad-loYvmuZ_W8zblmzaXeKMSnt63YmOqI3vGxzrV-n4,8582 +openai/resources/uploads/uploads.py,sha256=PdAGyjQwucRxtFPF7Hl645yU4D-usDTkbLLw6cjZXgo,27246 +openai/resources/vector_stores/__init__.py,sha256=11Xn1vhgndWiI0defJHv31vmbtbDgh2GwZT3gX8GgHk,1296 +openai/resources/vector_stores/__pycache__/__init__.cpython-310.pyc,, +openai/resources/vector_stores/__pycache__/file_batches.cpython-310.pyc,, +openai/resources/vector_stores/__pycache__/files.cpython-310.pyc,, +openai/resources/vector_stores/__pycache__/vector_stores.cpython-310.pyc,, +openai/resources/vector_stores/file_batches.py,sha256=r1pdaoB8a9PXk_kGyZRx2Xm41Kiq4kZQ4X7LossznzY,38075 +openai/resources/vector_stores/files.py,sha256=4v7YbHfig0dlh2ySiKRorwKSI05WjbOJl32pEXthKPg,43454 +openai/resources/vector_stores/vector_stores.py,sha256=AAYqMM0-LRihXpbT3h4CP3QTkHNuGKVqgFi1_tg-CUQ,36908 +openai/resources/videos.py,sha256=GwcvN22G0jmSof64SZOpB1Tb4y86wSSb_yZ-zfwp0YU,51986 +openai/resources/webhooks/__init__.py,sha256=B6Ku4PhIQmf4VSVnpeTqqPXdrB0bgL5UklqrJVcPyj4,292 +openai/resources/webhooks/__pycache__/__init__.cpython-310.pyc,, +openai/resources/webhooks/__pycache__/webhooks.cpython-310.pyc,, +openai/resources/webhooks/api.md,sha256=QBUWdJuTiC_NNhbr7U4Zmvc09x6CX5PEiyhTizX2yQU,610 +openai/resources/webhooks/webhooks.py,sha256=-KsfTOl5QrwLfwzwTmLQOg6DKSzbh9sVdaSyVgYYoNA,7826 +openai/types/__init__.py,sha256=HtyE6McpyhlCmoe7u8JxRT06UEM1FUYi8oW3YPcuiuA,8757 +openai/types/__pycache__/__init__.cpython-310.pyc,, +openai/types/__pycache__/audio_model.cpython-310.pyc,, +openai/types/__pycache__/audio_response_format.cpython-310.pyc,, +openai/types/__pycache__/auto_file_chunking_strategy_param.cpython-310.pyc,, +openai/types/__pycache__/batch.cpython-310.pyc,, +openai/types/__pycache__/batch_create_params.cpython-310.pyc,, +openai/types/__pycache__/batch_error.cpython-310.pyc,, +openai/types/__pycache__/batch_list_params.cpython-310.pyc,, +openai/types/__pycache__/batch_request_counts.cpython-310.pyc,, +openai/types/__pycache__/batch_usage.cpython-310.pyc,, +openai/types/__pycache__/chat_model.cpython-310.pyc,, +openai/types/__pycache__/completion.cpython-310.pyc,, +openai/types/__pycache__/completion_choice.cpython-310.pyc,, +openai/types/__pycache__/completion_create_params.cpython-310.pyc,, +openai/types/__pycache__/completion_usage.cpython-310.pyc,, +openai/types/__pycache__/container_create_params.cpython-310.pyc,, +openai/types/__pycache__/container_create_response.cpython-310.pyc,, +openai/types/__pycache__/container_list_params.cpython-310.pyc,, +openai/types/__pycache__/container_list_response.cpython-310.pyc,, +openai/types/__pycache__/container_retrieve_response.cpython-310.pyc,, +openai/types/__pycache__/create_embedding_response.cpython-310.pyc,, +openai/types/__pycache__/deleted_skill.cpython-310.pyc,, +openai/types/__pycache__/embedding.cpython-310.pyc,, +openai/types/__pycache__/embedding_create_params.cpython-310.pyc,, +openai/types/__pycache__/embedding_model.cpython-310.pyc,, +openai/types/__pycache__/eval_create_params.cpython-310.pyc,, +openai/types/__pycache__/eval_create_response.cpython-310.pyc,, +openai/types/__pycache__/eval_custom_data_source_config.cpython-310.pyc,, +openai/types/__pycache__/eval_delete_response.cpython-310.pyc,, +openai/types/__pycache__/eval_list_params.cpython-310.pyc,, +openai/types/__pycache__/eval_list_response.cpython-310.pyc,, +openai/types/__pycache__/eval_retrieve_response.cpython-310.pyc,, +openai/types/__pycache__/eval_stored_completions_data_source_config.cpython-310.pyc,, +openai/types/__pycache__/eval_update_params.cpython-310.pyc,, +openai/types/__pycache__/eval_update_response.cpython-310.pyc,, +openai/types/__pycache__/file_chunking_strategy.cpython-310.pyc,, +openai/types/__pycache__/file_chunking_strategy_param.cpython-310.pyc,, +openai/types/__pycache__/file_content.cpython-310.pyc,, +openai/types/__pycache__/file_create_params.cpython-310.pyc,, +openai/types/__pycache__/file_deleted.cpython-310.pyc,, +openai/types/__pycache__/file_list_params.cpython-310.pyc,, +openai/types/__pycache__/file_object.cpython-310.pyc,, +openai/types/__pycache__/file_purpose.cpython-310.pyc,, +openai/types/__pycache__/image.cpython-310.pyc,, +openai/types/__pycache__/image_create_variation_params.cpython-310.pyc,, +openai/types/__pycache__/image_edit_completed_event.cpython-310.pyc,, +openai/types/__pycache__/image_edit_params.cpython-310.pyc,, +openai/types/__pycache__/image_edit_partial_image_event.cpython-310.pyc,, +openai/types/__pycache__/image_edit_stream_event.cpython-310.pyc,, +openai/types/__pycache__/image_gen_completed_event.cpython-310.pyc,, +openai/types/__pycache__/image_gen_partial_image_event.cpython-310.pyc,, +openai/types/__pycache__/image_gen_stream_event.cpython-310.pyc,, +openai/types/__pycache__/image_generate_params.cpython-310.pyc,, +openai/types/__pycache__/image_input_reference_param.cpython-310.pyc,, +openai/types/__pycache__/image_model.cpython-310.pyc,, +openai/types/__pycache__/images_response.cpython-310.pyc,, +openai/types/__pycache__/model.cpython-310.pyc,, +openai/types/__pycache__/model_deleted.cpython-310.pyc,, +openai/types/__pycache__/moderation.cpython-310.pyc,, +openai/types/__pycache__/moderation_create_params.cpython-310.pyc,, +openai/types/__pycache__/moderation_create_response.cpython-310.pyc,, +openai/types/__pycache__/moderation_image_url_input_param.cpython-310.pyc,, +openai/types/__pycache__/moderation_model.cpython-310.pyc,, +openai/types/__pycache__/moderation_multi_modal_input_param.cpython-310.pyc,, +openai/types/__pycache__/moderation_text_input_param.cpython-310.pyc,, +openai/types/__pycache__/other_file_chunking_strategy_object.cpython-310.pyc,, +openai/types/__pycache__/skill.cpython-310.pyc,, +openai/types/__pycache__/skill_create_params.cpython-310.pyc,, +openai/types/__pycache__/skill_list.cpython-310.pyc,, +openai/types/__pycache__/skill_list_params.cpython-310.pyc,, +openai/types/__pycache__/skill_update_params.cpython-310.pyc,, +openai/types/__pycache__/static_file_chunking_strategy.cpython-310.pyc,, +openai/types/__pycache__/static_file_chunking_strategy_object.cpython-310.pyc,, +openai/types/__pycache__/static_file_chunking_strategy_object_param.cpython-310.pyc,, +openai/types/__pycache__/static_file_chunking_strategy_param.cpython-310.pyc,, +openai/types/__pycache__/upload.cpython-310.pyc,, +openai/types/__pycache__/upload_complete_params.cpython-310.pyc,, +openai/types/__pycache__/upload_create_params.cpython-310.pyc,, +openai/types/__pycache__/vector_store.cpython-310.pyc,, +openai/types/__pycache__/vector_store_create_params.cpython-310.pyc,, +openai/types/__pycache__/vector_store_deleted.cpython-310.pyc,, +openai/types/__pycache__/vector_store_list_params.cpython-310.pyc,, +openai/types/__pycache__/vector_store_search_params.cpython-310.pyc,, +openai/types/__pycache__/vector_store_search_response.cpython-310.pyc,, +openai/types/__pycache__/vector_store_update_params.cpython-310.pyc,, +openai/types/__pycache__/video.cpython-310.pyc,, +openai/types/__pycache__/video_create_character_params.cpython-310.pyc,, +openai/types/__pycache__/video_create_character_response.cpython-310.pyc,, +openai/types/__pycache__/video_create_error.cpython-310.pyc,, +openai/types/__pycache__/video_create_params.cpython-310.pyc,, +openai/types/__pycache__/video_delete_response.cpython-310.pyc,, +openai/types/__pycache__/video_download_content_params.cpython-310.pyc,, +openai/types/__pycache__/video_edit_params.cpython-310.pyc,, +openai/types/__pycache__/video_extend_params.cpython-310.pyc,, +openai/types/__pycache__/video_get_character_response.cpython-310.pyc,, +openai/types/__pycache__/video_list_params.cpython-310.pyc,, +openai/types/__pycache__/video_model.cpython-310.pyc,, +openai/types/__pycache__/video_model_param.cpython-310.pyc,, +openai/types/__pycache__/video_remix_params.cpython-310.pyc,, +openai/types/__pycache__/video_seconds.cpython-310.pyc,, +openai/types/__pycache__/video_size.cpython-310.pyc,, +openai/types/__pycache__/websocket_connection_options.cpython-310.pyc,, +openai/types/__pycache__/websocket_reconnection.cpython-310.pyc,, +openai/types/admin/__init__.py,sha256=OKfJYcKb4NObdiRObqJV_dOyDQ8feXekDUge2o_4pXQ,122 +openai/types/admin/__pycache__/__init__.cpython-310.pyc,, +openai/types/admin/organization/__init__.py,sha256=r_8es2doXEc22dwXaWQ94S_FDrE3HfS4WgfvJavASxg,4941 +openai/types/admin/organization/__pycache__/__init__.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/admin_api_key.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/admin_api_key_create_params.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/admin_api_key_create_response.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/admin_api_key_delete_response.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/admin_api_key_list_params.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/audit_log_list_params.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/audit_log_list_response.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/certificate.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/certificate_activate_params.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/certificate_activate_response.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/certificate_create_params.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/certificate_deactivate_params.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/certificate_deactivate_response.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/certificate_delete_response.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/certificate_list_params.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/certificate_list_response.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/certificate_retrieve_params.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/certificate_update_params.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/group.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/group_create_params.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/group_delete_response.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/group_list_params.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/group_update_params.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/group_update_response.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/invite.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/invite_create_params.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/invite_delete_response.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/invite_list_params.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/organization_user.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/project.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/project_create_params.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/project_list_params.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/project_update_params.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/role.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/role_create_params.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/role_delete_response.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/role_list_params.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/role_update_params.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/usage_audio_speeches_params.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/usage_audio_speeches_response.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/usage_audio_transcriptions_params.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/usage_audio_transcriptions_response.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/usage_code_interpreter_sessions_params.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/usage_code_interpreter_sessions_response.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/usage_completions_params.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/usage_completions_response.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/usage_costs_params.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/usage_costs_response.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/usage_embeddings_params.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/usage_embeddings_response.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/usage_images_params.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/usage_images_response.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/usage_moderations_params.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/usage_moderations_response.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/usage_vector_stores_params.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/usage_vector_stores_response.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/user_delete_response.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/user_list_params.cpython-310.pyc,, +openai/types/admin/organization/__pycache__/user_update_params.cpython-310.pyc,, +openai/types/admin/organization/admin_api_key.py,sha256=f9t47-aX5KifCffV5PjoC2H5vN_hu-noCfjpKsKxsso,1385 +openai/types/admin/organization/admin_api_key_create_params.py,sha256=cufK_hmH8N1Fv8AWiPWGj4s9dE4Yu_65cooral3GFC0,293 +openai/types/admin/organization/admin_api_key_create_response.py,sha256=gWuqQR7aBdaahDB5w5RnNRDYI52ABEHCJ7T-FJKyS-U,349 +openai/types/admin/organization/admin_api_key_delete_response.py,sha256=bK8bSRQt9jLatCRyPK3CMNZugAkF9wVIsexi2iucJAM,337 +openai/types/admin/organization/admin_api_key_list_params.py,sha256=7rDl-CBge-ejfFT3Tx3tAXyIboMLK77GVhV6n5MNyNA,559 +openai/types/admin/organization/audit_log_list_params.py,sha256=sWXIfPUEx2TWNO5kbvF9pM6KEjPziSQm2HxkoFN3i04,4366 +openai/types/admin/organization/audit_log_list_response.py,sha256=vPJ3dnTCsy6sE2-vnQtzYOKU1KHQeRQagR0jPbSVm0s,31342 +openai/types/admin/organization/certificate.py,sha256=hV4Q--8aN4-dHADFiZGS0gNILMKt1TsgU0ZvQWOophQ,1695 +openai/types/admin/organization/certificate_activate_params.py,sha256=Bd9a6SlRFo9ASkT0hCWdD7jKVwUu5Vt4J8XyxVLXFCw,363 +openai/types/admin/organization/certificate_activate_response.py,sha256=6pWVzqfqrKHk2dLRyrC2TSy7Cll1ZHfGAQSWLEXGmgU,1170 +openai/types/admin/organization/certificate_create_params.py,sha256=iUJSVD8HOr95pefP7Wy7slSLxbCcCAchr8kt8mHyIz8,410 +openai/types/admin/organization/certificate_deactivate_params.py,sha256=1nhrYamr9L5_3IGJVWH_ir6YAUCh_D9ADWIdj3uyHbQ,367 +openai/types/admin/organization/certificate_deactivate_response.py,sha256=VZiGr75Fo6q6Y8apbGmpJ03BYaCqM8L3TP3PgpGLQVw,1174 +openai/types/admin/organization/certificate_delete_response.py,sha256=Fv99yEDlAy6f14fBt0CGZj1Q8D18J-LPNpqt0HGwGpw,415 +openai/types/admin/organization/certificate_list_params.py,sha256=SxFt0MyHxAp1Zmp891v_aw2E8MoD0lPPTgDbDVGwaS0,897 +openai/types/admin/organization/certificate_list_response.py,sha256=gHfh1uGJPKzEwsPfATgozrB73pNh16Y05Sz_VrXhwzE,1162 +openai/types/admin/organization/certificate_retrieve_params.py,sha256=ocHCnsLN84DzSl9ftEGVaTgfWfa7ZL5NdG11fucyi8s,507 +openai/types/admin/organization/certificate_update_params.py,sha256=hNaT7bnn0tZ4zyPWLe0NSK9BaDwXs6EglMk20V9O9_A,320 +openai/types/admin/organization/group.py,sha256=SP93JeNHVvKzR8lk-JwQ3e5uAUzCAXglWJYaAImymv8,592 +openai/types/admin/organization/group_create_params.py,sha256=JsZAwApwETuEEoEz9GkSHb0QAYkBYpNyJUpo2G6GJWU,326 +openai/types/admin/organization/group_delete_response.py,sha256=rI4YisXh-_AYDoloNRPUaakRNPBJiQYdmSgACABkovU,487 +openai/types/admin/organization/group_list_params.py,sha256=ARkOTxDzyPDK2y9_g_jdKusPMJeulgvksMX_vQ7QVrE,813 +openai/types/admin/organization/group_update_params.py,sha256=5l9PdDerboanDfyzi9gjNDoJDFHzRJRNkDCykGCYVsk,323 +openai/types/admin/organization/group_update_response.py,sha256=3pbmVY9zVOYibUvynxtU2Qy-alUFl06l74wUxBVvgek,580 +openai/types/admin/organization/groups/__init__.py,sha256=1CTcn68Bt3k4foRo9awQjJAJlPPod2l58gufZmDOJbU,840 +openai/types/admin/organization/groups/__pycache__/__init__.cpython-310.pyc,, +openai/types/admin/organization/groups/__pycache__/organization_group_user.cpython-310.pyc,, +openai/types/admin/organization/groups/__pycache__/role_create_params.cpython-310.pyc,, +openai/types/admin/organization/groups/__pycache__/role_create_response.cpython-310.pyc,, +openai/types/admin/organization/groups/__pycache__/role_delete_response.cpython-310.pyc,, +openai/types/admin/organization/groups/__pycache__/role_list_params.cpython-310.pyc,, +openai/types/admin/organization/groups/__pycache__/role_list_response.cpython-310.pyc,, +openai/types/admin/organization/groups/__pycache__/user_create_params.cpython-310.pyc,, +openai/types/admin/organization/groups/__pycache__/user_create_response.cpython-310.pyc,, +openai/types/admin/organization/groups/__pycache__/user_delete_response.cpython-310.pyc,, +openai/types/admin/organization/groups/__pycache__/user_list_params.cpython-310.pyc,, +openai/types/admin/organization/groups/organization_group_user.py,sha256=AKHk9xTJF4_3qMTQ0LOM-Wt-npuKrvaazbMik51n0WM,514 +openai/types/admin/organization/groups/role_create_params.py,sha256=TCpbJtiJgb2i67nbachk6LqnqyuGDLd7ASjDyIuYJq0,326 +openai/types/admin/organization/groups/role_create_response.py,sha256=biOJ722ED9pj0PBRy_fap5Scz4QrYtzgutbrMADy1rc,1015 +openai/types/admin/organization/groups/role_delete_response.py,sha256=mKACovZTBnxcsQasWRIBDaNKyeAZk0rKVGT9Slen8bM,459 +openai/types/admin/organization/groups/role_list_params.py,sha256=ndIqUzHSR4Ii2DGJ4jSuknyZ0bMsmiH77izcEztoxs0,597 +openai/types/admin/organization/groups/role_list_response.py,sha256=F9Sq4qOYnNCOVacVDy9VdjV7JQLBQTbXIokKVcJLg2E,1212 +openai/types/admin/organization/groups/user_create_params.py,sha256=Pk6UBWud73Vw6Vtak_em4s7r9IsozSCg9NSWPbk9TuM,336 +openai/types/admin/organization/groups/user_create_response.py,sha256=soQl1enTEBw5Yka2uXYDjbgw0SF1sL6sPpkQr0Oif94,515 +openai/types/admin/organization/groups/user_delete_response.py,sha256=1TUh1GE0XIoixjiOpVpfqKGwaKxvqb0zjRR7krke4zk,463 +openai/types/admin/organization/groups/user_list_params.py,sha256=LUzVvCWdazyAtfk9vfR-E3IfIR8XvkEg917szI2mOA4,647 +openai/types/admin/organization/invite.py,sha256=Qr1wd_P_vyGI-m3TQMO3zebfVf3FGyUOMstX5vnJD_8,1334 +openai/types/admin/organization/invite_create_params.py,sha256=QOsmnXpfg_xxU0z-_bIBVeO-MnGXQv445kvGpcS_ld8,883 +openai/types/admin/organization/invite_delete_response.py,sha256=5exJKRlWyl-MQPWqVctHfBXAaWOSp4VzvMeBZ9Ivm40,393 +openai/types/admin/organization/invite_list_params.py,sha256=sNCsR15yf8uM_XrUSySyl0QIYHdgk-t9XhYlD1CddBQ,707 +openai/types/admin/organization/organization_user.py,sha256=cNFOmrIzoppJkxQs8vV379N4a5vo3JSYpIzTpKeZdQo,2428 +openai/types/admin/organization/project.py,sha256=ENOgpCQJUPXMxiAKZJBhLo-XRvY4_P-07K8CTEuxR50,955 +openai/types/admin/organization/project_create_params.py,sha256=VNlLohTRHBqEpIS56lu-hlrPmK4sq4F6R4MocpKlNYo,859 +openai/types/admin/organization/project_list_params.py,sha256=NnKSDA_3NJt1UOj4fcJDBQDxMltspPUmEjehqK99MV4,878 +openai/types/admin/organization/project_update_params.py,sha256=IrajXyzHsbGucJRoFW_HfHnBpDeAerceyuhEZF_z1Xc,536 +openai/types/admin/organization/projects/__init__.py,sha256=Nv06HuBq5Heu24-Anj0vGAc2M234OtO8XOhgJy4r1Zo,2578 +openai/types/admin/organization/projects/__pycache__/__init__.cpython-310.pyc,, +openai/types/admin/organization/projects/__pycache__/api_key_delete_response.cpython-310.pyc,, +openai/types/admin/organization/projects/__pycache__/api_key_list_params.cpython-310.pyc,, +openai/types/admin/organization/projects/__pycache__/certificate_activate_params.cpython-310.pyc,, +openai/types/admin/organization/projects/__pycache__/certificate_activate_response.cpython-310.pyc,, +openai/types/admin/organization/projects/__pycache__/certificate_deactivate_params.cpython-310.pyc,, +openai/types/admin/organization/projects/__pycache__/certificate_deactivate_response.cpython-310.pyc,, +openai/types/admin/organization/projects/__pycache__/certificate_list_params.cpython-310.pyc,, +openai/types/admin/organization/projects/__pycache__/certificate_list_response.cpython-310.pyc,, +openai/types/admin/organization/projects/__pycache__/group_create_params.cpython-310.pyc,, +openai/types/admin/organization/projects/__pycache__/group_delete_response.cpython-310.pyc,, +openai/types/admin/organization/projects/__pycache__/group_list_params.cpython-310.pyc,, +openai/types/admin/organization/projects/__pycache__/project_api_key.cpython-310.pyc,, +openai/types/admin/organization/projects/__pycache__/project_group.cpython-310.pyc,, +openai/types/admin/organization/projects/__pycache__/project_rate_limit.cpython-310.pyc,, +openai/types/admin/organization/projects/__pycache__/project_service_account.cpython-310.pyc,, +openai/types/admin/organization/projects/__pycache__/project_user.cpython-310.pyc,, +openai/types/admin/organization/projects/__pycache__/rate_limit_list_rate_limits_params.cpython-310.pyc,, +openai/types/admin/organization/projects/__pycache__/rate_limit_update_rate_limit_params.cpython-310.pyc,, +openai/types/admin/organization/projects/__pycache__/role_create_params.cpython-310.pyc,, +openai/types/admin/organization/projects/__pycache__/role_delete_response.cpython-310.pyc,, +openai/types/admin/organization/projects/__pycache__/role_list_params.cpython-310.pyc,, +openai/types/admin/organization/projects/__pycache__/role_update_params.cpython-310.pyc,, +openai/types/admin/organization/projects/__pycache__/service_account_create_params.cpython-310.pyc,, +openai/types/admin/organization/projects/__pycache__/service_account_create_response.cpython-310.pyc,, +openai/types/admin/organization/projects/__pycache__/service_account_delete_response.cpython-310.pyc,, +openai/types/admin/organization/projects/__pycache__/service_account_list_params.cpython-310.pyc,, +openai/types/admin/organization/projects/__pycache__/user_create_params.cpython-310.pyc,, +openai/types/admin/organization/projects/__pycache__/user_delete_response.cpython-310.pyc,, +openai/types/admin/organization/projects/__pycache__/user_list_params.cpython-310.pyc,, +openai/types/admin/organization/projects/__pycache__/user_update_params.cpython-310.pyc,, +openai/types/admin/organization/projects/api_key_delete_response.py,sha256=71chZq4cZgzGuWlGjOTOMnF0aFimORTbRiDouRKaSME,330 +openai/types/admin/organization/projects/api_key_list_params.py,sha256=bagWAjS3XwVr8o_C5V1iHy0Mz77cAeteUYEzC1I0v7Q,707 +openai/types/admin/organization/projects/certificate_activate_params.py,sha256=lDSri3b_on5cx0p0MLqfVVVlEX5QC0EFheWLSftjzJA,364 +openai/types/admin/organization/projects/certificate_activate_response.py,sha256=RmdBuc1ww-dPmHGwbvRPt2alCYWDaijRlt6tWTjRia8,1177 +openai/types/admin/organization/projects/certificate_deactivate_params.py,sha256=eivu_CTZn0K1JlMwh9fiyvnMbuwMnVLHunsXSjEQooQ,368 +openai/types/admin/organization/projects/certificate_deactivate_response.py,sha256=tGD1j-blBjKUj9hGuoEYTEqZSCXRcdL_NVx4HAkT0PU,1181 +openai/types/admin/organization/projects/certificate_list_params.py,sha256=SxFt0MyHxAp1Zmp891v_aw2E8MoD0lPPTgDbDVGwaS0,897 +openai/types/admin/organization/projects/certificate_list_response.py,sha256=5P098855PTpQfGeuBYdCh20jXFHM_1IqCSEiCNwYTuc,1169 +openai/types/admin/organization/projects/group_create_params.py,sha256=B9zWZylSWKMGipdplp88_-7KdSVwzIRV-4G59ovXbK0,431 +openai/types/admin/organization/projects/group_delete_response.py,sha256=5XeA62QdSEBnaUxlb5vRxHoq8YNdttBm4XYumxMLxvo,489 +openai/types/admin/organization/projects/group_list_params.py,sha256=b8yqt2uC2FDJbDbFdVmuGjqoAPXZf7XaT82MP04ukvI,572 +openai/types/admin/organization/projects/groups/__init__.py,sha256=hn4qHHw0j4I2l-EXMhbqHgn2P5UD9pcXXYwN3DXugNc,474 +openai/types/admin/organization/projects/groups/__pycache__/__init__.cpython-310.pyc,, +openai/types/admin/organization/projects/groups/__pycache__/role_create_params.cpython-310.pyc,, +openai/types/admin/organization/projects/groups/__pycache__/role_create_response.cpython-310.pyc,, +openai/types/admin/organization/projects/groups/__pycache__/role_delete_response.cpython-310.pyc,, +openai/types/admin/organization/projects/groups/__pycache__/role_list_params.cpython-310.pyc,, +openai/types/admin/organization/projects/groups/__pycache__/role_list_response.cpython-310.pyc,, +openai/types/admin/organization/projects/groups/role_create_params.py,sha256=8-454dHUz6x2rjkguxBalaTQeZxgTKQ24Dqrd-h6HdA,357 +openai/types/admin/organization/projects/groups/role_create_response.py,sha256=gCU0pmwGDexXbFMQReg1J_oEuey_vXYSNVz-zQp9gac,1017 +openai/types/admin/organization/projects/groups/role_delete_response.py,sha256=9dDZXoCneaTp60QLUrqzquNmXomGzP357RtAmOfaG_U,460 +openai/types/admin/organization/projects/groups/role_list_params.py,sha256=9nemSb4BFDUmcjjeuIowDf2utkxNAalqcVDvmLLn2Os,623 +openai/types/admin/organization/projects/groups/role_list_response.py,sha256=Lpr0A3N4FKZlae_Cx7fLYheXW4dtvQS3k3QOixnYas4,1213 +openai/types/admin/organization/projects/project_api_key.py,sha256=VTjjHz48BJnFE2_jyRRTKH2YuQ6NfYaAC6uzdO9U2M0,2046 +openai/types/admin/organization/projects/project_group.py,sha256=lwghiYFF4E629p92e_ixNB0Zg3Idk-qLuPRVhWSVwXQ,710 +openai/types/admin/organization/projects/project_rate_limit.py,sha256=8PgfGdThBJRHW8zk76r2micyXjjdttIJ4NWVV5piXS8,1248 +openai/types/admin/organization/projects/project_service_account.py,sha256=WyNAUKNr6wyvOwrJS9Opnd9qeQJJxD__jhX2saP2auA,756 +openai/types/admin/organization/projects/project_user.py,sha256=8mH-3cu2VJCxSH7JKOiptFzjWyMaxiU_0R1802JjmLA,776 +openai/types/admin/organization/projects/rate_limit_list_rate_limits_params.py,sha256=i1h82bEShBzXWW440zaaaBHtqiVNzsrPs0474kDN_js,1015 +openai/types/admin/organization/projects/rate_limit_update_rate_limit_params.py,sha256=byLFVybJK_LzvE5kVtWs-bB4ez4wmS76gS-5YK7-JTA,933 +openai/types/admin/organization/projects/role_create_params.py,sha256=ESZuNaV2GH_MPEMEFWQDS5owBCcbjOoBNkM6VFxC5V4,556 +openai/types/admin/organization/projects/role_delete_response.py,sha256=80m7TCkyzQYtlbaW7r7ZLf9kX3-VZ2Bu7k8BpnuyUNI,481 +openai/types/admin/organization/projects/role_list_params.py,sha256=2FdVWF4cxKBSiQH-5NsXoyt4dZVcz-Pthz8HgJByszY,565 +openai/types/admin/organization/projects/role_update_params.py,sha256=79S12SGATf4oZxRp6fuo6XMX30ujs0E0nA-y5QZjOVQ,587 +openai/types/admin/organization/projects/service_account_create_params.py,sha256=qjjLYu7hAKn9Get81esTrxBJY33bEidpIocePYAidgQ,356 +openai/types/admin/organization/projects/service_account_create_response.py,sha256=3Wm0k80aiVzIIZvQL8WKVmgLN67buj9fYHLmuQb622U,785 +openai/types/admin/organization/projects/service_account_delete_response.py,sha256=R-fLcAl6eqdAdnV7giqD0i7Zae0JDthU5_vJ03PMtls,354 +openai/types/admin/organization/projects/service_account_list_params.py,sha256=gUiqOz3V27INtw7Tw_0Qnfnzc0anzwHdnAPKcJGkbNc,723 +openai/types/admin/organization/projects/user_create_params.py,sha256=wP6T8wNiAkGjZq7PKhcxFFNvej1ORot3Vm2vU9NY7nU,457 +openai/types/admin/organization/projects/user_delete_response.py,sha256=0007tgxMRau2ZoCifMkBuf2wg71dAQNfXTYalBy_oGM,323 +openai/types/admin/organization/projects/user_list_params.py,sha256=ZlaMc5yx7QA8ogDDHA3Cq-39NRkPwV9Y60XRh9tpEpI,703 +openai/types/admin/organization/projects/user_update_params.py,sha256=4g-V7k7eWOnt4jGDemJ577nZushqqnq5yY1otURo_vk,368 +openai/types/admin/organization/projects/users/__init__.py,sha256=hn4qHHw0j4I2l-EXMhbqHgn2P5UD9pcXXYwN3DXugNc,474 +openai/types/admin/organization/projects/users/__pycache__/__init__.cpython-310.pyc,, +openai/types/admin/organization/projects/users/__pycache__/role_create_params.cpython-310.pyc,, +openai/types/admin/organization/projects/users/__pycache__/role_create_response.cpython-310.pyc,, +openai/types/admin/organization/projects/users/__pycache__/role_delete_response.cpython-310.pyc,, +openai/types/admin/organization/projects/users/__pycache__/role_list_params.cpython-310.pyc,, +openai/types/admin/organization/projects/users/__pycache__/role_list_response.cpython-310.pyc,, +openai/types/admin/organization/projects/users/role_create_params.py,sha256=8-454dHUz6x2rjkguxBalaTQeZxgTKQ24Dqrd-h6HdA,357 +openai/types/admin/organization/projects/users/role_create_response.py,sha256=pyHsBUhXJLWEmEjnoodTZNHzAVgwsWbmR9Jvjdnc-yI,618 +openai/types/admin/organization/projects/users/role_delete_response.py,sha256=9dDZXoCneaTp60QLUrqzquNmXomGzP357RtAmOfaG_U,460 +openai/types/admin/organization/projects/users/role_list_params.py,sha256=9nemSb4BFDUmcjjeuIowDf2utkxNAalqcVDvmLLn2Os,623 +openai/types/admin/organization/projects/users/role_list_response.py,sha256=Lpr0A3N4FKZlae_Cx7fLYheXW4dtvQS3k3QOixnYas4,1213 +openai/types/admin/organization/role.py,sha256=QU_H1IUX1YnBTHPR5q7kwXgBMjfFMMcFnrpgctsqQi4,853 +openai/types/admin/organization/role_create_params.py,sha256=YJFmcSoZ2ST5nka1iYiVvl7p42tIDEJUsRBALxWcuFU,555 +openai/types/admin/organization/role_delete_response.py,sha256=5etIMh2FsGwE28_pkt2EPx305bnfNJrzElgwSSMk0Ck,480 +openai/types/admin/organization/role_list_params.py,sha256=2FdVWF4cxKBSiQH-5NsXoyt4dZVcz-Pthz8HgJByszY,565 +openai/types/admin/organization/role_update_params.py,sha256=eLwZgBtOStqxZXb8kXD6c6Lq_wzRHQcUi8OikvvMyn4,545 +openai/types/admin/organization/usage_audio_speeches_params.py,sha256=rR10IU_0kHY4VmV46vCaAJJ7F6xWXZfy5-uFbfi-sYs,1625 +openai/types/admin/organization/usage_audio_speeches_response.py,sha256=j-EiHBFdpQrxrTqMsngTQ-QIp9Fn7rf_6gsXCpdP4TI,10990 +openai/types/admin/organization/usage_audio_transcriptions_params.py,sha256=AD_pigEf_aNuzdnGLfrLRpep_E6t6vQgtwG-5lccTbg,1637 +openai/types/admin/organization/usage_audio_transcriptions_response.py,sha256=tExJINELhcgn_n8v7HH7a001SvScxnMENqceWSpl5tY,11002 +openai/types/admin/organization/usage_code_interpreter_sessions_params.py,sha256=tJrDYG3snEgVYHVHHL0QV_6--DgRZ97CPHdnIDTWfnU,1301 +openai/types/admin/organization/usage_code_interpreter_sessions_response.py,sha256=QQtfEEFGuxCq9gAruv3S8-q6AHder2_f8hjRPJo-yEk,11010 +openai/types/admin/organization/usage_completions_params.py,sha256=FcmFfFGOOeVbDt16e9Wk9Y29Bi1V7NoM00hFuRtxl7E,1808 +openai/types/admin/organization/usage_completions_response.py,sha256=FjfAp0UqkxyJrsnEZrHMjLBLAGVCp4t3xvZm780Lpjo,10986 +openai/types/admin/organization/usage_costs_params.py,sha256=N0ut2EY4a37LCvpraDejkZofTvv5DNdywBg56a6T3g8,1336 +openai/types/admin/organization/usage_costs_response.py,sha256=DEj__dD2nAkDRDH3fdTu83YfXEvFYLyIgj9mDTKd71Y,10974 +openai/types/admin/organization/usage_embeddings_params.py,sha256=zepEOg0cloZD-cyLdFhFq4o_FJkVt9mnHlQTuMxusBk,1619 +openai/types/admin/organization/usage_embeddings_response.py,sha256=QQtgvXs3z_51Lx6fkcQA3P7wF5oVMTKVPW7yyOLYfgk,10984 +openai/types/admin/organization/usage_images_params.py,sha256=-A-FR1ZlvUEt4XIjm71RJdjVBQp-VAvkSAsrPJ9tNCY,2151 +openai/types/admin/organization/usage_images_response.py,sha256=mazcd1IIjrYiO7a6oviCm-9U3Iz59Tlsi3UcUPsMwJk,10976 +openai/types/admin/organization/usage_moderations_params.py,sha256=WaOt7CVMMF5rqkhYuSNC3Y8JKj9OcUNtKyXdjtwB9t4,1621 +openai/types/admin/organization/usage_moderations_response.py,sha256=JkoQz57Rf2xqzilOWAhjZvm9WCVIm46MP005d1gJTIA,10986 +openai/types/admin/organization/usage_vector_stores_params.py,sha256=E_lIc4St0b_uJU_4_t93wFx4p7a9s7LYTv7p-YwlTPM,1279 +openai/types/admin/organization/usage_vector_stores_response.py,sha256=AN56myDEnuTp-nEnr7WsZ07wLgCkdwJyautWxkv5f20,10988 +openai/types/admin/organization/user_delete_response.py,sha256=l1y5z9hZuTmVgRg2yeTiiCPbzPj_IWy4xsQRe7A8bQ8,314 +openai/types/admin/organization/user_list_params.py,sha256=C_X5xQwRs-5s33zPgiSwRQt7ElIS3ESPN3Lf_nWzZFM,823 +openai/types/admin/organization/user_update_params.py,sha256=H1-hLkWFru49keL_p6aQlfg-Y_mtovRzQkSm3NYpW4M,544 +openai/types/admin/organization/users/__init__.py,sha256=hn4qHHw0j4I2l-EXMhbqHgn2P5UD9pcXXYwN3DXugNc,474 +openai/types/admin/organization/users/__pycache__/__init__.cpython-310.pyc,, +openai/types/admin/organization/users/__pycache__/role_create_params.cpython-310.pyc,, +openai/types/admin/organization/users/__pycache__/role_create_response.cpython-310.pyc,, +openai/types/admin/organization/users/__pycache__/role_delete_response.cpython-310.pyc,, +openai/types/admin/organization/users/__pycache__/role_list_params.cpython-310.pyc,, +openai/types/admin/organization/users/__pycache__/role_list_response.cpython-310.pyc,, +openai/types/admin/organization/users/role_create_params.py,sha256=TCpbJtiJgb2i67nbachk6LqnqyuGDLd7ASjDyIuYJq0,326 +openai/types/admin/organization/users/role_create_response.py,sha256=cT1Z-rE356OJ52Scm8-aKbD02hVbdLROXthU971IxOc,615 +openai/types/admin/organization/users/role_delete_response.py,sha256=mKACovZTBnxcsQasWRIBDaNKyeAZk0rKVGT9Slen8bM,459 +openai/types/admin/organization/users/role_list_params.py,sha256=ndIqUzHSR4Ii2DGJ4jSuknyZ0bMsmiH77izcEztoxs0,597 +openai/types/admin/organization/users/role_list_response.py,sha256=F9Sq4qOYnNCOVacVDy9VdjV7JQLBQTbXIokKVcJLg2E,1212 +openai/types/audio/__init__.py,sha256=8DwArrrSRwIemWLhWLItaV3F_EgXgtVPSu4yUIf8iyM,1723 +openai/types/audio/__pycache__/__init__.cpython-310.pyc,, +openai/types/audio/__pycache__/speech_create_params.cpython-310.pyc,, +openai/types/audio/__pycache__/speech_model.cpython-310.pyc,, +openai/types/audio/__pycache__/transcription.cpython-310.pyc,, +openai/types/audio/__pycache__/transcription_create_params.cpython-310.pyc,, +openai/types/audio/__pycache__/transcription_create_response.cpython-310.pyc,, +openai/types/audio/__pycache__/transcription_diarized.cpython-310.pyc,, +openai/types/audio/__pycache__/transcription_diarized_segment.cpython-310.pyc,, +openai/types/audio/__pycache__/transcription_include.cpython-310.pyc,, +openai/types/audio/__pycache__/transcription_segment.cpython-310.pyc,, +openai/types/audio/__pycache__/transcription_stream_event.cpython-310.pyc,, +openai/types/audio/__pycache__/transcription_text_delta_event.cpython-310.pyc,, +openai/types/audio/__pycache__/transcription_text_done_event.cpython-310.pyc,, +openai/types/audio/__pycache__/transcription_text_segment_event.cpython-310.pyc,, +openai/types/audio/__pycache__/transcription_verbose.cpython-310.pyc,, +openai/types/audio/__pycache__/transcription_word.cpython-310.pyc,, +openai/types/audio/__pycache__/translation.cpython-310.pyc,, +openai/types/audio/__pycache__/translation_create_params.cpython-310.pyc,, +openai/types/audio/__pycache__/translation_create_response.cpython-310.pyc,, +openai/types/audio/__pycache__/translation_verbose.cpython-310.pyc,, +openai/types/audio/speech_create_params.py,sha256=4e8Zvljk1x5XTFVUpJOlB4S6Gt9fjDzFgjPcVYqlkvs,2144 +openai/types/audio/speech_model.py,sha256=swuN1lLQxGSuYj_X_OeQuUx5abIUpEfZZqNjDES7kU0,267 +openai/types/audio/transcription.py,sha256=7q7nfUTe-GDMpicrWOugFU4bSBIyqhQkndnKCTD1X2M,2407 +openai/types/audio/transcription_create_params.py,sha256=Mxl-LoHCiEkO41fGUcsSmN35fOtNWXYDgMa-nP90DNg,6977 +openai/types/audio/transcription_create_response.py,sha256=-x20GMKDHrHzl_37fsGjpPlJC91ZNGwrD_5-AkZgnOw,459 +openai/types/audio/transcription_diarized.py,sha256=fYKkV0B5Rjcx9GC-6TfJP4TjSWUbbIdvle1Sb3DQp2I,2374 +openai/types/audio/transcription_diarized_segment.py,sha256=s63ItoQlqLqxi17vUniZagifOw8Y-nVR17-SwQUWW8Y,931 +openai/types/audio/transcription_include.py,sha256=mclUP_50njW7TG4d9m_E6zSjAFW8djPJ6ZTYub71kq0,227 +openai/types/audio/transcription_segment.py,sha256=-pPAGolwIIXUBMic-H5U7aR0u_Aq-pipSA4xTtn_viA,1153 +openai/types/audio/transcription_stream_event.py,sha256=MJNeIqgrVJekLGA3KSzE7lHK3dyhrvvhGLIwgQsZDPE,648 +openai/types/audio/transcription_text_delta_event.py,sha256=JH09I9eYFZLZKAJcSMc3-4owS9CtTpTmNajXgAlcQ7c,1551 +openai/types/audio/transcription_text_done_event.py,sha256=AtXZflObQVBwETQlVcUqN4h-SFiiod4oAH9f7UHZ39g,2341 +openai/types/audio/transcription_text_segment_event.py,sha256=amH-qLV2l1Y4d2bnZrWplsz41_LzYvmyOdHv1rlXEtE,990 +openai/types/audio/transcription_verbose.py,sha256=vI30MetsMh3yT2hTCUGdKxjHNZ0wkM2mJ-yhu2opGuM,1303 +openai/types/audio/transcription_word.py,sha256=s2aWssAgHjMOZHhiihs1m4gYWQpjBP2rkI1DE5eZBXc,367 +openai/types/audio/translation.py,sha256=Dlu9YMo0cc44NSCAtLfZnEugkM7VBA6zw2v9bfrLMh0,193 +openai/types/audio/translation_create_params.py,sha256=ejrom_64QOe47gZtrYmDAQkb65wLaZL4-iU-mKVTVq0,1572 +openai/types/audio/translation_create_response.py,sha256=x6H0yjTbZR3vd3d7LdABcn9nrMDNdeMjepcjW1oUfVc,362 +openai/types/audio/translation_verbose.py,sha256=lGB5FqkV-ne__aaGbMTFbEciJ-Sl3wBhlKmETmtROT8,615 +openai/types/audio_model.py,sha256=U5nv4NKBd3A5k3mDw0BmK0PiSc0VQADOkirXnKsC-eo,344 +openai/types/audio_response_format.py,sha256=67QSPDpT9_yYhxFYYd15N3nukwKrHJ7f8pvVQiVOQuk,276 +openai/types/auto_file_chunking_strategy_param.py,sha256=wvFMNI7RvIPLBoGZpdRMgVa-VlQkovurGi1aypefqwg,495 +openai/types/batch.py,sha256=o8ADxSZQe7F_1VTGSC5_RDUajU03SbWvN1wPiH98dVQ,3517 +openai/types/batch_create_params.py,sha256=4BruiTfBF9RfDIVK4gTfZcDDoUI4G7FxUusINvWrv70,2858 +openai/types/batch_error.py,sha256=Xxl-gYm0jerpYyI-mKSSVxRMQRubkoLUiOP9U3v72EM,622 +openai/types/batch_list_params.py,sha256=X1_sfRspuIMSDyXWVh0YnJ9vJLeOOH66TrvgEHueC84,705 +openai/types/batch_request_counts.py,sha256=iIPVKk4s5FcHlfLvLYetuXb_RxGPUvCGhRGYTryszV8,479 +openai/types/batch_usage.py,sha256=myAsCyOT7xWiZ_GDznGptUHeJVYx_Mg7c1cEtBMKmEc,1260 +openai/types/beta/__init__.py,sha256=kl4wEKnYF_urBLZV6wZ6ZCTwaLhlNYSOfFR64jO-Adc,2393 +openai/types/beta/__pycache__/__init__.cpython-310.pyc,, +openai/types/beta/__pycache__/assistant.cpython-310.pyc,, +openai/types/beta/__pycache__/assistant_create_params.cpython-310.pyc,, +openai/types/beta/__pycache__/assistant_deleted.cpython-310.pyc,, +openai/types/beta/__pycache__/assistant_list_params.cpython-310.pyc,, +openai/types/beta/__pycache__/assistant_response_format_option.cpython-310.pyc,, +openai/types/beta/__pycache__/assistant_response_format_option_param.cpython-310.pyc,, +openai/types/beta/__pycache__/assistant_stream_event.cpython-310.pyc,, +openai/types/beta/__pycache__/assistant_tool.cpython-310.pyc,, +openai/types/beta/__pycache__/assistant_tool_choice.cpython-310.pyc,, +openai/types/beta/__pycache__/assistant_tool_choice_function.cpython-310.pyc,, +openai/types/beta/__pycache__/assistant_tool_choice_function_param.cpython-310.pyc,, +openai/types/beta/__pycache__/assistant_tool_choice_option.cpython-310.pyc,, +openai/types/beta/__pycache__/assistant_tool_choice_option_param.cpython-310.pyc,, +openai/types/beta/__pycache__/assistant_tool_choice_param.cpython-310.pyc,, +openai/types/beta/__pycache__/assistant_tool_param.cpython-310.pyc,, +openai/types/beta/__pycache__/assistant_update_params.cpython-310.pyc,, +openai/types/beta/__pycache__/chatkit_workflow.cpython-310.pyc,, +openai/types/beta/__pycache__/code_interpreter_tool.cpython-310.pyc,, +openai/types/beta/__pycache__/code_interpreter_tool_param.cpython-310.pyc,, +openai/types/beta/__pycache__/file_search_tool.cpython-310.pyc,, +openai/types/beta/__pycache__/file_search_tool_param.cpython-310.pyc,, +openai/types/beta/__pycache__/function_tool.cpython-310.pyc,, +openai/types/beta/__pycache__/function_tool_param.cpython-310.pyc,, +openai/types/beta/__pycache__/thread.cpython-310.pyc,, +openai/types/beta/__pycache__/thread_create_and_run_params.cpython-310.pyc,, +openai/types/beta/__pycache__/thread_create_params.cpython-310.pyc,, +openai/types/beta/__pycache__/thread_deleted.cpython-310.pyc,, +openai/types/beta/__pycache__/thread_update_params.cpython-310.pyc,, +openai/types/beta/assistant.py,sha256=K97cr0lg4fiZuLO6zNqIZVuUBjMFxtRtoszjyNI70DA,5394 +openai/types/beta/assistant_create_params.py,sha256=0TrKE4rMWP9y2sE1VL9T9vSyDv9Ty6fvuo3OnzHiyLo,8991 +openai/types/beta/assistant_deleted.py,sha256=bTTUl5FPHTBI5nRm7d0sGuR9VCSBDZ-IbOn9G_IpmJQ,301 +openai/types/beta/assistant_list_params.py,sha256=yW-lj6AUkG0IRZQKre0veEr9p4VMN-9YdELFMYs74Cw,1222 +openai/types/beta/assistant_response_format_option.py,sha256=yNeoAWxM-_8Sjmwqu8exqyKRFhVZIKeTypetPY55VFA,561 +openai/types/beta/assistant_response_format_option_param.py,sha256=dyPMhwRSLBZ0ltpxiD7KM-9X6BzWnbGeG-nT_3SenuQ,628 +openai/types/beta/assistant_stream_event.py,sha256=FDkbgQcmL64ExC2Q3mrPD73pYdGFcIMPt-wboshBWHg,10055 +openai/types/beta/assistant_tool.py,sha256=_0FC7Db4Ctq_0yLaKJ93zNTB5HthuJWEAHx3fadDRlw,506 +openai/types/beta/assistant_tool_choice.py,sha256=QXy2nQ2-_JLh3aU_BRZ3K17uZJUxrHC1cygqUMnr0U4,652 +openai/types/beta/assistant_tool_choice_function.py,sha256=p5YEbTnED_kZpPfj5fMQqWSgLXAUEajsDd0LXGdlENU,269 +openai/types/beta/assistant_tool_choice_function_param.py,sha256=-O38277LhSaqOVhTp0haHP0ZnVTLpEBvcLJa5MRo7wE,355 +openai/types/beta/assistant_tool_choice_option.py,sha256=jrXMd_IYIQ1pt8Lkc-KrPd4CR3lR8sFV4m7_lpG8A4Y,362 +openai/types/beta/assistant_tool_choice_option_param.py,sha256=VcatO5Nej9e5eqfrwetG4uM1vFoewnBEcFz47IxAK2E,424 +openai/types/beta/assistant_tool_choice_param.py,sha256=vB7bLafOjDZ4Ww3GMT_CXzcpFtVUtH6nYvHXpVjg_xA,680 +openai/types/beta/assistant_tool_param.py,sha256=6DcaU3nMjurur2VkVIYcCaRAY1QLQscXXjCd0ZHHGho,501 +openai/types/beta/assistant_update_params.py,sha256=sveL8Z489CV1SemVlQzGlNPjDy6JINfDLYoGgCFdrsg,7417 +openai/types/beta/chat/__init__.py,sha256=OKfJYcKb4NObdiRObqJV_dOyDQ8feXekDUge2o_4pXQ,122 +openai/types/beta/chat/__pycache__/__init__.cpython-310.pyc,, +openai/types/beta/chatkit/__init__.py,sha256=K4Q3JL1OSz8tRSJyUoReRkBKsksw5QZdBy4HBvuBjZ4,2116 +openai/types/beta/chatkit/__pycache__/__init__.cpython-310.pyc,, +openai/types/beta/chatkit/__pycache__/chat_session.cpython-310.pyc,, +openai/types/beta/chatkit/__pycache__/chat_session_automatic_thread_titling.cpython-310.pyc,, +openai/types/beta/chatkit/__pycache__/chat_session_chatkit_configuration.cpython-310.pyc,, +openai/types/beta/chatkit/__pycache__/chat_session_chatkit_configuration_param.cpython-310.pyc,, +openai/types/beta/chatkit/__pycache__/chat_session_expires_after_param.cpython-310.pyc,, +openai/types/beta/chatkit/__pycache__/chat_session_file_upload.cpython-310.pyc,, +openai/types/beta/chatkit/__pycache__/chat_session_history.cpython-310.pyc,, +openai/types/beta/chatkit/__pycache__/chat_session_rate_limits.cpython-310.pyc,, +openai/types/beta/chatkit/__pycache__/chat_session_rate_limits_param.cpython-310.pyc,, +openai/types/beta/chatkit/__pycache__/chat_session_status.cpython-310.pyc,, +openai/types/beta/chatkit/__pycache__/chat_session_workflow_param.cpython-310.pyc,, +openai/types/beta/chatkit/__pycache__/chatkit_attachment.cpython-310.pyc,, +openai/types/beta/chatkit/__pycache__/chatkit_response_output_text.cpython-310.pyc,, +openai/types/beta/chatkit/__pycache__/chatkit_thread.cpython-310.pyc,, +openai/types/beta/chatkit/__pycache__/chatkit_thread_assistant_message_item.cpython-310.pyc,, +openai/types/beta/chatkit/__pycache__/chatkit_thread_item_list.cpython-310.pyc,, +openai/types/beta/chatkit/__pycache__/chatkit_thread_user_message_item.cpython-310.pyc,, +openai/types/beta/chatkit/__pycache__/chatkit_widget_item.cpython-310.pyc,, +openai/types/beta/chatkit/__pycache__/session_create_params.cpython-310.pyc,, +openai/types/beta/chatkit/__pycache__/thread_delete_response.cpython-310.pyc,, +openai/types/beta/chatkit/__pycache__/thread_list_items_params.cpython-310.pyc,, +openai/types/beta/chatkit/__pycache__/thread_list_params.cpython-310.pyc,, +openai/types/beta/chatkit/chat_session.py,sha256=NjVT5SQUWNroXynit10bwKsj8mntUSLouST46C9sBhM,1401 +openai/types/beta/chatkit/chat_session_automatic_thread_titling.py,sha256=R0PpWfBT5VMZp--Xxn082UjWbha7U5K9lJeSa4Cbhuk,360 +openai/types/beta/chatkit/chat_session_chatkit_configuration.py,sha256=-ailkIhSj6W2rHS3xPNc7XJ0duVG0fTmJaaVqqoE9RE,739 +openai/types/beta/chatkit/chat_session_chatkit_configuration_param.py,sha256=4_3sCd7BIeNsy-kArfNgDO1jHjaUn703ib4_CHbsuZQ,2178 +openai/types/beta/chatkit/chat_session_expires_after_param.py,sha256=E9IcLvoz0FIIxE73sOF-WuqySbMpk5E9jvMj28_mDdo,597 +openai/types/beta/chatkit/chat_session_file_upload.py,sha256=ruKpNTM8zhXZfXgBZDYOGgRDT4Y3J4IjeMSnEwdlFTI,558 +openai/types/beta/chatkit/chat_session_history.py,sha256=XuxpwdFgpfCuw8Uc_TFB7H33683fSAfqhfIRdJoLQ6U,534 +openai/types/beta/chatkit/chat_session_rate_limits.py,sha256=irV4fZrQs6e6GbBT7rPsjsJBlheq3rz9tBsGq_fnb9k,353 +openai/types/beta/chatkit/chat_session_rate_limits_param.py,sha256=n8aeeakdT7L6liR6I5umF9BHABInNx7rL2WhmFWx0jQ,446 +openai/types/beta/chatkit/chat_session_status.py,sha256=l-SGwIDV4EFdX13Wjl2t-EipKFyYw7mckp9gxJhydqI,243 +openai/types/beta/chatkit/chat_session_workflow_param.py,sha256=bP2hQ-PXLLC1c8gjDjOh_fVLRPOFVSj7WV2-RrT9rfE,1202 +openai/types/beta/chatkit/chatkit_attachment.py,sha256=ZQPepId3dMRd-Jrzc0gCatbsXqYoj51-3S2XbPfAOmE,665 +openai/types/beta/chatkit/chatkit_response_output_text.py,sha256=e3rNmV2eTU0msEh67TaZRvE58wduZdaeN30wXpf39I0,1882 +openai/types/beta/chatkit/chatkit_thread.py,sha256=JAqb28gFwoGHgF6QPy0brlUc1jCzV1BFoiRikKrJ-IM,1918 +openai/types/beta/chatkit/chatkit_thread_assistant_message_item.py,sha256=va96N80NNiHFRYEArjBNYlwFilbqZXvOtlHR0Dxec5o,941 +openai/types/beta/chatkit/chatkit_thread_item_list.py,sha256=2Qv0iPKkvIANfWQpIZh7iqZYBz51tgBAYtcSh3M8eaw,4302 +openai/types/beta/chatkit/chatkit_thread_user_message_item.py,sha256=pcpYEqmODoV-1MWgQsElSS8rcEbsp9OYRLKkr9SceqA,2505 +openai/types/beta/chatkit/chatkit_widget_item.py,sha256=d6l-XTELPMSLCizd2d6gnzBnYocDkaaFPei9WWhKggk,774 +openai/types/beta/chatkit/session_create_params.py,sha256=OUWYjVEXdYa8Y7mMKjR8CwZCAKI9QMZ1aqM8N1JDcQw,1274 +openai/types/beta/chatkit/thread_delete_response.py,sha256=laKdWnyeplfi0Tos0ps-izneu2ZGEnst7FJn87BS8pU,549 +openai/types/beta/chatkit/thread_list_items_params.py,sha256=9WerQ8VLMzWFSGJDnmg82bRNZy-YT7S6OjESDN9a9vU,697 +openai/types/beta/chatkit/thread_list_params.py,sha256=IHHdXtlMoV7a19YJg8dFLYzVgSzEUnSgMW2kQc_RE9Y,812 +openai/types/beta/chatkit_workflow.py,sha256=TCG5iL_5j9Lq_EsRx7HKrUYWhz9SFIJbHrYlYkXnSAg,961 +openai/types/beta/code_interpreter_tool.py,sha256=7mgQc9OtD_ZUnZeNhoobMFcmmvtZPFCNYGB-PEnNnfs,333 +openai/types/beta/code_interpreter_tool_param.py,sha256=X6mwzFyZx1RCKEYbBCPs4kh_tZkxFxydPMK4yFNJkLs,389 +openai/types/beta/file_search_tool.py,sha256=1r_kHrJYPD8HJ2lCg_npyXvG-BSydlOyo4dpnEI3w0o,2136 +openai/types/beta/file_search_tool_param.py,sha256=LZYlCZoHFOzqQnE7y55Oq5k20R9S0ZHJrtBpGnhYr_I,2132 +openai/types/beta/function_tool.py,sha256=oYGJfcfPpUohKw2ikgshDjOI1HXCK-5pAWyegYNezeU,397 +openai/types/beta/function_tool_param.py,sha256=hCclpGO4Re-TxiGy_QxX75g1kcN6_ElubicO6SdJ_YI,471 +openai/types/beta/realtime/__init__.py,sha256=trJb-lqh3vHHMYdohrgiU2cHwReFZyw4cXM-Xj8Dwq8,7364 +openai/types/beta/realtime/__pycache__/__init__.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/conversation_created_event.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/conversation_item.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/conversation_item_content.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/conversation_item_content_param.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/conversation_item_create_event.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/conversation_item_create_event_param.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/conversation_item_created_event.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/conversation_item_delete_event.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/conversation_item_delete_event_param.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/conversation_item_deleted_event.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/conversation_item_input_audio_transcription_completed_event.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/conversation_item_input_audio_transcription_delta_event.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/conversation_item_input_audio_transcription_failed_event.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/conversation_item_param.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/conversation_item_retrieve_event.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/conversation_item_retrieve_event_param.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/conversation_item_truncate_event.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/conversation_item_truncate_event_param.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/conversation_item_truncated_event.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/conversation_item_with_reference.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/conversation_item_with_reference_param.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/error_event.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/input_audio_buffer_append_event.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/input_audio_buffer_append_event_param.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/input_audio_buffer_clear_event.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/input_audio_buffer_clear_event_param.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/input_audio_buffer_cleared_event.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/input_audio_buffer_commit_event.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/input_audio_buffer_commit_event_param.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/input_audio_buffer_committed_event.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/input_audio_buffer_speech_started_event.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/input_audio_buffer_speech_stopped_event.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/rate_limits_updated_event.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/realtime_client_event.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/realtime_client_event_param.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/realtime_connect_params.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/realtime_response.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/realtime_response_status.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/realtime_response_usage.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/realtime_server_event.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/response_audio_delta_event.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/response_audio_done_event.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/response_audio_transcript_delta_event.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/response_audio_transcript_done_event.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/response_cancel_event.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/response_cancel_event_param.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/response_content_part_added_event.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/response_content_part_done_event.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/response_create_event.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/response_create_event_param.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/response_created_event.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/response_done_event.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/response_function_call_arguments_delta_event.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/response_function_call_arguments_done_event.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/response_output_item_added_event.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/response_output_item_done_event.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/response_text_delta_event.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/response_text_done_event.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/session.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/session_create_params.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/session_create_response.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/session_created_event.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/session_update_event.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/session_update_event_param.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/session_updated_event.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/transcription_session.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/transcription_session_create_params.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/transcription_session_update.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/transcription_session_update_param.cpython-310.pyc,, +openai/types/beta/realtime/__pycache__/transcription_session_updated_event.cpython-310.pyc,, +openai/types/beta/realtime/conversation_created_event.py,sha256=U4-nesN8rAep2_25E2DrkXUMafQejj3NE_0llXKj5Y8,752 +openai/types/beta/realtime/conversation_item.py,sha256=eIFg9zl3qzEijcQZvCnkvVLpSZgvEdubasgxGsQuFM4,2327 +openai/types/beta/realtime/conversation_item_content.py,sha256=KWZY8EUkjAi6K_IkWVjjrNZLG3KK2vGCy2_O30CEhzY,1050 +openai/types/beta/realtime/conversation_item_content_param.py,sha256=CrGi3XKwnfJdQGs-kJaGCsn53omdJF6_je0GWnVXhjQ,972 +openai/types/beta/realtime/conversation_item_create_event.py,sha256=jYXYdmqJh_znzcAgDuCxJXo5shf-t_DwmsyFkaDVnAE,1081 +openai/types/beta/realtime/conversation_item_create_event_param.py,sha256=vxTag6TrOLu1bf46F3mUmRkl5dd1Kb6bUp65gBDVmhM,1101 +openai/types/beta/realtime/conversation_item_created_event.py,sha256=cZBm_uKk5dkQXLlbF0Aetg4NJge3Ftz9kwRu2kCI3m4,817 +openai/types/beta/realtime/conversation_item_delete_event.py,sha256=p-O6R1Ku5pxZvaxhSi4YTPqLXS1SHhdLGgJuPQyPcHY,549 +openai/types/beta/realtime/conversation_item_delete_event_param.py,sha256=a17h8Hd8MxUbXT6NQg8YpTr1ICt1ztRecpfukHw4g34,569 +openai/types/beta/realtime/conversation_item_deleted_event.py,sha256=uWHSqX5ig550romSdhtROwrdQmdeN31Oz1Vpr9IuQFI,492 +openai/types/beta/realtime/conversation_item_input_audio_transcription_completed_event.py,sha256=FwZHHO4ZGMKoeQ80snCh_S-7anNUQtRLOhGjb8ScGOQ,2538 +openai/types/beta/realtime/conversation_item_input_audio_transcription_delta_event.py,sha256=5kjLmnRJug7L5fHxSSWWbhB70jGwNaMwbdENEwz9Xek,1143 +openai/types/beta/realtime/conversation_item_input_audio_transcription_failed_event.py,sha256=xYNSBIyERQJ4P-5YoFF1VptfPa8JnJ0sWaH6LGsPow0,1077 +openai/types/beta/realtime/conversation_item_param.py,sha256=HMB7MFR6WkztV1vMCFdIYNv8qOY4jzI2MIDtr9y8nEo,2207 +openai/types/beta/realtime/conversation_item_retrieve_event.py,sha256=5Cc7f0fM8ujwER0eIcQRwz0rmc6hdCUrAqiAvRNn9Zc,559 +openai/types/beta/realtime/conversation_item_retrieve_event_param.py,sha256=TRYaZ3btNaywRPaMOVRzK5VT7wh4taIGjbUdhkZ7gFc,579 +openai/types/beta/realtime/conversation_item_truncate_event.py,sha256=1c2_BamaTkgD26eyGZJU5xwbz7lRHupqU2HqcK0VniI,943 +openai/types/beta/realtime/conversation_item_truncate_event_param.py,sha256=hSnVOSMMtLf16nn4ISHkevYCfEsiN9kNcgxXRtHa8Kc,983 +openai/types/beta/realtime/conversation_item_truncated_event.py,sha256=K4S35U85J-UNRba9nkm-7G1ReZu8gA8Sa1z0-Vlozc0,704 +openai/types/beta/realtime/conversation_item_with_reference.py,sha256=NDMfbnG0YKLqWJskFSHRIMkN2ISs8yNRxP6d6sZshws,3288 +openai/types/beta/realtime/conversation_item_with_reference_param.py,sha256=X0iEdjijFkoGtZtp0viB8bAFqMn4fNNSvJiCZbgJ-3Q,3079 +openai/types/beta/realtime/error_event.py,sha256=goNkorKXUHKiYVsVunEsnaRa6_3dsDKVtrxXQtzZCmk,877 +openai/types/beta/realtime/input_audio_buffer_append_event.py,sha256=lTKWd_WFbtDAy6AdaCjeQYBV0dgHuVNNt_PbrtPB8tg,662 +openai/types/beta/realtime/input_audio_buffer_append_event_param.py,sha256=XmN2bE6jBRrkKGVPJdnPjJql5dqMPqwbmFnxo-z22JE,682 +openai/types/beta/realtime/input_audio_buffer_clear_event.py,sha256=7AfCQfMxZQ-UoQXF9edYKw5GcTELPcfvvJWWpuLS41c,489 +openai/types/beta/realtime/input_audio_buffer_clear_event_param.py,sha256=y-zfWqJsh1n6r2i0MgLDpnNC4g1dq3GCS66Twfkng38,499 +openai/types/beta/realtime/input_audio_buffer_cleared_event.py,sha256=j9gpm7aGVmrUt48wqtvBMN8NOgtvqHciegjXjOnWm7A,429 +openai/types/beta/realtime/input_audio_buffer_commit_event.py,sha256=SLZR2xxRd6uO3IQL6-LuozkjROXiGyblKoHYQjwXk4I,493 +openai/types/beta/realtime/input_audio_buffer_commit_event_param.py,sha256=B8agXC-rUl-D-RijJ5MeTLgw43qVYzmf2_2oAVokhLY,503 +openai/types/beta/realtime/input_audio_buffer_committed_event.py,sha256=76XHl3ETfG5YiYce2OCUsv0wNfSiaabLzYVjGtBwux0,733 +openai/types/beta/realtime/input_audio_buffer_speech_started_event.py,sha256=NVp60RUsLFtte9Ilknmu_5lRk2dZp_1fXCgGHd4EvSM,861 +openai/types/beta/realtime/input_audio_buffer_speech_stopped_event.py,sha256=gszRuYQtAW8upIhd7CJZ7pxboDk-K7sqidjqxgf47q4,779 +openai/types/beta/realtime/rate_limits_updated_event.py,sha256=kBnf_p-49Q_LNdJsj0R1Szi8R4TGYAAJ_KifLuuyFZw,949 +openai/types/beta/realtime/realtime_client_event.py,sha256=0c48JcJH5yruF52zl0Sanm_dd2W5ZHV5GocRG0Xm6m4,1839 +openai/types/beta/realtime/realtime_client_event_param.py,sha256=xBeZ60Q-OWuZxstPQaoqE0DUTDOPOwrL8LWMmDJI2rM,1887 +openai/types/beta/realtime/realtime_connect_params.py,sha256=AvTypkFCYmDn9qMeektVqij6cqzgovr3PpgpMalJoJ4,290 +openai/types/beta/realtime/realtime_response.py,sha256=iUOItlPQv6-okCuiTsloe0LDVyJ0MUQ64ug8ZaLePnw,3567 +openai/types/beta/realtime/realtime_response_status.py,sha256=gU-59Pr_58TRfMZqFzdCloc53e1qOnU4aaHY3yURUK8,1326 +openai/types/beta/realtime/realtime_response_usage.py,sha256=6XOFjCjPWioHoICZ0Q8KXuUzktQugx6WuTz0O5UvzZg,1541 +openai/types/beta/realtime/realtime_server_event.py,sha256=-PpqZpg-DL_C_wseLMRQHWdBvxnVGRAfOF7x13Qr34E,5408 +openai/types/beta/realtime/response_audio_delta_event.py,sha256=UjbnK4u_WSNTOColZj8SmJgHnAc2H8iRXD76ZnPbz7E,742 +openai/types/beta/realtime/response_audio_done_event.py,sha256=1XEWBPh1JiOgyr6V03mRt_3sLm0YFUq5ft1AhfFlNEg,679 +openai/types/beta/realtime/response_audio_transcript_delta_event.py,sha256=HEVNQ_R2_Nyo6BvNvsliMnN__b17eVd2Jx5udRHg0Hg,773 +openai/types/beta/realtime/response_audio_transcript_done_event.py,sha256=Cn5l4mJnKK3LeSN9qFL4LLqs1WOWg4kt1SaYThB-5c0,787 +openai/types/beta/realtime/response_cancel_event.py,sha256=EKx8IZUISJHdl-_3tCdHtz2BINQ85Tq_ocadnsEGPSk,637 +openai/types/beta/realtime/response_cancel_event_param.py,sha256=nidzBL83liHwyImiNGiz9Ad0V34EtFAQDw1utqcF6ns,630 +openai/types/beta/realtime/response_content_part_added_event.py,sha256=a8-rm1NAwX685fk7GdT6Xi0Yr-JfeAkyUr94-RoFe34,1232 +openai/types/beta/realtime/response_content_part_done_event.py,sha256=jO2TZygxPabbnEG9E1AfNP-JYJv1QtCMnCzgcZ_3n18,1190 +openai/types/beta/realtime/response_create_event.py,sha256=46i-O9wwvhr1CzHNMDzhs2SGVwHiFJDOkQfOZZRfAWo,4763 +openai/types/beta/realtime/response_create_event_param.py,sha256=IPJlTWH0HzsknpSRrFgrQ3bfxsFZVRdQ6IYEsiGSZOk,4619 +openai/types/beta/realtime/response_created_event.py,sha256=zZtHx-1YjehXxX6aNE88SFINDaKOBzpzejo6sTNjq9g,506 +openai/types/beta/realtime/response_done_event.py,sha256=_yUPoECCli89iHLtV3NQkXQOW6Lc1JlxVPFw04ziBGY,494 +openai/types/beta/realtime/response_function_call_arguments_delta_event.py,sha256=Yh2mQZDucfnTLiO8LRyG9r7zeS1sjwLcMF1JPMdTFJc,793 +openai/types/beta/realtime/response_function_call_arguments_done_event.py,sha256=kxSPK6nbNWL6pxveY7zaNGgCkCXqyBFJPVYJrw9cbOw,793 +openai/types/beta/realtime/response_output_item_added_event.py,sha256=-_BZjvAqcgv3NIz-EMhvYMxIwvcXTt68FVNp0pw09dI,713 +openai/types/beta/realtime/response_output_item_done_event.py,sha256=0ClNVMZmeIxKghlEid9VGoWiZ97wp00hIdNnev4qBD8,709 +openai/types/beta/realtime/response_text_delta_event.py,sha256=B1yyuc6iMOMoG5Wh6W5KoQNYtVD1vEm2cKqHnl2CuFQ,721 +openai/types/beta/realtime/response_text_done_event.py,sha256=mPgVG6nWxwkZ3aZOX-JkVF7CpaWP5-bvtbxFrr4fK7g,724 +openai/types/beta/realtime/session.py,sha256=RZMR4d09k0erHFefzbYwQNyw0V6M5ESEPJ0qoO90lCU,10183 +openai/types/beta/realtime/session_create_params.py,sha256=PTFBt7w7fTrz2KWZIz5GjJqLoQkyv7qEIspFscs6zy8,10251 +openai/types/beta/realtime/session_create_response.py,sha256=HfCFE46q3IEfvLFEdU06DAg5GKIPlJjaU9DtKzKcr2U,6574 +openai/types/beta/realtime/session_created_event.py,sha256=rTElnBlE7z1htmkdmpdPN4q_dUYS6Su4BkmsqO65hUc,489 +openai/types/beta/realtime/session_update_event.py,sha256=w4SVhFjcoasgL1yyyNfykarnD-BzmxDt_0kED8pN8pw,11237 +openai/types/beta/realtime/session_update_event_param.py,sha256=Wu_4oa0R1YUTyI6_7AtOwy07qJf1YSCUZpdqO8CKkd0,10749 +openai/types/beta/realtime/session_updated_event.py,sha256=HyR-Pz3U9finVO-bUCvnmeqsANw-fceNvVqEIF6ey10,489 +openai/types/beta/realtime/transcription_session.py,sha256=Soo2LuEMJtkUD2oPJ1E23GUcoUrYBiSu_UtbLUKemfw,3184 +openai/types/beta/realtime/transcription_session_create_params.py,sha256=BVwSY41UX2njXAJpWynMJtC5XuKv6sNs7kp2Y8KSjnk,5976 +openai/types/beta/realtime/transcription_session_update.py,sha256=YMP9OB9P5FaSwaicXtYELjm4hD1gDSvKFq9YtF2sq64,6694 +openai/types/beta/realtime/transcription_session_update_param.py,sha256=b99v4yKnB2lC_cnYGiaxKnQuHB4eUW-v3eKT2UDsamk,6453 +openai/types/beta/realtime/transcription_session_updated_event.py,sha256=CKAS98QL7CuOVEWF6qGcC9qhTktdG2CPPJXbrW75GIM,833 +openai/types/beta/thread.py,sha256=bVlpfXpyA_tApIDBNAWJCgusLEiE-7xR-ptcIq1obg4,2545 +openai/types/beta/thread_create_and_run_params.py,sha256=4JQRzg8p4dNpsbGt2P479Uz_X_Q5O2-PZ2iDBxS03uM,15981 +openai/types/beta/thread_create_params.py,sha256=wfpOgxuEZhE81n2nWBU5uH5-kZscsMVqVuzwI0A6YYY,7122 +openai/types/beta/thread_deleted.py,sha256=MaYG_jZIjSiB9h_ZBiTtpMsRSwFKkCY83ziM5GO_oUk,292 +openai/types/beta/thread_update_params.py,sha256=oPdEz_th3PNmWB9jMA3ZdkOPalaCfMEVminirac7Cas,2217 +openai/types/beta/threads/__init__.py,sha256=0WsJo0tXp08CgayozR7Tqc3b8sqzotWzvBun19CEIWc,3066 +openai/types/beta/threads/__pycache__/__init__.cpython-310.pyc,, +openai/types/beta/threads/__pycache__/annotation.cpython-310.pyc,, +openai/types/beta/threads/__pycache__/annotation_delta.cpython-310.pyc,, +openai/types/beta/threads/__pycache__/file_citation_annotation.cpython-310.pyc,, +openai/types/beta/threads/__pycache__/file_citation_delta_annotation.cpython-310.pyc,, +openai/types/beta/threads/__pycache__/file_path_annotation.cpython-310.pyc,, +openai/types/beta/threads/__pycache__/file_path_delta_annotation.cpython-310.pyc,, +openai/types/beta/threads/__pycache__/image_file.cpython-310.pyc,, +openai/types/beta/threads/__pycache__/image_file_content_block.cpython-310.pyc,, +openai/types/beta/threads/__pycache__/image_file_content_block_param.cpython-310.pyc,, +openai/types/beta/threads/__pycache__/image_file_delta.cpython-310.pyc,, +openai/types/beta/threads/__pycache__/image_file_delta_block.cpython-310.pyc,, +openai/types/beta/threads/__pycache__/image_file_param.cpython-310.pyc,, +openai/types/beta/threads/__pycache__/image_url.cpython-310.pyc,, +openai/types/beta/threads/__pycache__/image_url_content_block.cpython-310.pyc,, +openai/types/beta/threads/__pycache__/image_url_content_block_param.cpython-310.pyc,, +openai/types/beta/threads/__pycache__/image_url_delta.cpython-310.pyc,, +openai/types/beta/threads/__pycache__/image_url_delta_block.cpython-310.pyc,, +openai/types/beta/threads/__pycache__/image_url_param.cpython-310.pyc,, +openai/types/beta/threads/__pycache__/message.cpython-310.pyc,, +openai/types/beta/threads/__pycache__/message_content.cpython-310.pyc,, +openai/types/beta/threads/__pycache__/message_content_delta.cpython-310.pyc,, +openai/types/beta/threads/__pycache__/message_content_part_param.cpython-310.pyc,, +openai/types/beta/threads/__pycache__/message_create_params.cpython-310.pyc,, +openai/types/beta/threads/__pycache__/message_deleted.cpython-310.pyc,, +openai/types/beta/threads/__pycache__/message_delta.cpython-310.pyc,, +openai/types/beta/threads/__pycache__/message_delta_event.cpython-310.pyc,, +openai/types/beta/threads/__pycache__/message_list_params.cpython-310.pyc,, +openai/types/beta/threads/__pycache__/message_update_params.cpython-310.pyc,, +openai/types/beta/threads/__pycache__/refusal_content_block.cpython-310.pyc,, +openai/types/beta/threads/__pycache__/refusal_delta_block.cpython-310.pyc,, +openai/types/beta/threads/__pycache__/required_action_function_tool_call.cpython-310.pyc,, +openai/types/beta/threads/__pycache__/run.cpython-310.pyc,, +openai/types/beta/threads/__pycache__/run_create_params.cpython-310.pyc,, +openai/types/beta/threads/__pycache__/run_list_params.cpython-310.pyc,, +openai/types/beta/threads/__pycache__/run_status.cpython-310.pyc,, +openai/types/beta/threads/__pycache__/run_submit_tool_outputs_params.cpython-310.pyc,, +openai/types/beta/threads/__pycache__/run_update_params.cpython-310.pyc,, +openai/types/beta/threads/__pycache__/text.cpython-310.pyc,, +openai/types/beta/threads/__pycache__/text_content_block.cpython-310.pyc,, +openai/types/beta/threads/__pycache__/text_content_block_param.cpython-310.pyc,, +openai/types/beta/threads/__pycache__/text_delta.cpython-310.pyc,, +openai/types/beta/threads/__pycache__/text_delta_block.cpython-310.pyc,, +openai/types/beta/threads/annotation.py,sha256=Ce3Y0mSodmYRkoqyhtyIdep6WfWew6KJJgtrENOnfek,462 +openai/types/beta/threads/annotation_delta.py,sha256=iNsE-1Gn1yU0TlTHoxqKbOvPRUxWuXsF72qY_mMnWGY,510 +openai/types/beta/threads/file_citation_annotation.py,sha256=BNpkIVngBZKLi8Db-yrJP52Kz4Q3z4Zv4JPjGsyxHqo,819 +openai/types/beta/threads/file_citation_delta_annotation.py,sha256=1of3IGGzEDTclj2uYID5rS4yZeymFRuzYKmIKfr5aO0,1097 +openai/types/beta/threads/file_path_annotation.py,sha256=1bI1P-utzhQMbNWPKFFCM5ELMH82qrJ1WsqErmrjhB0,681 +openai/types/beta/threads/file_path_delta_annotation.py,sha256=jhEbT7AinewxqTDiBdriy9KIc085VV2HjUpsVUwFHIM,884 +openai/types/beta/threads/image_file.py,sha256=QVXLiplb-CigZqdMZtXlmebXKt6tF74kI-3vHxe_qUE,707 +openai/types/beta/threads/image_file_content_block.py,sha256=f2QUOVbfBCakboLwIf416C2LOR-Tz4KT5AZf6vbE32A,494 +openai/types/beta/threads/image_file_content_block_param.py,sha256=ErMMN4cM5D1fac1kBsrKtDRc3mUFD64qnaFhLPaAIBc,576 +openai/types/beta/threads/image_file_delta.py,sha256=nUJoSuP-3YyqqwBsmPJ0AqiQydz2FymVDCXQVkNYwOk,734 +openai/types/beta/threads/image_file_delta_block.py,sha256=G6UI6p4Cl0HLph3tXHU2uxA5PsEdfPyVN93nrOzFDw8,623 +openai/types/beta/threads/image_file_param.py,sha256=BaKD31JPxQ5CjRfZ_0RcOG3lDTZeW_k85XCvwyctD54,717 +openai/types/beta/threads/image_url.py,sha256=EzEK-CYoO0YyqFmejIPu7pMfTEgMmp5NFscsRd2pCos,592 +openai/types/beta/threads/image_url_content_block.py,sha256=AhYYI0pe55gEKM8FQT7jr7Z02NueszB7pvzLV_FuXdA,429 +openai/types/beta/threads/image_url_content_block_param.py,sha256=XBPXiRqqLAkAnK5H6zKiZ9v5eQ4IOcEctsdQn0P6ikI,511 +openai/types/beta/threads/image_url_delta.py,sha256=MXCp-OmuNT4njbWA9DWAbocP7pD3VpdcUy2wgeOjwm4,582 +openai/types/beta/threads/image_url_delta_block.py,sha256=7ufBlfrXXY8ACIi8M_u-ytH-4ZXew_ytKbwf__z-cLg,548 +openai/types/beta/threads/image_url_param.py,sha256=VRLaxZf-wxnvAOcKGwyF_o6KEvwktBfE3B6KmYE5LZo,602 +openai/types/beta/threads/message.py,sha256=0Xt_yrqhmLhVoDXRbW0YeXJx9BtlLjX8MNPG-B-ySyg,3613 +openai/types/beta/threads/message_content.py,sha256=b8IC_EG28hcXk28z09EABfJwPkYZ7U-lTp_9ykdoxvU,630 +openai/types/beta/threads/message_content_delta.py,sha256=o4Edlx9BtdH2Z4OMwGWWXex8wiijknNRihJ-wu8PDUQ,615 +openai/types/beta/threads/message_content_part_param.py,sha256=RXrnoDP2-UMQHoR2jJvaT3JHrCeffLi6WzXzH05cDGI,550 +openai/types/beta/threads/message_create_params.py,sha256=7fXlNyqy7tzuLgMsCYfJegL2sZcjKwYNLihwteODyg0,2083 +openai/types/beta/threads/message_deleted.py,sha256=DNnrSfGZ3kWEazmo4mVTdLhiKlIHxs-D8Ef5sNdHY1o,303 +openai/types/beta/threads/message_delta.py,sha256=1lh0FTbyqpcLVL8XqwTiAkZy03teJYIAYm_Zj8dbnY8,647 +openai/types/beta/threads/message_delta_event.py,sha256=Rg7g-1taxc2vTowD1J8ykXXRBeQJeTmTxxkZ8e95r1U,682 +openai/types/beta/threads/message_list_params.py,sha256=iuwzDccnViooUxHlq-WoE1FEJArNy5-zrYCoaNgVS8k,1296 +openai/types/beta/threads/message_update_params.py,sha256=XNCSLfRkk531F8mNbUB9bRYcCzJfW8NiFQ9c0Aq75Dk,757 +openai/types/beta/threads/refusal_content_block.py,sha256=C5ORJo34aPdqi-7rviVDUnzi6nneUersczpNM7KPDds,369 +openai/types/beta/threads/refusal_delta_block.py,sha256=F2EWI_H7aUpySDO2xhZTMkICMj1aaM-XwXMzsx7Klhg,481 +openai/types/beta/threads/required_action_function_tool_call.py,sha256=1RWejiSE3wAM7bXWB5q3H_bVkRX2SKXwQ09SEJHOM98,953 +openai/types/beta/threads/run.py,sha256=MLn7qaAPJLijjQ3D-M0ftrbRD4WEQdzDMHC0XPSJcpU,9141 +openai/types/beta/threads/run_create_params.py,sha256=WdjVbHlKhCh2g7uIh-_9YyY8t29UKHk0hd_LHSTKKo8,10956 +openai/types/beta/threads/run_list_params.py,sha256=TgepSLrupUUtuQV2kbVcoGH1YA0FVUX9ESkszKuwyHY,1210 +openai/types/beta/threads/run_status.py,sha256=OU1hzoyYXaRJ3lupX4YcZ-HZkTpctNE4tzAcp6X8Q9U,351 +openai/types/beta/threads/run_submit_tool_outputs_params.py,sha256=cKiyD374BsZN_Oih5o5n5gOf_DYsxErVrbgxveNhmPI,1643 +openai/types/beta/threads/run_update_params.py,sha256=sVjkl6ayjU75Tk8t69r6xgIg80OlTikyRdS0sa2Gavg,749 +openai/types/beta/threads/runs/__init__.py,sha256=mg_roY9yL1bClJ8isizkQgHOAkN17iSdVr2m65iyBrs,1653 +openai/types/beta/threads/runs/__pycache__/__init__.cpython-310.pyc,, +openai/types/beta/threads/runs/__pycache__/code_interpreter_logs.cpython-310.pyc,, +openai/types/beta/threads/runs/__pycache__/code_interpreter_output_image.cpython-310.pyc,, +openai/types/beta/threads/runs/__pycache__/code_interpreter_tool_call.cpython-310.pyc,, +openai/types/beta/threads/runs/__pycache__/code_interpreter_tool_call_delta.cpython-310.pyc,, +openai/types/beta/threads/runs/__pycache__/file_search_tool_call.cpython-310.pyc,, +openai/types/beta/threads/runs/__pycache__/file_search_tool_call_delta.cpython-310.pyc,, +openai/types/beta/threads/runs/__pycache__/function_tool_call.cpython-310.pyc,, +openai/types/beta/threads/runs/__pycache__/function_tool_call_delta.cpython-310.pyc,, +openai/types/beta/threads/runs/__pycache__/message_creation_step_details.cpython-310.pyc,, +openai/types/beta/threads/runs/__pycache__/run_step.cpython-310.pyc,, +openai/types/beta/threads/runs/__pycache__/run_step_delta.cpython-310.pyc,, +openai/types/beta/threads/runs/__pycache__/run_step_delta_event.cpython-310.pyc,, +openai/types/beta/threads/runs/__pycache__/run_step_delta_message_delta.cpython-310.pyc,, +openai/types/beta/threads/runs/__pycache__/run_step_include.cpython-310.pyc,, +openai/types/beta/threads/runs/__pycache__/step_list_params.cpython-310.pyc,, +openai/types/beta/threads/runs/__pycache__/step_retrieve_params.cpython-310.pyc,, +openai/types/beta/threads/runs/__pycache__/tool_call.cpython-310.pyc,, +openai/types/beta/threads/runs/__pycache__/tool_call_delta.cpython-310.pyc,, +openai/types/beta/threads/runs/__pycache__/tool_call_delta_object.cpython-310.pyc,, +openai/types/beta/threads/runs/__pycache__/tool_calls_step_details.cpython-310.pyc,, +openai/types/beta/threads/runs/code_interpreter_logs.py,sha256=UhfSrLKN3NSIOTYGCZhJCv1s_d_8_gTdppFIbBPdgSk,564 +openai/types/beta/threads/runs/code_interpreter_output_image.py,sha256=8o99k0ZHMHpqH0taXkOkYR9WaDUpCN-G0Ifd5XsJpb8,613 +openai/types/beta/threads/runs/code_interpreter_tool_call.py,sha256=u8htH0HfF8Yxc4cBOr6QgBSS1Q465rKz5z0L0bYBz-s,2029 +openai/types/beta/threads/runs/code_interpreter_tool_call_delta.py,sha256=qGBFdfYB0GUWNJpfvh_x387zCUxLrkQtSSOL9EV4K0g,1616 +openai/types/beta/threads/runs/file_search_tool_call.py,sha256=6R27ipmR0J4qc8qjBak00Leov8L_zWLNP6tplXLcfgY,2127 +openai/types/beta/threads/runs/file_search_tool_call_delta.py,sha256=Gx8c7GSgGYuOvGadcAr3ZIspEFMZS3e2OY7vBo_MYnM,655 +openai/types/beta/threads/runs/function_tool_call.py,sha256=V0-x41j1lAY_JBZ0jzd7olIY8HN-IPzzLz_oYTIgb30,979 +openai/types/beta/threads/runs/function_tool_call_delta.py,sha256=DxCHC0yHmryCfkwon1z5LMV-hGaBwacMoP74Pzwed0s,1135 +openai/types/beta/threads/runs/message_creation_step_details.py,sha256=Bfeq7HnLcQjHer0zen013YuU087_ZEitbEurEQS6xds,566 +openai/types/beta/threads/runs/run_step.py,sha256=oU0Rj1XfidZWiWZnY_koSBI56vnoRciMEDQC-sMLeLw,3882 +openai/types/beta/threads/runs/run_step_delta.py,sha256=YpcPvXnwBvlp6tlMhcWGGjCgNsKfiOJVzGhs-tyKe2U,741 +openai/types/beta/threads/runs/run_step_delta_event.py,sha256=f21Eb0e9Syf938ehZM2lh_tzy_T7CVpJTIOQoW35jfs,690 +openai/types/beta/threads/runs/run_step_delta_message_delta.py,sha256=JCbaG1UIrVT1mDtjgdVw4vD68dQkzst5eSjuTqdX_vE,624 +openai/types/beta/threads/runs/run_step_include.py,sha256=u-9Cw1hruRiWr70f_hw4XG0w1cwOAYfRJYKva2dEacs,264 +openai/types/beta/threads/runs/step_list_params.py,sha256=zorF5juogCzLMsZLjzMZTs_iIBcPj9WUur5HcrXuH8M,1752 +openai/types/beta/threads/runs/step_retrieve_params.py,sha256=aJ7l8RDJLPyEmqjfO4XsTV54VZOOqyb_gKSUvqp33ZI,815 +openai/types/beta/threads/runs/tool_call.py,sha256=1rwq4IbLgjQAQ-ORXYkNpmJyi9SREDnqA57nJbj_NiU,537 +openai/types/beta/threads/runs/tool_call_delta.py,sha256=t5wF8ndW3z99lHF981FL-IN5xXBS9p7eonH9bxvKu_c,600 +openai/types/beta/threads/runs/tool_call_delta_object.py,sha256=GsemUuIbB-0arodq5YBBqJjH4LtrGWXi8Fql4-v3f9c,652 +openai/types/beta/threads/runs/tool_calls_step_details.py,sha256=gpNk7AUCm3ND1z2O2ETSZiXqXqkhHpZ2GzxzXAuQXTs,611 +openai/types/beta/threads/text.py,sha256=9gjmDCqoptnxQ8Jhym87pECyd6m1lB3daCxKNzSFp4Y,319 +openai/types/beta/threads/text_content_block.py,sha256=sE7JQpaQDPFfnDRegY8rOqem1vhaL4GOologyT8FenU,374 +openai/types/beta/threads/text_content_block_param.py,sha256=PQ8yKhUp2REWA5opa-83JCYmCCjppkt72sMX57Ys_Ms,462 +openai/types/beta/threads/text_delta.py,sha256=2EFeQCkg_cc8nYEJ6BtYAA3_TqgMTbmEXoMvLjzaB34,389 +openai/types/beta/threads/text_delta_block.py,sha256=cyGoOBssDwxWn0YDKx8p665-v4AB9M3TWZUfgXgT_MM,503 +openai/types/chat/__init__.py,sha256=wyA0EWb0utj19dX0tCeGh4Jg5GrO3TGjmfQkR9HVxxE,6102 +openai/types/chat/__pycache__/__init__.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_allowed_tool_choice_param.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_allowed_tools_param.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_assistant_message_param.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_audio.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_audio_param.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_chunk.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_content_part_image.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_content_part_image_param.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_content_part_input_audio_param.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_content_part_param.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_content_part_refusal_param.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_content_part_text.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_content_part_text_param.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_custom_tool_param.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_deleted.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_developer_message_param.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_function_call_option_param.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_function_message_param.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_function_tool.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_function_tool_param.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_message.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_message_custom_tool_call.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_message_custom_tool_call_param.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_message_function_tool_call.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_message_function_tool_call_param.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_message_param.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_message_tool_call.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_message_tool_call_param.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_message_tool_call_union_param.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_modality.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_named_tool_choice_custom_param.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_named_tool_choice_param.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_prediction_content_param.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_reasoning_effort.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_role.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_store_message.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_stream_options_param.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_system_message_param.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_token_logprob.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_tool_choice_option_param.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_tool_message_param.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_tool_param.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_tool_union_param.cpython-310.pyc,, +openai/types/chat/__pycache__/chat_completion_user_message_param.cpython-310.pyc,, +openai/types/chat/__pycache__/completion_create_params.cpython-310.pyc,, +openai/types/chat/__pycache__/completion_list_params.cpython-310.pyc,, +openai/types/chat/__pycache__/completion_update_params.cpython-310.pyc,, +openai/types/chat/__pycache__/parsed_chat_completion.cpython-310.pyc,, +openai/types/chat/__pycache__/parsed_function_tool_call.cpython-310.pyc,, +openai/types/chat/chat_completion.py,sha256=rPTJBRPwYAvISXFRhupNZjBZtr6UEHRgIWBJkgJQj3o,3650 +openai/types/chat/chat_completion_allowed_tool_choice_param.py,sha256=iBicIuMGQ8vj-LNdat4huVSoalJuWfG3d4qzFyomOK8,713 +openai/types/chat/chat_completion_allowed_tools_param.py,sha256=Ya6LVup7cF69D0_vs-Xfk74L40i6_mz_0JSxVNxPpF0,1087 +openai/types/chat/chat_completion_assistant_message_param.py,sha256=TxOgyqhTYK5Q5pusSKqgEE1qqjkprbUZb9zuzHBASI0,2797 +openai/types/chat/chat_completion_audio.py,sha256=wOZxqzRU4G8TEm5e1syagWtILAEvgIY_Zyo-7MEktGY,851 +openai/types/chat/chat_completion_audio_param.py,sha256=EiYmoyjugmbx7zvN1QNFLvh5UxGPzLuIHnOXUfcm0Yo,1333 +openai/types/chat/chat_completion_chunk.py,sha256=rq8dljAql3jIRC10Qc9h0kBuKhb_Ju7DXBw6CWM3onA,6498 +openai/types/chat/chat_completion_content_part_image.py,sha256=9OD-MwO3od5471z5Il_w6EEunuuOAkKQQo25438KKyU,840 +openai/types/chat/chat_completion_content_part_image_param.py,sha256=U_HLJUD9WlpBuoX6Jg3YmS6MXdQG4ZWAbSonTNYLidM,884 +openai/types/chat/chat_completion_content_part_input_audio_param.py,sha256=0m6GBd4EPLddC29tkmB6kNfYNCqIyqzqi7FoNflc-gI,790 +openai/types/chat/chat_completion_content_part_param.py,sha256=J5ZhUW-SZvuEsKPGUytYLuEUdKgcdfQ68j5IJi6vvVk,1373 +openai/types/chat/chat_completion_content_part_refusal_param.py,sha256=TV1vu-IgrvKa5IBlPSIdBxUaW8g1zDhMOOBOEmhU2w0,467 +openai/types/chat/chat_completion_content_part_text.py,sha256=qgeE0bvOzD_BE4BdvEuFjBj1kWF74RhYQD7eSk7VCo8,468 +openai/types/chat/chat_completion_content_part_text_param.py,sha256=OR0mct4BbfJnDw6PAShySI8CsDxKBtr3wMwowJph40w,534 +openai/types/chat/chat_completion_custom_tool_param.py,sha256=5IU-XnMLDcCHleEjPebg6tNiY9gXvrKaH_hyQhkW-bk,1867 +openai/types/chat/chat_completion_deleted.py,sha256=O7oRuPI6YDa_h7uKnEubsjtw8raTcyVmVk95hoDfo74,470 +openai/types/chat/chat_completion_developer_message_param.py,sha256=XkL5kaXoSeAlvBMr7etkm1Ony6Z26gNakwfS3ch2Hq8,1049 +openai/types/chat/chat_completion_function_call_option_param.py,sha256=_Lii1uFcSbXO0blmJn3VHkYXuXKO2cRT-Z-JikD2mrA,489 +openai/types/chat/chat_completion_function_message_param.py,sha256=jIaZbBHHbt4v4xHCIyvYtYLst_X4jOznRjYNcTf0MF0,591 +openai/types/chat/chat_completion_function_tool.py,sha256=IGZSLdIbxJFgF-P0DTZeEanGFcf5iUdj5sAYd-6EbRI,513 +openai/types/chat/chat_completion_function_tool_param.py,sha256=085qkwOGKX3M-Laf66N3KBfalXbUQb3lp76wWRi68B8,587 +openai/types/chat/chat_completion_message.py,sha256=xtsA62BEMKI-06xRbiZo-ljpyq0FtHEsgr8BXJ1AqsM,2829 +openai/types/chat/chat_completion_message_custom_tool_call.py,sha256=dGX_nKX-qj4Yup44mov1rFPGPxhfarHf17wGHE4jB4g,750 +openai/types/chat/chat_completion_message_custom_tool_call_param.py,sha256=A2d2BTzl1-XrXhWmLyAPdqzwzQwTLfaA_M9ObIpIJeE,859 +openai/types/chat/chat_completion_message_function_tool_call.py,sha256=2kd0tKE_NUfvsR4nep1yap7D0TRzzD9yuSvn5wcyouo,1022 +openai/types/chat/chat_completion_message_function_tool_call_param.py,sha256=6FjTlBTsoFFBGcF2fFs6Uq3CoAnvY-9Jvs4dxHlepqY,1131 +openai/types/chat/chat_completion_message_param.py,sha256=aLrz_cX_CYymFdW9cMIPZpv0Z4zM50RECV3SH6QNZsc,1019 +openai/types/chat/chat_completion_message_tool_call.py,sha256=aWpKcV6NZZfx_-aGEwPz99IDWNCdRuwoYpUChs0Uvvc,738 +openai/types/chat/chat_completion_message_tool_call_param.py,sha256=rE_TbdN3N6JGzHecykgdFHZgI66p2lsl0loPpz5TxW0,458 +openai/types/chat/chat_completion_message_tool_call_union_param.py,sha256=L8IoSHXgIFxYyHSfXQJNN7FJlp31ez8X4l5eSPKGmYM,602 +openai/types/chat/chat_completion_modality.py,sha256=8Ga0kruwJc43WD2OIqNudn7KrVRTPDQaalVkh_8bp9I,236 +openai/types/chat/chat_completion_named_tool_choice_custom_param.py,sha256=yxPaDdBK71bQ4vHu-a4nSbvNLdxuOoT8utOJcCK9Ja4,680 +openai/types/chat/chat_completion_named_tool_choice_param.py,sha256=z8G5YhuzuTQwUGmRWu2jK5BDeJW5cuY14rpOa9DTJ6c,671 +openai/types/chat/chat_completion_prediction_content_param.py,sha256=7jK3nMFFPbxLx6-F6Y7u2kBygDm4IQbtEej5BeQ5KBg,988 +openai/types/chat/chat_completion_reasoning_effort.py,sha256=9sAGlM21dgRNOQRSsL_znZf9ruXcmvVriWeex0fRgMk,235 +openai/types/chat/chat_completion_role.py,sha256=LW6-tqXaqpD7H53PiSXrjvIo6g4RfHhWityDm6Nfvig,275 +openai/types/chat/chat_completion_store_message.py,sha256=JUcit8AUnUzrEJIokS15nssCZ_7g-dcEeXE9Fejb6Sg,977 +openai/types/chat/chat_completion_stream_options_param.py,sha256=pwt3pqOZNIzmeESTT2hzouRCNJ5cQHRZ1ZQ1as2vzSg,1397 +openai/types/chat/chat_completion_system_message_param.py,sha256=14_Nq02KOYn6bd9BYJ1pzUPcYG8lOZCuDFNcyrfiEZw,1024 +openai/types/chat/chat_completion_token_logprob.py,sha256=ALerVs0mCWavq4JuNE_pFehVNbD5LQTX56RD9_Zf1qA,1747 +openai/types/chat/chat_completion_tool_choice_option_param.py,sha256=wPIjU-eeybPjRFr28mx8Njp2OCrKw3Xpu0231z4Kz1A,758 +openai/types/chat/chat_completion_tool_message_param.py,sha256=5K7jfKpwTuKNi1PTFabq_LHH-7wun8CUsLDh90U8zQE,730 +openai/types/chat/chat_completion_tool_param.py,sha256=5hFt0Izat_o50JMJzspCYeB0gubilRDB3a6yIfGHoN8,431 +openai/types/chat/chat_completion_tool_union_param.py,sha256=smpIoekwuuXKQx9jRRB2cqc3L7_fmN5lB4IIJHlKhys,504 +openai/types/chat/chat_completion_user_message_param.py,sha256=znqcR_CPZX8YxQpFq1xNQISVR3dM8hj5rjN33b00KHo,901 +openai/types/chat/completion_create_params.py,sha256=Ag1nboIdsXDD9KF5mozrec6iL2Nk2MuXSjmysxHX__4,18563 +openai/types/chat/completion_list_params.py,sha256=QBKLa941_4fU2PAT2uLImYIfPZj-WdTqqpsy0vQ1b0c,931 +openai/types/chat/completion_update_params.py,sha256=VRDF28qoonjrveHhw8BT4Yo_NlLsV2Qzd_KUUQ6AEG8,742 +openai/types/chat/completions/__init__.py,sha256=nmKlohYbZmr7Pzv1qCDMSDbthcH6ySPFIgvXpHZtxK8,195 +openai/types/chat/completions/__pycache__/__init__.cpython-310.pyc,, +openai/types/chat/completions/__pycache__/message_list_params.cpython-310.pyc,, +openai/types/chat/completions/message_list_params.py,sha256=IArlye40xGlMVIDHxsK9RX_5usPL71wXPMgdwI7_wYU,583 +openai/types/chat/parsed_chat_completion.py,sha256=KwcwCtj0yexl6gB7yuOnyETRW-uUvNRYbVzPMkwCe5Q,1437 +openai/types/chat/parsed_function_tool_call.py,sha256=JDWYo1XhTDQ8CxssbgjpzBhUw8jeXAmEd5Tr_CqFrVA,945 +openai/types/chat_model.py,sha256=yFvzwm6VJXCn6jN21FS-utN6bcBBzRIpKYk1VTP8sdo,177 +openai/types/completion.py,sha256=mwIFVtTYVKOmvIQJz6M6jQS1r48_rvbVvOztDp0C9Wo,1347 +openai/types/completion_choice.py,sha256=PUk77T3Cp34UJSXoMfSzTKGWDK0rQQwq84X_PSlOUJo,965 +openai/types/completion_create_params.py,sha256=UqgYjUpYbQYPdYETVxhkwgbGRKTQCBoyeSFtrB8iuAo,7652 +openai/types/completion_usage.py,sha256=siq8f0jlCP3GYFHQr8Zzflf-BYxOggE_OjtsGs9ur4A,1895 +openai/types/container_create_params.py,sha256=hKLUqHR3O8P3ovPRAHSf8F9ksdg8mzzyYKxX4SDalSw,1771 +openai/types/container_create_response.py,sha256=u6CGmXJGKQN2dL7m2aBjSxf5u3E2qTI8JQAd-3CGMu4,1991 +openai/types/container_list_params.py,sha256=nT4iLO9FdooggoR867JNy0ycb0RnUvwhz-giYo9mos8,952 +openai/types/container_list_response.py,sha256=m5lCUUSEArG02a7ex8xW1AZTgljTAjkEGHz54cX31IY,1987 +openai/types/container_retrieve_response.py,sha256=zSR77D4CoWLSGpbRecWxSIcjctW0fjB-51J4KdZC2pU,1995 +openai/types/containers/__init__.py,sha256=SCdMa4GNxw-I23CwW03iVOoHRfDybyKEMmpDkdVuUcI,480 +openai/types/containers/__pycache__/__init__.cpython-310.pyc,, +openai/types/containers/__pycache__/file_create_params.cpython-310.pyc,, +openai/types/containers/__pycache__/file_create_response.cpython-310.pyc,, +openai/types/containers/__pycache__/file_list_params.cpython-310.pyc,, +openai/types/containers/__pycache__/file_list_response.cpython-310.pyc,, +openai/types/containers/__pycache__/file_retrieve_response.cpython-310.pyc,, +openai/types/containers/file_create_params.py,sha256=KXoZNG4DpiD7NDeQixdKJsuOv-iCZAlSN4sz7AQm49k,412 +openai/types/containers/file_create_response.py,sha256=Dh1OWf86XNMfmvVwfRGezfihdDuuAcdiQxT_3iefBzw,722 +openai/types/containers/file_list_params.py,sha256=9bU7uKeXPk7adFzwvKHFitFOV4phnIbbfFx5u6n1OFY,883 +openai/types/containers/file_list_response.py,sha256=xwvdMIUafkHSXJGQT1_mxt6T_8nJo-isp9M_5YTq-J8,718 +openai/types/containers/file_retrieve_response.py,sha256=wGPU9o5SKkg8s4aUJXhwC38u8KfTFKmIUk1ItUdYxJg,726 +openai/types/containers/files/__init__.py,sha256=OKfJYcKb4NObdiRObqJV_dOyDQ8feXekDUge2o_4pXQ,122 +openai/types/containers/files/__pycache__/__init__.cpython-310.pyc,, +openai/types/conversations/__init__.py,sha256=N7GRumNq1KeGR4X9STSKWLM1axUntyaMI_OwPihZmjI,1854 +openai/types/conversations/__pycache__/__init__.cpython-310.pyc,, +openai/types/conversations/__pycache__/computer_screenshot_content.cpython-310.pyc,, +openai/types/conversations/__pycache__/conversation.cpython-310.pyc,, +openai/types/conversations/__pycache__/conversation_create_params.cpython-310.pyc,, +openai/types/conversations/__pycache__/conversation_deleted_resource.cpython-310.pyc,, +openai/types/conversations/__pycache__/conversation_item.cpython-310.pyc,, +openai/types/conversations/__pycache__/conversation_item_list.cpython-310.pyc,, +openai/types/conversations/__pycache__/conversation_update_params.cpython-310.pyc,, +openai/types/conversations/__pycache__/input_file_content.cpython-310.pyc,, +openai/types/conversations/__pycache__/input_file_content_param.cpython-310.pyc,, +openai/types/conversations/__pycache__/input_image_content.cpython-310.pyc,, +openai/types/conversations/__pycache__/input_image_content_param.cpython-310.pyc,, +openai/types/conversations/__pycache__/input_text_content.cpython-310.pyc,, +openai/types/conversations/__pycache__/input_text_content_param.cpython-310.pyc,, +openai/types/conversations/__pycache__/item_create_params.cpython-310.pyc,, +openai/types/conversations/__pycache__/item_list_params.cpython-310.pyc,, +openai/types/conversations/__pycache__/item_retrieve_params.cpython-310.pyc,, +openai/types/conversations/__pycache__/message.cpython-310.pyc,, +openai/types/conversations/__pycache__/output_text_content.cpython-310.pyc,, +openai/types/conversations/__pycache__/output_text_content_param.cpython-310.pyc,, +openai/types/conversations/__pycache__/refusal_content.cpython-310.pyc,, +openai/types/conversations/__pycache__/refusal_content_param.cpython-310.pyc,, +openai/types/conversations/__pycache__/summary_text_content.cpython-310.pyc,, +openai/types/conversations/__pycache__/text_content.cpython-310.pyc,, +openai/types/conversations/computer_screenshot_content.py,sha256=hhFabvZFNyIiTvAnoxPMVmI6Y1TBHhzN_4miuIgieK8,878 +openai/types/conversations/conversation.py,sha256=BVpec4hLHle_8iRf6v5y4CPYHtMhEntP0m8PDG_5GSY,886 +openai/types/conversations/conversation_create_params.py,sha256=dtgIXlZj1yKP3oJUYdFCb2MKIk6BH8e4QbKIPPGjHf8,976 +openai/types/conversations/conversation_deleted_resource.py,sha256=HagMTsOrDL7QYQSeZqMbBMfRzhWAgnrxtinGT5uhog4,326 +openai/types/conversations/conversation_item.py,sha256=LlKb4MEg1hlnCu_bxM7SQpR9L9DVrg_u91XJk7acpAI,8005 +openai/types/conversations/conversation_item_list.py,sha256=bFXSZFmB1H9-IwjDRTCGtszxt57B3RAbHGZaL08gcYA,708 +openai/types/conversations/conversation_update_params.py,sha256=YMyThjw2ObnqY-dhI4iy2pqf0cZW7rNV0TcxpBMs1bs,746 +openai/types/conversations/input_file_content.py,sha256=xxG8_PMhnjH1F6jXs6vZyj_T1HdO--48fTYFrvWCPzk,219 +openai/types/conversations/input_file_content_param.py,sha256=ATFOU1VRdw8SDRvwdC1KEamfAMna-mIfpER5bLpGIeg,244 +openai/types/conversations/input_image_content.py,sha256=LKKWx1y5Gi0nu34a8CFbDUaXUWQACeQ80lwJtukOx3U,224 +openai/types/conversations/input_image_content_param.py,sha256=AceRCBW-WuXG5rI4uDF2w0n_eaa8DzpCmbdWm3ofVMg,248 +openai/types/conversations/input_text_content.py,sha256=G5L4ln3tkWqSzaZlAkFuzkFOpjYqPVnE3QyXafiA6YU,219 +openai/types/conversations/input_text_content_param.py,sha256=HPl92LQHoA3_2azNJcVF1FD6OTJY200uwbCodF7_xPg,244 +openai/types/conversations/item_create_params.py,sha256=TRAsvDuMBjLeL5DzqC-WyqmorZTnu4qZRt9eE13SJ8E,874 +openai/types/conversations/item_list_params.py,sha256=nMzeK_XkVTWsa5pMQDGDuRPfGwiXFBDcdZ4NYwYV7H4,1896 +openai/types/conversations/item_retrieve_params.py,sha256=lHK-Sqbd7DXWQKuXGRBUvu_a7LxYNAT_tBQqLP-OC5A,690 +openai/types/conversations/message.py,sha256=P1bCl2hwjbbvi0_JUPN4YQe-2QKsyL15_xF_a_1mUUg,2535 +openai/types/conversations/output_text_content.py,sha256=bFDVfODBGMwRLcKeo0OZzZumZdZwHzHkG1B_Bw43vWA,224 +openai/types/conversations/output_text_content_param.py,sha256=8NlazI-VuJ9DgQ-ZGt9xJ8su2-CZ1mb_ebI9O19YC7Q,248 +openai/types/conversations/refusal_content.py,sha256=ThoHeemlqaKlUf7oVYOTUwnHuqph-4RXS4Ud_kGbGg0,227 +openai/types/conversations/refusal_content_param.py,sha256=hWb2AoU0oTKCNLRZs5kzxY2Uk7HkeHhEy5leL29Uy64,254 +openai/types/conversations/summary_text_content.py,sha256=TuGepAPiMlauu9CdEwkQdkLwErBjx6kNXlIG-CSb-4g,447 +openai/types/conversations/text_content.py,sha256=eya3kB6nXl0KEGlvpH_LlE8CIPzD5GVg5r851-oWR0g,286 +openai/types/create_embedding_response.py,sha256=S_HDPpkr_2us12j1M8NsXTrTg6RJT2rgI3zAsZpMSZg,848 +openai/types/deleted_skill.py,sha256=S2SZKHQIla9-2lwbtYtVao5eIeH9936pn-PDHXBGrGw,288 +openai/types/embedding.py,sha256=PDZAZRp7mzlvz5R2FMMf50vRIphHNCgyST2gbo2NdA4,711 +openai/types/embedding_create_params.py,sha256=asahWWNcMvXGDfbTMz4uDy7DU9g6OJ9wowqZByghzw8,2039 +openai/types/embedding_model.py,sha256=0dDL87len4vZ4DR6eCp7JZJCJpgwWphRmJhMK3Se8f4,281 +openai/types/eval_create_params.py,sha256=QW52PWt7EhyNdYJ976ZpZiAolzoFdfa7zoXPUZWj4lc,8239 +openai/types/eval_create_response.py,sha256=MRZlHRJrtyGS5JN3GLR6UzjTa3Fjt0v-cGFAaGD4wHE,4468 +openai/types/eval_custom_data_source_config.py,sha256=XmGu1MzqE9poFFH65qMpw0W_C89DJdP8cwgpTvNYuPU,876 +openai/types/eval_delete_response.py,sha256=iCMGN0JG5kFIYNPSCOMSWlTu0FDkd2lbAw1VLO73-bQ,245 +openai/types/eval_list_params.py,sha256=WmIJa3O9wyuDKXXwE3tSnQv1XOTe1hngttSvvhbtf28,754 +openai/types/eval_list_response.py,sha256=H35sv5yCN_ROUNb0pBO1RkXHC8kEQMPxEtpMVhJ5MNg,4464 +openai/types/eval_retrieve_response.py,sha256=tOpjCP4ww5XYZrniUh9CphrWaltfTKhTdAXPiEhz3Ts,4472 +openai/types/eval_stored_completions_data_source_config.py,sha256=OGMNipFZes_EaeTi5ediozfUHAeLoTZTISIQRGaQDCI,1137 +openai/types/eval_update_params.py,sha256=Wooz-3SDznbC3ihrhOs-10y9cxpTKGQgobDLfZ-23c0,757 +openai/types/eval_update_response.py,sha256=ZH82tSoBv64c_4VUXKOcGBLJQ6xSersZz8gnGzbvjw8,4468 +openai/types/evals/__init__.py,sha256=wiXRqdkT-SkjE0Sgv6MixeECZjF0xaoCPdSGFEh0rEs,1193 +openai/types/evals/__pycache__/__init__.cpython-310.pyc,, +openai/types/evals/__pycache__/create_eval_completions_run_data_source.cpython-310.pyc,, +openai/types/evals/__pycache__/create_eval_completions_run_data_source_param.cpython-310.pyc,, +openai/types/evals/__pycache__/create_eval_jsonl_run_data_source.cpython-310.pyc,, +openai/types/evals/__pycache__/create_eval_jsonl_run_data_source_param.cpython-310.pyc,, +openai/types/evals/__pycache__/eval_api_error.cpython-310.pyc,, +openai/types/evals/__pycache__/run_cancel_response.cpython-310.pyc,, +openai/types/evals/__pycache__/run_create_params.cpython-310.pyc,, +openai/types/evals/__pycache__/run_create_response.cpython-310.pyc,, +openai/types/evals/__pycache__/run_delete_response.cpython-310.pyc,, +openai/types/evals/__pycache__/run_list_params.cpython-310.pyc,, +openai/types/evals/__pycache__/run_list_response.cpython-310.pyc,, +openai/types/evals/__pycache__/run_retrieve_response.cpython-310.pyc,, +openai/types/evals/create_eval_completions_run_data_source.py,sha256=91mh923L-jJ2AyqzA3dh87hJR0KPDvaKaKr3OuH-4yY,9127 +openai/types/evals/create_eval_completions_run_data_source_param.py,sha256=Qa7TlKjpsJlUkVsxuI8q4pyBgyI-XWQKvQVqOnUIo6c,9210 +openai/types/evals/create_eval_jsonl_run_data_source.py,sha256=4BsR_n4iiFNoQ2-_Y8X0O2BONcSqCNY4Vav4RQPHX78,1323 +openai/types/evals/create_eval_jsonl_run_data_source_param.py,sha256=n0l8GC_RE89kcT4-WUE8tCpoOYbaW18b8XEgXQULqcc,1389 +openai/types/evals/eval_api_error.py,sha256=mBaebr3g8M0-mHtZQAg0QuCj3TDeXHeGLCBsHI5A7mA,339 +openai/types/evals/run_cancel_response.py,sha256=jF_JPZITqR3277nk4bh7ZpJvhZT5-LiL5mWir7YFsT8,15905 +openai/types/evals/run_create_params.py,sha256=caeqpTzX8grnYQ-JNa6iNk3EdosMA63PZT8MPXQbpkY,14849 +openai/types/evals/run_create_response.py,sha256=zh8DTmxlgUFEnUCfmITZuJFevYWSV4bq3GK8VA0bAj4,15905 +openai/types/evals/run_delete_response.py,sha256=WSQpOlZu53eWBCXSRGkthFn_Yz5rDCcSomqoa4HpUrk,323 +openai/types/evals/run_list_params.py,sha256=vgbJMYybzCep7e9rxUVHlWy_o4GNy4tJyGTwNu4n4ys,758 +openai/types/evals/run_list_response.py,sha256=VOCF7XSR3bloPGQR1froYWqmcJpEPb6vjmfzkQsyJ2g,15901 +openai/types/evals/run_retrieve_response.py,sha256=ImzKvC_ZMA_YaesVYfuHm1TZnWQ6-3OkpWZIJFX7qug,15909 +openai/types/evals/runs/__init__.py,sha256=sltNV1VwseIVr09gQ5E4IKbRKJuWJSLY1xUvAuC97Ec,393 +openai/types/evals/runs/__pycache__/__init__.cpython-310.pyc,, +openai/types/evals/runs/__pycache__/output_item_list_params.cpython-310.pyc,, +openai/types/evals/runs/__pycache__/output_item_list_response.cpython-310.pyc,, +openai/types/evals/runs/__pycache__/output_item_retrieve_response.cpython-310.pyc,, +openai/types/evals/runs/output_item_list_params.py,sha256=Lp1OQV1qXeEUwMS90_-BpOnO1jICwJOo9QgNC9OGJ2U,821 +openai/types/evals/runs/output_item_list_response.py,sha256=YWkB3RtLae4hl0xs6gQvllYOcTwViR806LA_W3n9Kyg,4120 +openai/types/evals/runs/output_item_retrieve_response.py,sha256=CG3oTPKn9OOyHMLa3A-EAmo09mb_j2mJz6zw9hJ2C00,4128 +openai/types/file_chunking_strategy.py,sha256=oT5tAbwt3wJsFqSj2sjDPBcisegNwJOecxS_V7M4EdA,559 +openai/types/file_chunking_strategy_param.py,sha256=mOFh18BKAGkzVTrWv_3Iphzbs-EbT6hq-jChCA4HgAE,517 +openai/types/file_content.py,sha256=qLlM4J8kgu1BfrtlmYftPsQVCJu4VqYeiS1T28u8EQ8,184 +openai/types/file_create_params.py,sha256=1QmHtJJdSAwqARQjde2BsDaL-WpFNIjxEnsQXmi-HQE,1584 +openai/types/file_deleted.py,sha256=H_r9U7XthT5xHAo_4ay1EGGkc21eURt8MkkIBRYiQcw,277 +openai/types/file_list_params.py,sha256=TmmqvM7droAJ49YlgpeFzrhPv5uVkSZDxqlG6hhumPo,960 +openai/types/file_object.py,sha256=s0hqehIWHSMHbiIRTrURTi4iiCu2PXmEGrd4tUB8lW8,1589 +openai/types/file_purpose.py,sha256=aNd8G-GC1UVCL9bvTgtL4kfkiF0uEjfiimRS-eh8VrY,265 +openai/types/fine_tuning/__init__.py,sha256=f8GH2rKGcIU1Kjrfjw5J0QoqlsC4jRmH96bU6axGD64,1832 +openai/types/fine_tuning/__pycache__/__init__.cpython-310.pyc,, +openai/types/fine_tuning/__pycache__/dpo_hyperparameters.cpython-310.pyc,, +openai/types/fine_tuning/__pycache__/dpo_hyperparameters_param.cpython-310.pyc,, +openai/types/fine_tuning/__pycache__/dpo_method.cpython-310.pyc,, +openai/types/fine_tuning/__pycache__/dpo_method_param.cpython-310.pyc,, +openai/types/fine_tuning/__pycache__/fine_tuning_job.cpython-310.pyc,, +openai/types/fine_tuning/__pycache__/fine_tuning_job_event.cpython-310.pyc,, +openai/types/fine_tuning/__pycache__/fine_tuning_job_integration.cpython-310.pyc,, +openai/types/fine_tuning/__pycache__/fine_tuning_job_wandb_integration.cpython-310.pyc,, +openai/types/fine_tuning/__pycache__/fine_tuning_job_wandb_integration_object.cpython-310.pyc,, +openai/types/fine_tuning/__pycache__/job_create_params.cpython-310.pyc,, +openai/types/fine_tuning/__pycache__/job_list_events_params.cpython-310.pyc,, +openai/types/fine_tuning/__pycache__/job_list_params.cpython-310.pyc,, +openai/types/fine_tuning/__pycache__/reinforcement_hyperparameters.cpython-310.pyc,, +openai/types/fine_tuning/__pycache__/reinforcement_hyperparameters_param.cpython-310.pyc,, +openai/types/fine_tuning/__pycache__/reinforcement_method.cpython-310.pyc,, +openai/types/fine_tuning/__pycache__/reinforcement_method_param.cpython-310.pyc,, +openai/types/fine_tuning/__pycache__/supervised_hyperparameters.cpython-310.pyc,, +openai/types/fine_tuning/__pycache__/supervised_hyperparameters_param.cpython-310.pyc,, +openai/types/fine_tuning/__pycache__/supervised_method.cpython-310.pyc,, +openai/types/fine_tuning/__pycache__/supervised_method_param.cpython-310.pyc,, +openai/types/fine_tuning/alpha/__init__.py,sha256=e_Evj3xLs7o_SONlqoXDM75oZMbxuGWhxBW-azsXD_w,429 +openai/types/fine_tuning/alpha/__pycache__/__init__.cpython-310.pyc,, +openai/types/fine_tuning/alpha/__pycache__/grader_run_params.cpython-310.pyc,, +openai/types/fine_tuning/alpha/__pycache__/grader_run_response.cpython-310.pyc,, +openai/types/fine_tuning/alpha/__pycache__/grader_validate_params.cpython-310.pyc,, +openai/types/fine_tuning/alpha/__pycache__/grader_validate_response.cpython-310.pyc,, +openai/types/fine_tuning/alpha/grader_run_params.py,sha256=ECVczgghTZ8J9xfqAbNc_VvAHfhOpkaVzQw_wUmE4r8,1414 +openai/types/fine_tuning/alpha/grader_run_response.py,sha256=So-fvQMRvpccsSYb0jfKGQ_MNWdqqS71OcE9GbeLASs,1556 +openai/types/fine_tuning/alpha/grader_validate_params.py,sha256=Jd6m3DjIZAUNY-PlLUWDbH3ojm8ztnfjHmPjKw2DrLM,875 +openai/types/fine_tuning/alpha/grader_validate_response.py,sha256=nLldMLyNG-ICS3HwykDWdKuAPKu4gR2A2I0C79C4khs,773 +openai/types/fine_tuning/checkpoints/__init__.py,sha256=7I1e_nAa8YIuKob-VPOLtlRyUYuPynpUrbGGRN6TUQU,756 +openai/types/fine_tuning/checkpoints/__pycache__/__init__.cpython-310.pyc,, +openai/types/fine_tuning/checkpoints/__pycache__/permission_create_params.cpython-310.pyc,, +openai/types/fine_tuning/checkpoints/__pycache__/permission_create_response.cpython-310.pyc,, +openai/types/fine_tuning/checkpoints/__pycache__/permission_delete_response.cpython-310.pyc,, +openai/types/fine_tuning/checkpoints/__pycache__/permission_list_params.cpython-310.pyc,, +openai/types/fine_tuning/checkpoints/__pycache__/permission_list_response.cpython-310.pyc,, +openai/types/fine_tuning/checkpoints/__pycache__/permission_retrieve_params.cpython-310.pyc,, +openai/types/fine_tuning/checkpoints/__pycache__/permission_retrieve_response.cpython-310.pyc,, +openai/types/fine_tuning/checkpoints/permission_create_params.py,sha256=TI90xY-4dv8vDKKZ0FBdbly9JTCrw4FgXkcXz_gTUlk,407 +openai/types/fine_tuning/checkpoints/permission_create_response.py,sha256=ATIeO4fFBTtaylBYdC6Id-wvirln4lKh2tRLMaJW01Y,751 +openai/types/fine_tuning/checkpoints/permission_delete_response.py,sha256=X_RuOvxa6i3wGLP5joHixv4tNLUpuK-2umiUf6P7Ha8,558 +openai/types/fine_tuning/checkpoints/permission_list_params.py,sha256=5BYaVDcV8LaBk9yBueZD60h1mi1xCmf7WwLZEHh36i4,602 +openai/types/fine_tuning/checkpoints/permission_list_response.py,sha256=ufUBrKKR15VJmz4HSK6m4KSDFqxjASV7USqSxkj0P1Q,747 +openai/types/fine_tuning/checkpoints/permission_retrieve_params.py,sha256=3zVCOq1676MizKhKSba2OLmBSPlBx6Az2ZdxyVl580o,610 +openai/types/fine_tuning/checkpoints/permission_retrieve_response.py,sha256=o8wXyRWH80oA8o80crPkaGDyPIwuQZysRK1ic6mPqj8,963 +openai/types/fine_tuning/dpo_hyperparameters.py,sha256=Kkylxhw94kImWo6-SS_7Jq66nftP0Hy0bbRxtcrChXM,1129 +openai/types/fine_tuning/dpo_hyperparameters_param.py,sha256=mXJJXLhC_6E-7IYqDOlYGTWLLxx5Fs2l4_fmVvRs9RM,1113 +openai/types/fine_tuning/dpo_method.py,sha256=pQVpzKu0WGMQkL1itgY2Wrec85u5QHHROa0FInGdVhw,434 +openai/types/fine_tuning/dpo_method_param.py,sha256=cYBljFPSCtdDoNmyJ4s8OcgU08vCdQK8sxTJ7JX7nEA,471 +openai/types/fine_tuning/fine_tuning_job.py,sha256=DFd9yrwcrh4Jmpjf4HBgUTw7FLu-EkBWmhSkXTyuHS4,5662 +openai/types/fine_tuning/fine_tuning_job_event.py,sha256=T_ESNL8qLk25Z9MHbLqTZtj-nR_LyAS4FHuHTsU-KAI,894 +openai/types/fine_tuning/fine_tuning_job_integration.py,sha256=uNFfuBV87nUHQORNGVLP_HbotooR_e37Bgd0dyZ4nUM,241 +openai/types/fine_tuning/fine_tuning_job_wandb_integration.py,sha256=WUCywzpaj6ZVg_ZZKZxRqt_XS1A22mMasdSGxlOQsbU,1343 +openai/types/fine_tuning/fine_tuning_job_wandb_integration_object.py,sha256=7vEc2uEV2c_DENBjhq0Qy5X8B-rzxsKvGECjnvF1Wdw,804 +openai/types/fine_tuning/job_create_params.py,sha256=-79Le_1QQI0c8W5M1NWLKlmRs9Wt8soE7Y_2wGLfxds,6719 +openai/types/fine_tuning/job_list_events_params.py,sha256=4xOED4H2ky2mI9sIDytjmfJz5bNAdNWb70WIb_0bBWs,400 +openai/types/fine_tuning/job_list_params.py,sha256=wUGXsQ4UDCKvAjHDZAZ-JDU6XAouiTGThb0Jo_9XX08,623 +openai/types/fine_tuning/jobs/__init__.py,sha256=nuWhOUsmsoVKTKMU35kknmr8sfpTF-kkIzyuOlRbJj0,295 +openai/types/fine_tuning/jobs/__pycache__/__init__.cpython-310.pyc,, +openai/types/fine_tuning/jobs/__pycache__/checkpoint_list_params.cpython-310.pyc,, +openai/types/fine_tuning/jobs/__pycache__/fine_tuning_job_checkpoint.cpython-310.pyc,, +openai/types/fine_tuning/jobs/checkpoint_list_params.py,sha256=XoDLkkKCWmf5an5rnoVEpNK8mtQHq1fHw9EqmezfrXM,415 +openai/types/fine_tuning/jobs/fine_tuning_job_checkpoint.py,sha256=UG9keznPmpRFAM4ivkMJ8KlBbojdF3m2bSmiftBCnT8,1548 +openai/types/fine_tuning/reinforcement_hyperparameters.py,sha256=DwLBbYDa4QDJQup7aeg_KUu5wwC4tSLDpp60axNsmC0,1501 +openai/types/fine_tuning/reinforcement_hyperparameters_param.py,sha256=t91X4q0WocQ9PcjGJ8yu1w8vOdPvCFthTD-zrZuCNTs,1432 +openai/types/fine_tuning/reinforcement_method.py,sha256=vKEmXkRWUdd5GeLNxzZsqfQ8kG5GR3EXLCqaXy-DOoM,1025 +openai/types/fine_tuning/reinforcement_method_param.py,sha256=rjE_b2IY7Zkaf6UpMuGNrvizor2mhrUrMC-cZFFDmlQ,1157 +openai/types/fine_tuning/supervised_hyperparameters.py,sha256=Y9h3_iGD5drhkAdMjR4Szb00BZqQ43ka1FFUSgKrzJI,926 +openai/types/fine_tuning/supervised_hyperparameters_param.py,sha256=9nnnvgvHbT-x1adrP2yTBCtU19CGrjcQ5AQvXb2wkZ0,923 +openai/types/fine_tuning/supervised_method.py,sha256=sGXoTMI_r3BN53I7FA45dz_JU9d_7eQlPXHvRSswgfY,472 +openai/types/fine_tuning/supervised_method_param.py,sha256=GKw3VgMuZ6V0B0NKwHh_lrHRSM4gYp0dPBPoamYPze8,509 +openai/types/graders/__init__.py,sha256=y-002SPDfVfefLY1hTugtFHv74beH51tCTXi6dZrCDk,1147 +openai/types/graders/__pycache__/__init__.cpython-310.pyc,, +openai/types/graders/__pycache__/grader_inputs.cpython-310.pyc,, +openai/types/graders/__pycache__/grader_inputs_param.cpython-310.pyc,, +openai/types/graders/__pycache__/label_model_grader.cpython-310.pyc,, +openai/types/graders/__pycache__/label_model_grader_param.cpython-310.pyc,, +openai/types/graders/__pycache__/multi_grader.cpython-310.pyc,, +openai/types/graders/__pycache__/multi_grader_param.cpython-310.pyc,, +openai/types/graders/__pycache__/python_grader.cpython-310.pyc,, +openai/types/graders/__pycache__/python_grader_param.cpython-310.pyc,, +openai/types/graders/__pycache__/score_model_grader.cpython-310.pyc,, +openai/types/graders/__pycache__/score_model_grader_param.cpython-310.pyc,, +openai/types/graders/__pycache__/string_check_grader.cpython-310.pyc,, +openai/types/graders/__pycache__/string_check_grader_param.cpython-310.pyc,, +openai/types/graders/__pycache__/text_similarity_grader.cpython-310.pyc,, +openai/types/graders/__pycache__/text_similarity_grader_param.cpython-310.pyc,, +openai/types/graders/grader_inputs.py,sha256=rboj5sT1i5dwbXH3gGw6NgACSchjECaFeNg9a4Iq4dc,1299 +openai/types/graders/grader_inputs_param.py,sha256=-kXE-BoLSannXeqP0SSdcU9x6ssRu0xxMdgnmffMxCA,1494 +openai/types/graders/label_model_grader.py,sha256=UwzUzamECdsrNpyAnKYfFqTmE_R-ORzIKDIvtJmFCSU,2765 +openai/types/graders/label_model_grader_param.py,sha256=w7tWVs69B7IiM0BzfBEvZ-DKNQqbO-IIZ0csIt-94QI,3061 +openai/types/graders/multi_grader.py,sha256=JULSGQyLMw8aUX35xiKVr_hoqaVn2vkHG2VAjSV0GbI,1127 +openai/types/graders/multi_grader_param.py,sha256=BMnqlkcSYAKjLjjWvqj9FHVUQTFseHvs9MXaX_iDcrc,1300 +openai/types/graders/python_grader.py,sha256=xM2ClJoMlai_VqVDs_7HCwBj7bGwQurq8Y2zsMV2gQU,607 +openai/types/graders/python_grader_param.py,sha256=uNRp2JEkNSdTFDVpo0BcrQ8oyEgLeYodyFzxsT7miWs,638 +openai/types/graders/score_model_grader.py,sha256=iBAl6DjyKoHLD8x-CRGzIXtbFHO4ahSyKoNfDcTREww,4412 +openai/types/graders/score_model_grader_param.py,sha256=0wQcPE-nbrNmYHKpJ_nfVvWc0YcrBC48yK_mohefncE,4589 +openai/types/graders/string_check_grader.py,sha256=xQwwSyqZT0JRwLOiBW5bo_AdAAa9nAntJwkwfYGwBcQ,814 +openai/types/graders/string_check_grader_param.py,sha256=HLFE2vMYtN42p3whZw7snhwlt8hb55UphGhmzOYRKKM,910 +openai/types/graders/text_similarity_grader.py,sha256=ye43c3vEbWeSoABRURyd1j3EVRACVENRqn9Qx7YzU_Y,975 +openai/types/graders/text_similarity_grader_param.py,sha256=KW-fjo4H3S7mdZbFMXj7N0R0iWT7C5FsUrjCe2zIStw,1133 +openai/types/image.py,sha256=21v1I9bcjq7p-rw20iSNxW0CQG7OLUB1VP3d3zTjID4,872 +openai/types/image_create_variation_params.py,sha256=Xeka4vp5V0o8R_6vnLsqiQhWH5O6tUSCyO3FKGVmAeU,1426 +openai/types/image_edit_completed_event.py,sha256=u8Rj9eW4C7htO0jl59OP0u4CKEhO0TcTL1dqLGN2JQU,2024 +openai/types/image_edit_params.py,sha256=mezMyXofFWhJ7U-PAJDdwkqA1Qxb6f_IU-OURie9-iI,6406 +openai/types/image_edit_partial_image_event.py,sha256=tJR59-lg3QQfoDNsItBoScAMhS-IdOHDon655vRz0CA,1180 +openai/types/image_edit_stream_event.py,sha256=GtHKc8VdumW5RnQtIiyMqhwIIaqYogKXZF1QNuq9Bd4,516 +openai/types/image_gen_completed_event.py,sha256=rpjnocJQ5imYRrHHxEz5yDzWppi9W6sxxHYX1dKamQg,2036 +openai/types/image_gen_partial_image_event.py,sha256=5VJhxTf6ZgjVFbQn72iOkolIHCMAa4LExMhXhq35NRw,1165 +openai/types/image_gen_stream_event.py,sha256=gVzdE6qzBPpK3kEFM7EdoUzBa4DgCaS3AdF9gjd0pUs,508 +openai/types/image_generate_params.py,sha256=lh6e0wSxf5h9ObG1bx0ikc_jZopM8Ofe0F1mbSIMoqc,6278 +openai/types/image_input_reference_param.py,sha256=2RGuIde_YVPaml9QAqXVea7BQ6h5rMCGT2seLyPMOIg,358 +openai/types/image_model.py,sha256=TI_uEEqY48vsiZgqEe2eP5MQ6p_HM1w3f9z5wyFR4p4,371 +openai/types/images_response.py,sha256=GyUSpxaUXJfr0qHdabXdeYn15MXv1vD2SziISO01Qdg,2574 +openai/types/model.py,sha256=cmrjNhjHXnJUfgp3al0B2s4O-PvFD-nHni7h8h2p6FM,609 +openai/types/model_deleted.py,sha256=ntKUfq9nnKB6esFmLBla1hYU29KjmFElr_i14IcWIUA,228 +openai/types/moderation.py,sha256=epjd2oQqw5uSaBGXVSu0hCUaDITvfMgwJe9cNjCjvTc,7099 +openai/types/moderation_create_params.py,sha256=bv5qr2y_MQ1MYBhWWUiCET2L18ypWtQpaIKzYTrl9xs,1032 +openai/types/moderation_create_response.py,sha256=mNPnXzdTgyVarKDENlkgud35yoK9CqWpKtcpC1bV_ds,552 +openai/types/moderation_image_url_input_param.py,sha256=AZhp5qCmWjuaZbDO3Y0MMXMRYv_cEK45PP5I7VYn-F4,758 +openai/types/moderation_model.py,sha256=BFeqSyel2My2WKC6MCa_mAIHJx4uXU3-p8UNudJANeM,319 +openai/types/moderation_multi_modal_input_param.py,sha256=RFdiEPsakWIscutX896ir5_rnEA2TLX5xQkjO5QR2vs,483 +openai/types/moderation_text_input_param.py,sha256=4egKHVxB5niYopwD6j3DRU1fIq3vcG2Q7utGQj24kGM,456 +openai/types/other_file_chunking_strategy_object.py,sha256=h4JKlz4p__U1vbZeXKO9v4DrPsDLIE5IilYdNrrnhFs,501 +openai/types/realtime/__init__.py,sha256=T9gtnTs3rGYJkmHPBrp2Kbn0CDjoTNUvHRSXF9hZO-M,17230 +openai/types/realtime/__pycache__/__init__.cpython-310.pyc,, +openai/types/realtime/__pycache__/audio_transcription.cpython-310.pyc,, +openai/types/realtime/__pycache__/audio_transcription_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/call_accept_params.cpython-310.pyc,, +openai/types/realtime/__pycache__/call_create_params.cpython-310.pyc,, +openai/types/realtime/__pycache__/call_refer_params.cpython-310.pyc,, +openai/types/realtime/__pycache__/call_reject_params.cpython-310.pyc,, +openai/types/realtime/__pycache__/client_secret_create_params.cpython-310.pyc,, +openai/types/realtime/__pycache__/client_secret_create_response.cpython-310.pyc,, +openai/types/realtime/__pycache__/conversation_created_event.cpython-310.pyc,, +openai/types/realtime/__pycache__/conversation_item.cpython-310.pyc,, +openai/types/realtime/__pycache__/conversation_item_added.cpython-310.pyc,, +openai/types/realtime/__pycache__/conversation_item_create_event.cpython-310.pyc,, +openai/types/realtime/__pycache__/conversation_item_create_event_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/conversation_item_created_event.cpython-310.pyc,, +openai/types/realtime/__pycache__/conversation_item_delete_event.cpython-310.pyc,, +openai/types/realtime/__pycache__/conversation_item_delete_event_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/conversation_item_deleted_event.cpython-310.pyc,, +openai/types/realtime/__pycache__/conversation_item_done.cpython-310.pyc,, +openai/types/realtime/__pycache__/conversation_item_input_audio_transcription_completed_event.cpython-310.pyc,, +openai/types/realtime/__pycache__/conversation_item_input_audio_transcription_delta_event.cpython-310.pyc,, +openai/types/realtime/__pycache__/conversation_item_input_audio_transcription_failed_event.cpython-310.pyc,, +openai/types/realtime/__pycache__/conversation_item_input_audio_transcription_segment.cpython-310.pyc,, +openai/types/realtime/__pycache__/conversation_item_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/conversation_item_retrieve_event.cpython-310.pyc,, +openai/types/realtime/__pycache__/conversation_item_retrieve_event_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/conversation_item_truncate_event.cpython-310.pyc,, +openai/types/realtime/__pycache__/conversation_item_truncate_event_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/conversation_item_truncated_event.cpython-310.pyc,, +openai/types/realtime/__pycache__/input_audio_buffer_append_event.cpython-310.pyc,, +openai/types/realtime/__pycache__/input_audio_buffer_append_event_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/input_audio_buffer_clear_event.cpython-310.pyc,, +openai/types/realtime/__pycache__/input_audio_buffer_clear_event_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/input_audio_buffer_cleared_event.cpython-310.pyc,, +openai/types/realtime/__pycache__/input_audio_buffer_commit_event.cpython-310.pyc,, +openai/types/realtime/__pycache__/input_audio_buffer_commit_event_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/input_audio_buffer_committed_event.cpython-310.pyc,, +openai/types/realtime/__pycache__/input_audio_buffer_dtmf_event_received_event.cpython-310.pyc,, +openai/types/realtime/__pycache__/input_audio_buffer_speech_started_event.cpython-310.pyc,, +openai/types/realtime/__pycache__/input_audio_buffer_speech_stopped_event.cpython-310.pyc,, +openai/types/realtime/__pycache__/input_audio_buffer_timeout_triggered.cpython-310.pyc,, +openai/types/realtime/__pycache__/log_prob_properties.cpython-310.pyc,, +openai/types/realtime/__pycache__/mcp_list_tools_completed.cpython-310.pyc,, +openai/types/realtime/__pycache__/mcp_list_tools_failed.cpython-310.pyc,, +openai/types/realtime/__pycache__/mcp_list_tools_in_progress.cpython-310.pyc,, +openai/types/realtime/__pycache__/noise_reduction_type.cpython-310.pyc,, +openai/types/realtime/__pycache__/output_audio_buffer_clear_event.cpython-310.pyc,, +openai/types/realtime/__pycache__/output_audio_buffer_clear_event_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/rate_limits_updated_event.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_audio_config.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_audio_config_input.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_audio_config_input_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_audio_config_output.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_audio_config_output_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_audio_config_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_audio_formats.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_audio_formats_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_audio_input_turn_detection.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_audio_input_turn_detection_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_client_event.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_client_event_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_connect_params.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_conversation_item_assistant_message.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_conversation_item_assistant_message_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_conversation_item_function_call.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_conversation_item_function_call_output.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_conversation_item_function_call_output_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_conversation_item_function_call_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_conversation_item_system_message.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_conversation_item_system_message_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_conversation_item_user_message.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_conversation_item_user_message_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_error.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_error_event.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_function_tool.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_function_tool_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_mcp_approval_request.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_mcp_approval_request_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_mcp_approval_response.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_mcp_approval_response_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_mcp_list_tools.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_mcp_list_tools_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_mcp_protocol_error.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_mcp_protocol_error_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_mcp_tool_call.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_mcp_tool_call_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_mcp_tool_execution_error.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_mcp_tool_execution_error_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_mcphttp_error.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_mcphttp_error_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_reasoning.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_reasoning_effort.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_reasoning_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_response.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_response_create_audio_output.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_response_create_audio_output_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_response_create_mcp_tool.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_response_create_mcp_tool_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_response_create_params.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_response_create_params_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_response_status.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_response_usage.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_response_usage_input_token_details.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_response_usage_output_token_details.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_server_event.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_session_create_request.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_session_create_request_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_session_create_response.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_tool_choice_config.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_tool_choice_config_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_tools_config.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_tools_config_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_tools_config_union.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_tools_config_union_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_tracing_config.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_tracing_config_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_transcription_session_audio.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_transcription_session_audio_input.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_transcription_session_audio_input_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_transcription_session_audio_input_turn_detection.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_transcription_session_audio_input_turn_detection_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_transcription_session_audio_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_transcription_session_create_request.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_transcription_session_create_request_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_transcription_session_create_response.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_transcription_session_turn_detection.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_truncation.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_truncation_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_truncation_retention_ratio.cpython-310.pyc,, +openai/types/realtime/__pycache__/realtime_truncation_retention_ratio_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/response_audio_delta_event.cpython-310.pyc,, +openai/types/realtime/__pycache__/response_audio_done_event.cpython-310.pyc,, +openai/types/realtime/__pycache__/response_audio_transcript_delta_event.cpython-310.pyc,, +openai/types/realtime/__pycache__/response_audio_transcript_done_event.cpython-310.pyc,, +openai/types/realtime/__pycache__/response_cancel_event.cpython-310.pyc,, +openai/types/realtime/__pycache__/response_cancel_event_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/response_content_part_added_event.cpython-310.pyc,, +openai/types/realtime/__pycache__/response_content_part_done_event.cpython-310.pyc,, +openai/types/realtime/__pycache__/response_create_event.cpython-310.pyc,, +openai/types/realtime/__pycache__/response_create_event_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/response_created_event.cpython-310.pyc,, +openai/types/realtime/__pycache__/response_done_event.cpython-310.pyc,, +openai/types/realtime/__pycache__/response_function_call_arguments_delta_event.cpython-310.pyc,, +openai/types/realtime/__pycache__/response_function_call_arguments_done_event.cpython-310.pyc,, +openai/types/realtime/__pycache__/response_mcp_call_arguments_delta.cpython-310.pyc,, +openai/types/realtime/__pycache__/response_mcp_call_arguments_done.cpython-310.pyc,, +openai/types/realtime/__pycache__/response_mcp_call_completed.cpython-310.pyc,, +openai/types/realtime/__pycache__/response_mcp_call_failed.cpython-310.pyc,, +openai/types/realtime/__pycache__/response_mcp_call_in_progress.cpython-310.pyc,, +openai/types/realtime/__pycache__/response_output_item_added_event.cpython-310.pyc,, +openai/types/realtime/__pycache__/response_output_item_done_event.cpython-310.pyc,, +openai/types/realtime/__pycache__/response_text_delta_event.cpython-310.pyc,, +openai/types/realtime/__pycache__/response_text_done_event.cpython-310.pyc,, +openai/types/realtime/__pycache__/session_created_event.cpython-310.pyc,, +openai/types/realtime/__pycache__/session_update_event.cpython-310.pyc,, +openai/types/realtime/__pycache__/session_update_event_param.cpython-310.pyc,, +openai/types/realtime/__pycache__/session_updated_event.cpython-310.pyc,, +openai/types/realtime/audio_transcription.py,sha256=zeRAVCk6D38BGMTvW-VDd_L-__6RgVPOA8U58L1ekVk,1975 +openai/types/realtime/audio_transcription_param.py,sha256=Jz7yaBnqkts3QTLfpUx0c9mKuyY4Bp3QCm7OzsFTwHU,1929 +openai/types/realtime/call_accept_params.py,sha256=cDnc_EgJANKx8_TfKsJBsSY5FScpCLazfy8XO8OOdNo,5753 +openai/types/realtime/call_create_params.py,sha256=r0vyhcjvDAKZF8DSbLP7bEQAVh92hgzNBnXBQWJ56no,544 +openai/types/realtime/call_refer_params.py,sha256=Zhy_H0Jv0leRL6HS_WH7Oca7HUlZ0feINePxN-hms0s,422 +openai/types/realtime/call_reject_params.py,sha256=cyz55zIN5DzSL74uhzeKQOSecl4V0UkpySt7zykoGIA,374 +openai/types/realtime/client_secret_create_params.py,sha256=12Guwuw4txjO_cW2GnrPT67UO-AVBaOg7LTEPAFuuLQ,1989 +openai/types/realtime/client_secret_create_response.py,sha256=ZUDhhR8vzMZRdHkfc9hpl80T4bUbDk4QNeLV8QlcQlc,1016 +openai/types/realtime/conversation_created_event.py,sha256=kVZE5Y1ZRDQq-x0vqbuYAl-VIRj5is_zC4pjHKwKZjw,879 +openai/types/realtime/conversation_item.py,sha256=BGqZp9UpybVbEyr6enYqdleryy4NMbXpzkUPX03cvoI,1437 +openai/types/realtime/conversation_item_added.py,sha256=SaE8tAlIbS1hgv_F6p3BWMmfwkdrPQU18UnTxfoJ29U,1516 +openai/types/realtime/conversation_item_create_event.py,sha256=Oo3Bk0qhCGS6INYscyU8l7c6omFu6n8cxmxPCZKYH5U,1560 +openai/types/realtime/conversation_item_create_event_param.py,sha256=tMEIyyj5ues0XQ9wTTvFbE8Lubx30DrXzvKJfa1GeUE,1581 +openai/types/realtime/conversation_item_created_event.py,sha256=hSqqRT281uXGKYPCaIImzYcWtzJLGp_fTkhIX3fQx3c,1474 +openai/types/realtime/conversation_item_delete_event.py,sha256=gDbD3qPFSxSYj3zjGUuVn5L1KLQDEyiDqPaGwMZeUAY,840 +openai/types/realtime/conversation_item_delete_event_param.py,sha256=sMZ5WeOkLHCV8bh9-06i2EUFD2V_-bA9DMkGX67W82I,861 +openai/types/realtime/conversation_item_deleted_event.py,sha256=VwTgV7HhBNOIBwSJfAtO9C0LP0pFers83ORnggEpbOQ,741 +openai/types/realtime/conversation_item_done.py,sha256=TjLuup27QloMnHgXemjpknACqV9N3A2-alX2_msK-1I,969 +openai/types/realtime/conversation_item_input_audio_transcription_completed_event.py,sha256=ZemU0mTZAdxe8O1u5ZdLpelVd-UksKrIKFPnf0_Eg1I,3281 +openai/types/realtime/conversation_item_input_audio_transcription_delta_event.py,sha256=KGr9MvmKDXnbAsQU-PbHethJ09I_MQ4KfQgUJlhF8Tk,1495 +openai/types/realtime/conversation_item_input_audio_transcription_failed_event.py,sha256=Qugv24nmNkYqJFmsTMlDH-P38r50dPVSyt8-43Nmmr0,1364 +openai/types/realtime/conversation_item_input_audio_transcription_segment.py,sha256=JC_QW5z_TFmCPjRUm6k2qnWUEnoIK3IHXGlE88J2YP0,1079 +openai/types/realtime/conversation_item_param.py,sha256=yrtdTZDIfAsJGwSXDY7v-_e9GtOPqRNXQAM2LWjxOOI,1483 +openai/types/realtime/conversation_item_retrieve_event.py,sha256=YuRUzjV3VWdfMchkeyWBNkZdMjtboRaHiBz3PpXGVZc,975 +openai/types/realtime/conversation_item_retrieve_event_param.py,sha256=NG4pq3JXYIG44-vu5apNfa6iEO8y9Pn1Ypa8AqKQWjE,996 +openai/types/realtime/conversation_item_truncate_event.py,sha256=3OUHG_uqYOQgH6LX0vtZJ4WFjVDAv9FrSb8ZLAtZcSw,1560 +openai/types/realtime/conversation_item_truncate_event_param.py,sha256=OiSiFZ0KyUYN5AyhCKf7HKIyOxj-uW3psdtMN6PI5Yk,1601 +openai/types/realtime/conversation_item_truncated_event.py,sha256=KXuLWI1Ozcq0bR44T92cleAd6bvZRLQhD1XvaJBHLNM,1124 +openai/types/realtime/input_audio_buffer_append_event.py,sha256=VS09zVCzDrXJ2OXxkzBQORqfWuwwxRrUibsLkPyVxCs,1591 +openai/types/realtime/input_audio_buffer_append_event_param.py,sha256=U7EcpuHlmMwI6MJm5aWSg-OQs19T5IDycNSrosMFTgY,1612 +openai/types/realtime/input_audio_buffer_clear_event.py,sha256=2MJ3ypmN8SyOYkNjYTvdPp0Sz5UtvGumqOa8tCH1O3Y,637 +openai/types/realtime/input_audio_buffer_clear_event_param.py,sha256=MTQMjN6RACt7J9tSnzglNNOfGL-_MgzxWCYWltbko0k,648 +openai/types/realtime/input_audio_buffer_cleared_event.py,sha256=iClRNb-MTR86VkuZSbmwJii8iP9j0Ox0QlbCyt2G85w,556 +openai/types/realtime/input_audio_buffer_commit_event.py,sha256=Nluuq9h5G3hxy5PmmWGStxiS7-t-Dy4lsOKBIudMy14,1068 +openai/types/realtime/input_audio_buffer_commit_event_param.py,sha256=oflH-u7iSqqF-eriFHDWrqO-8G7iW0n-VfUUWcF2thQ,1079 +openai/types/realtime/input_audio_buffer_committed_event.py,sha256=M3MAPO5XwuFmOnfC_0_GcuYQ12aKILiEgEGdPAWzOlU,1027 +openai/types/realtime/input_audio_buffer_dtmf_event_received_event.py,sha256=JUq_t7Q5E4241M1JTqTcRUwsmgZNmJmiUdn_LKcYP84,889 +openai/types/realtime/input_audio_buffer_speech_started_event.py,sha256=GjjkLM3MOoW8wJ6KKdUz-3yLpkK4VtrQu8NKC1BwQBg,1567 +openai/types/realtime/input_audio_buffer_speech_stopped_event.py,sha256=l0CmVlUxcGpthG37Hxtdf9ydypFKQxR0a_z7fz131kY,1029 +openai/types/realtime/input_audio_buffer_timeout_triggered.py,sha256=lLraokk0TW03UNyjpeVpHlyCoupNLQaRCsH7NofvYdI,1898 +openai/types/realtime/log_prob_properties.py,sha256=78jAqS9O2wwM5JhpV8Cdwpy8xgET0ceXclW4BcyPoCY,489 +openai/types/realtime/mcp_list_tools_completed.py,sha256=zKMP0fwchYZMbdJERmFBhIALlrNuz6npH4Gn0cMjbto,543 +openai/types/realtime/mcp_list_tools_failed.py,sha256=1En1gz6mxUhaYy0RoTBKxLk6grL1_kfaYWGRmX2Lkrs,528 +openai/types/realtime/mcp_list_tools_in_progress.py,sha256=xC1hb9qODkB-dAJPeNf40gQOi4q1cYNU1LivPPgMaIg,550 +openai/types/realtime/noise_reduction_type.py,sha256=lrAb7YhMM-anRYzzOha8hcVloNJR_zWuFrO2SccrcIo,238 +openai/types/realtime/output_audio_buffer_clear_event.py,sha256=w4xRRkTcCtGdYDspgkLnD6LlzavmjxUNiF0lOzVF2ow,934 +openai/types/realtime/output_audio_buffer_clear_event_param.py,sha256=-zmYI1KaCgiGFnYeLl9_tutNFuHHrbeKeXt94-ZmLhk,945 +openai/types/realtime/rate_limits_updated_event.py,sha256=rsYK1Yc0WrtMFG8shtaYQv5uEd59foHBTJs4XoA1l-s,1255 +openai/types/realtime/realtime_audio_config.py,sha256=CFWqdebuucyHyL4gqIZTuh78PME5cQPLmeq1VsD9Z3Y,520 +openai/types/realtime/realtime_audio_config_input.py,sha256=t_d0vlXlLw6fRQB4PUpw6KuM29Rh2Sv8n-O1X5Nl4Qw,3368 +openai/types/realtime/realtime_audio_config_input_param.py,sha256=fn4umYGMf_EYcSjr7_r77_MpcGWD5r9EyQ7N9C3eEy4,3420 +openai/types/realtime/realtime_audio_config_output.py,sha256=hi8_fMZigCBSpA4_nc0dwYQI3UlOqgmvPMrjqxFQILw,1680 +openai/types/realtime/realtime_audio_config_output_param.py,sha256=001WNkdy5Olxc0-X6cL_nHpHYVtP0pUAkMSjEF2zAGE,1705 +openai/types/realtime/realtime_audio_config_param.py,sha256=d5gwlXPsJIc53Nh1A9QYefyHd5YJ-E1VRRfuK2IOafk,556 +openai/types/realtime/realtime_audio_formats.py,sha256=QZTTihJeSWCwEFUK2kjf4nvaZNXWnFfCKSXZee-Xa-Q,1069 +openai/types/realtime/realtime_audio_formats_param.py,sha256=N0NFD1pbh6ZlcbENKv10Np-K2QVPWIpFsLzl0koPirs,960 +openai/types/realtime/realtime_audio_input_turn_detection.py,sha256=mZB4mr8AaT5TtogXLwxzjM_Q5W-x5o4T1tPFFnyiMmU,4260 +openai/types/realtime/realtime_audio_input_turn_detection_param.py,sha256=ItL4MBzCTPYUScMQwgxdrbyIsbgbcNVoTuAF7Zk9oG8,4091 +openai/types/realtime/realtime_client_event.py,sha256=4_lYEyK-wj25VTh8GTaV0mZ0t17KhkfJrQ0yUF0mCYU,1473 +openai/types/realtime/realtime_client_event_param.py,sha256=YPveu8tNyKmZkK24qEJv8js5l5NNygDyAcsza2iOmKw,1543 +openai/types/realtime/realtime_connect_params.py,sha256=Zd5FnP-6nEzAPiWTckSdVGQsA_8GqhwELCpQXt22J8A,288 +openai/types/realtime/realtime_conversation_item_assistant_message.py,sha256=up0WdL75VVd6rK11nBjRCcIRn3Qj-6dFv3podahi78E,1780 +openai/types/realtime/realtime_conversation_item_assistant_message_param.py,sha256=agNl8DdxAJPV1NeGgTkti3V8QKg_WQTlZFbXYR931bI,1748 +openai/types/realtime/realtime_conversation_item_function_call.py,sha256=uT0NfedSzOpneh3Bqbx_oKSb-Cj0aFUd4b-sJ7QSIvQ,1262 +openai/types/realtime/realtime_conversation_item_function_call_output.py,sha256=aXHbpueTQ3lUri3oXA7B8m6S9Tcq8xQqFurzS8kNhdk,1170 +openai/types/realtime/realtime_conversation_item_function_call_output_param.py,sha256=yRdBH7iqCLqtKxgylFYK5c9moNuefrW6OQAWR0g0De0,1167 +openai/types/realtime/realtime_conversation_item_function_call_param.py,sha256=Et9Qisj41TwOgu6YweMUXm4hGDD6q4FGyoTEN5n8fWE,1242 +openai/types/realtime/realtime_conversation_item_system_message.py,sha256=vxOmlQODp5RtxCObbTj5_E-C82HjWJA2SiBIZYTuycE,1695 +openai/types/realtime/realtime_conversation_item_system_message_param.py,sha256=nbvAmVDzYD6HflURqkbrugVshOXpRvFxnnxFuQjc744,1697 +openai/types/realtime/realtime_conversation_item_user_message.py,sha256=Ud0ijIPDq8BALQsAjHyJqHjywzq7yl37dv28Ru7Ilvg,2170 +openai/types/realtime/realtime_conversation_item_user_message_param.py,sha256=bIEMwkqvS9iDpt7X1KofesZaTi0sZYVo6IJj-CWtXCc,2104 +openai/types/realtime/realtime_error.py,sha256=V33P7DvMTFyEI2rhVkCnoD5zbt6wndDYyr_eZQ29BJo,658 +openai/types/realtime/realtime_error_event.py,sha256=FGyefJO5-GSjwyrsXBq-Ezp6qYZEcQsN1J_5sWBlyiA,714 +openai/types/realtime/realtime_function_tool.py,sha256=3CDiCZCM0A1VLRxOFdG4teFXr8dx0JFU94KbSn-JgGc,734 +openai/types/realtime/realtime_function_tool_param.py,sha256=-vDBSmMWNdbABC8dxVckkNeRdEujAKeff6icJvYrM0I,674 +openai/types/realtime/realtime_mcp_approval_request.py,sha256=n88sEpgRYFAIPe_jqmlYa0KsBDv03kkBstpp90GSvhY,696 +openai/types/realtime/realtime_mcp_approval_request_param.py,sha256=GIdxqx9wz5cRBU0iT1_DtlZlyNgehKhrsaqMEfRl624,792 +openai/types/realtime/realtime_mcp_approval_response.py,sha256=HOiVoqZwfA8WAZIyN3fPwUsceepQq6OWkkLaZGqJDXM,742 +openai/types/realtime/realtime_mcp_approval_response_param.py,sha256=ysEMT5pSKOo8-scsMSoW_vutKX14MDTsKc_jEHQsPoc,821 +openai/types/realtime/realtime_mcp_list_tools.py,sha256=LrgWdG30hgwmoFHC92aONFReZzWaI24SDQaH78yyGsc,1004 +openai/types/realtime/realtime_mcp_list_tools_param.py,sha256=SEiFMWl6ig6xjzUAx9fnN8ap_88kVUQEy3Ia8zWPiSg,1090 +openai/types/realtime/realtime_mcp_protocol_error.py,sha256=4jqkfl6h7tFT5kQy40VW24LrokpKe6X4VROYlNmOHDQ,313 +openai/types/realtime/realtime_mcp_protocol_error_param.py,sha256=jlufPTMU_9JuYtqzQGTmb0o978gDiOFxkNx0yJAvwx8,389 +openai/types/realtime/realtime_mcp_tool_call.py,sha256=C3FP8y_xqmFjBcO64I6phXMiuFC1sRt-8JZypczbQ4k,1407 +openai/types/realtime/realtime_mcp_tool_call_param.py,sha256=lsbewyAWR1wH4rj3znPeJ3twMSV1EaP6p0Faq2s5JXM,1421 +openai/types/realtime/realtime_mcp_tool_execution_error.py,sha256=swcOrTKO5cx1kkfGS_5PhBPEQx_Vf_ZW04HbA5eRa0g,314 +openai/types/realtime/realtime_mcp_tool_execution_error_param.py,sha256=3IuPmvy52n_VByGYqfCr87kciEQdJMTcwGWj4__PiX8,380 +openai/types/realtime/realtime_mcphttp_error.py,sha256=-Zqz0xr2gPs6peG_wC3S8qVgtEUJNrZm4Mm5BIvmZw0,301 +openai/types/realtime/realtime_mcphttp_error_param.py,sha256=GcmAMBvZVNrN9p_tneHPu_pyN7D8wCytaAKruFtMfwI,377 +openai/types/realtime/realtime_reasoning.py,sha256=ZOrZm_TaL0Pb_3qj2FeKbt1LZ9L7O_aQuZG65ZBchTw,544 +openai/types/realtime/realtime_reasoning_effort.py,sha256=udaKzmvgV6NcjJ2Nme10cXThgV1n794AD6ujWn7CvQk,266 +openai/types/realtime/realtime_reasoning_param.py,sha256=hxHUxVSwyqpApYPaVU49MyPf95q3lOMEekXwAx4BjF8,565 +openai/types/realtime/realtime_response.py,sha256=zaUF7moDzT5foAYhiqg1zALpA-4pxUCvy1ImIFprD6g,3903 +openai/types/realtime/realtime_response_create_audio_output.py,sha256=C9uxTOMzYseGLPbLcVxn9puvudBtrqSYANGhSLWsOZQ,1384 +openai/types/realtime/realtime_response_create_audio_output_param.py,sha256=g4jfVNQb32DGH_d7QorydEtxk9OnFW_ArIYkERLsPrg,1422 +openai/types/realtime/realtime_response_create_mcp_tool.py,sha256=_KSSVpVYb-j2Gad1Ku2TUeKcAmp47p0uciewINqTB7U,5194 +openai/types/realtime/realtime_response_create_mcp_tool_param.py,sha256=I9kn6YZuVUPhJwyjBfYS6awDVAtsiy-pti62xl1LYJg,5080 +openai/types/realtime/realtime_response_create_params.py,sha256=yGRbE6XIr26bhV_N6mMXyTRzx0RB6SGKSf8f7dQsDDE,4730 +openai/types/realtime/realtime_response_create_params_param.py,sha256=dWVGvYAqJJMcVcj8dfxTXiN-_v-_MP_UOkwj67f98bo,4744 +openai/types/realtime/realtime_response_status.py,sha256=QjUdgjUKfX8tHVk-qRofl33vnjdoYzwTFhlk6knUGCo,1500 +openai/types/realtime/realtime_response_usage.py,sha256=atuMmLvzmTtH46RcOE7k3Br730ObjnkVBFL6x1BXWYg,1727 +openai/types/realtime/realtime_response_usage_input_token_details.py,sha256=Pt38MhRPUUhNGVN6nRShH750heUbbAlrYbKLPXcHHe8,1635 +openai/types/realtime/realtime_response_usage_output_token_details.py,sha256=3K2DIIvd92aJe9X38tSALn_t_-OyU4ivG3ckBXspkng,524 +openai/types/realtime/realtime_server_event.py,sha256=WkL6yNqJXjKbkhegGZr00_Uw84NVITGhV-zPlQdLGeA,8248 +openai/types/realtime/realtime_session_create_request.py,sha256=w9_qkBZc5lgGw5Yqv3RM1Ro9-GPvLM159IBvZjnluBY,5869 +openai/types/realtime/realtime_session_create_request_param.py,sha256=in1oIbTLPoHxVYhw_adXbBydaU7au-pmiSEKLgicBHk,5837 +openai/types/realtime/realtime_session_create_response.py,sha256=qf6GbkJ16JtVuc_EYPnfagHoK_6tnLq7OV8KV1wOi7c,19913 +openai/types/realtime/realtime_tool_choice_config.py,sha256=DV0uuyfK59paj5NC9adQskUF2km5TRSiHAlMDu1Fmdo,472 +openai/types/realtime/realtime_tool_choice_config_param.py,sha256=0vqYNM4MkU5d8GXfitT6AoE9AubKeLZOSHGOH8q73QU,550 +openai/types/realtime/realtime_tools_config.py,sha256=JSxehiQnA_tJUeXvi2h9H6wlYsnhhtRWB_o5S20V-oQ,318 +openai/types/realtime/realtime_tools_config_param.py,sha256=4mGkT-5n2BaZN6BxvlZaKr5jbo_Yv4SvFxzhU2n2A8o,5373 +openai/types/realtime/realtime_tools_config_union.py,sha256=vT4Q17Y6otLQFRcMsCrT0FKytDSKE9GUmiXR_ViWmlA,5451 +openai/types/realtime/realtime_tools_config_union_param.py,sha256=AueIp62Meupmtyui8_tC6n-rJH2CFOMc3ydUEEVroy0,5260 +openai/types/realtime/realtime_tracing_config.py,sha256=gkG557bdUH4-kAoyH9TEFp12VJFwQkGfQkPDc4ESh-E,918 +openai/types/realtime/realtime_tracing_config_param.py,sha256=fo2An_bdLxQrCLhZ6d34vcxiDAHTj2BoxsTqoyT6yjw,887 +openai/types/realtime/realtime_transcription_session_audio.py,sha256=cUETz-wzN-6qaupdCF06nmLmgH846dp7zu_wGOyl-Ho,467 +openai/types/realtime/realtime_transcription_session_audio_input.py,sha256=wh9iYK2YcVOvKWSeymK2N6zB6nQuZeEYR6zl9A7i7kQ,3497 +openai/types/realtime/realtime_transcription_session_audio_input_param.py,sha256=vsqjAJOtxxpUR4kvjvBVq3EB-BwubC6QGeAY6Vtntag,3549 +openai/types/realtime/realtime_transcription_session_audio_input_turn_detection.py,sha256=1j9-uzpvv-dt4D1jAqH-nbIIx7RwoZ3VnF6Kw4cXoIw,4300 +openai/types/realtime/realtime_transcription_session_audio_input_turn_detection_param.py,sha256=kmDzDtQAU8U6t9mmIMNz2pw5Mle06RMcpxACtCpnfw4,4131 +openai/types/realtime/realtime_transcription_session_audio_param.py,sha256=Jia_0_l0wqhrZDvY2WkR3koSHY2lL25z9ZlHcytXdFU,504 +openai/types/realtime/realtime_transcription_session_create_request.py,sha256=a2sXjIAJYePFHZ0SqC5Obi0EWO-YAgEW85vQqCK5Mkc,963 +openai/types/realtime/realtime_transcription_session_create_request_param.py,sha256=fRfSPuKXdxYJQbUT8woqTUReDUvQNVwXLsbMRH8NwiA,992 +openai/types/realtime/realtime_transcription_session_create_response.py,sha256=MKIHumBodSdvaerno5cUwI8AZoSqdfet_C_yG075aNM,2635 +openai/types/realtime/realtime_transcription_session_turn_detection.py,sha256=nZzliKU1BeSGd1VQEXLNwZebDVN8n25Uzu9n7HQklxU,1341 +openai/types/realtime/realtime_truncation.py,sha256=lnr1Uq9kSs6OfJb_TcvQrs7jx92UuSKaIhGNvwUK-qU,380 +openai/types/realtime/realtime_truncation_param.py,sha256=wBXHiAPS_HA6MWBqhRGEtqZxu6RdIrgnTVRYgUljwq4,442 +openai/types/realtime/realtime_truncation_retention_ratio.py,sha256=EfcvUfo8Ul7EgqWpDsTpUTlZrmZXIO1LroTLhgOfibw,1749 +openai/types/realtime/realtime_truncation_retention_ratio_param.py,sha256=t6qlpaEmtc0g4PvyXH2wz8PewNmnI_WyeYSCkYVkiXQ,1766 +openai/types/realtime/response_audio_delta_event.py,sha256=1tXOxDJqpshq4EP7R62Fnhy1u2Wwqflzru8N5MlPaNQ,818 +openai/types/realtime/response_audio_done_event.py,sha256=9fdpuN-G0dQGsSfWJRXftoA9vY2JCQ4kGEbw0VNFo3w,837 +openai/types/realtime/response_audio_transcript_delta_event.py,sha256=fk3wI07iou7q7dTIDuJsP1kjPfHvj_5E_pUct70_TWM,873 +openai/types/realtime/response_audio_transcript_done_event.py,sha256=fLcAV1ckIpDJ-SxukAeLZvuhaZrzid1AU4EUItVmLWM,983 +openai/types/realtime/response_cancel_event.py,sha256=VEQcxB2cTEmItz_o5ubbrWbvxWjrH8DB9UkKeTSrYV0,1031 +openai/types/realtime/response_cancel_event_param.py,sha256=Uh6zrwrw0xxKQULpYj6kGAOysR48JYp-yUlJDoFyRok,1025 +openai/types/realtime/response_content_part_added_event.py,sha256=SBtIynUx0WKuuHgrhDfwfejRZe0Rb3oe_eC_mBMj0p0,1399 +openai/types/realtime/response_content_part_done_event.py,sha256=Y27ee1ZRzf9WYwsny6J0SS-Su9DH-YfG7dEGK_Ooc9U,1404 +openai/types/realtime/response_create_event.py,sha256=mn__Lnv3Fuf4_aF6ZPEzHIHIZoXX_jzTRHbxEqnrnto,2085 +openai/types/realtime/response_create_event_param.py,sha256=3hLwSZv8ROLu11eU17YgdR2A8XE5P6XVFbBMO5PjY40,2096 +openai/types/realtime/response_created_event.py,sha256=02IS6XqoTnQr9gvPhUimQ0bchMW3LmjtYbL7V6H6Xlw,669 +openai/types/realtime/response_done_event.py,sha256=Vt88mKQS72w7ysbkcU3yMxkIoYV4AoDyWqxeth1rJj0,1053 +openai/types/realtime/response_function_call_arguments_delta_event.py,sha256=hceOwsJTdQ_vW8wMPebwj6tkt0nDPYbwCpWPs76nmrQ,874 +openai/types/realtime/response_function_call_arguments_done_event.py,sha256=JENjWrP1ErF3WfegEUp9WpFySA_VvvAcOzqSqxOZXw4,1033 +openai/types/realtime/response_mcp_call_arguments_delta.py,sha256=STwpfYmz3P6m-IwlUkHbI9rfauQn2HrmwNprY5NMaP4,920 +openai/types/realtime/response_mcp_call_arguments_done.py,sha256=3nZoOA7m2Bj1JyMPTwhiqIvsLwb8UBnFUVGZ5KviNmg,799 +openai/types/realtime/response_mcp_call_completed.py,sha256=8SfUc0zoVadfToShvtxw_wQ-wdh1q0aw68TSdS07fAE,633 +openai/types/realtime/response_mcp_call_failed.py,sha256=--MvtTO4ZANb5uYa-L9aC-PCdttglgUWyfzVvUlAqjU,605 +openai/types/realtime/response_mcp_call_in_progress.py,sha256=MK2m5lYcsKStDptN0fhVxQAn2hHZwSBD7KgzdIv0RJM,643 +openai/types/realtime/response_output_item_added_event.py,sha256=Wnbnn423eTc8iY1vFMGPghz88VCt7WfmTBIM3ErrD1U,796 +openai/types/realtime/response_output_item_done_event.py,sha256=foWLMOSv67skqeGLfOmuYGgABmMQnoLNGiT5ZmmmGIY,854 +openai/types/realtime/response_text_delta_event.py,sha256=1I5yu-_1ifZaNWvW9qzyMtOowUYjUyFt_JDIRSJGl1U,819 +openai/types/realtime/response_text_done_event.py,sha256=55fRkCAPSocN9iadkJeowE2-3laFjAAZwLa9WCNsXJA,914 +openai/types/realtime/session_created_event.py,sha256=vcxq7m7QFXsoLHiNRB6_Oh6zzxTUyfpB7ogqAUo4Lzo,980 +openai/types/realtime/session_update_event.py,sha256=R5YvfGKxhk0E4b02kQbYbg9MenVbUf-q-ZEHL8Gf5m4,1735 +openai/types/realtime/session_update_event_param.py,sha256=uSxqGmfwGW0raKiTkMFwBuPkTxEsDu-L8I1IR53530M,1807 +openai/types/realtime/session_updated_event.py,sha256=Zp9HaAopCZ1mdpt8BGp8t7JA5J4o3Cm_FbIobqvJhpM,887 +openai/types/responses/__init__.py,sha256=1ExeJOcIHGhwoHUyzJlnVz_JuJkAK9UWKI0NcoTnXvs,22041 +openai/types/responses/__pycache__/__init__.cpython-310.pyc,, +openai/types/responses/__pycache__/apply_patch_tool.cpython-310.pyc,, +openai/types/responses/__pycache__/apply_patch_tool_param.cpython-310.pyc,, +openai/types/responses/__pycache__/compacted_response.cpython-310.pyc,, +openai/types/responses/__pycache__/computer_action.cpython-310.pyc,, +openai/types/responses/__pycache__/computer_action_list.cpython-310.pyc,, +openai/types/responses/__pycache__/computer_action_list_param.cpython-310.pyc,, +openai/types/responses/__pycache__/computer_action_param.cpython-310.pyc,, +openai/types/responses/__pycache__/computer_tool.cpython-310.pyc,, +openai/types/responses/__pycache__/computer_tool_param.cpython-310.pyc,, +openai/types/responses/__pycache__/computer_use_preview_tool.cpython-310.pyc,, +openai/types/responses/__pycache__/computer_use_preview_tool_param.cpython-310.pyc,, +openai/types/responses/__pycache__/container_auto.cpython-310.pyc,, +openai/types/responses/__pycache__/container_auto_param.cpython-310.pyc,, +openai/types/responses/__pycache__/container_network_policy_allowlist.cpython-310.pyc,, +openai/types/responses/__pycache__/container_network_policy_allowlist_param.cpython-310.pyc,, +openai/types/responses/__pycache__/container_network_policy_disabled.cpython-310.pyc,, +openai/types/responses/__pycache__/container_network_policy_disabled_param.cpython-310.pyc,, +openai/types/responses/__pycache__/container_network_policy_domain_secret.cpython-310.pyc,, +openai/types/responses/__pycache__/container_network_policy_domain_secret_param.cpython-310.pyc,, +openai/types/responses/__pycache__/container_reference.cpython-310.pyc,, +openai/types/responses/__pycache__/container_reference_param.cpython-310.pyc,, +openai/types/responses/__pycache__/custom_tool.cpython-310.pyc,, +openai/types/responses/__pycache__/custom_tool_param.cpython-310.pyc,, +openai/types/responses/__pycache__/easy_input_message.cpython-310.pyc,, +openai/types/responses/__pycache__/easy_input_message_param.cpython-310.pyc,, +openai/types/responses/__pycache__/file_search_tool.cpython-310.pyc,, +openai/types/responses/__pycache__/file_search_tool_param.cpython-310.pyc,, +openai/types/responses/__pycache__/function_shell_tool.cpython-310.pyc,, +openai/types/responses/__pycache__/function_shell_tool_param.cpython-310.pyc,, +openai/types/responses/__pycache__/function_tool.cpython-310.pyc,, +openai/types/responses/__pycache__/function_tool_param.cpython-310.pyc,, +openai/types/responses/__pycache__/inline_skill.cpython-310.pyc,, +openai/types/responses/__pycache__/inline_skill_param.cpython-310.pyc,, +openai/types/responses/__pycache__/inline_skill_source.cpython-310.pyc,, +openai/types/responses/__pycache__/inline_skill_source_param.cpython-310.pyc,, +openai/types/responses/__pycache__/input_item_list_params.cpython-310.pyc,, +openai/types/responses/__pycache__/input_token_count_params.cpython-310.pyc,, +openai/types/responses/__pycache__/input_token_count_response.cpython-310.pyc,, +openai/types/responses/__pycache__/local_environment.cpython-310.pyc,, +openai/types/responses/__pycache__/local_environment_param.cpython-310.pyc,, +openai/types/responses/__pycache__/local_skill.cpython-310.pyc,, +openai/types/responses/__pycache__/local_skill_param.cpython-310.pyc,, +openai/types/responses/__pycache__/namespace_tool.cpython-310.pyc,, +openai/types/responses/__pycache__/namespace_tool_param.cpython-310.pyc,, +openai/types/responses/__pycache__/parsed_response.cpython-310.pyc,, +openai/types/responses/__pycache__/response.cpython-310.pyc,, +openai/types/responses/__pycache__/response_apply_patch_tool_call.cpython-310.pyc,, +openai/types/responses/__pycache__/response_apply_patch_tool_call_output.cpython-310.pyc,, +openai/types/responses/__pycache__/response_audio_delta_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_audio_done_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_audio_transcript_delta_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_audio_transcript_done_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_code_interpreter_call_code_delta_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_code_interpreter_call_code_done_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_code_interpreter_call_completed_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_code_interpreter_call_in_progress_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_code_interpreter_call_interpreting_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_code_interpreter_tool_call.cpython-310.pyc,, +openai/types/responses/__pycache__/response_code_interpreter_tool_call_param.cpython-310.pyc,, +openai/types/responses/__pycache__/response_compact_params.cpython-310.pyc,, +openai/types/responses/__pycache__/response_compaction_item.cpython-310.pyc,, +openai/types/responses/__pycache__/response_compaction_item_param.cpython-310.pyc,, +openai/types/responses/__pycache__/response_compaction_item_param_param.cpython-310.pyc,, +openai/types/responses/__pycache__/response_completed_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_computer_tool_call.cpython-310.pyc,, +openai/types/responses/__pycache__/response_computer_tool_call_output_item.cpython-310.pyc,, +openai/types/responses/__pycache__/response_computer_tool_call_output_screenshot.cpython-310.pyc,, +openai/types/responses/__pycache__/response_computer_tool_call_output_screenshot_param.cpython-310.pyc,, +openai/types/responses/__pycache__/response_computer_tool_call_param.cpython-310.pyc,, +openai/types/responses/__pycache__/response_container_reference.cpython-310.pyc,, +openai/types/responses/__pycache__/response_content_part_added_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_content_part_done_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_conversation_param.cpython-310.pyc,, +openai/types/responses/__pycache__/response_conversation_param_param.cpython-310.pyc,, +openai/types/responses/__pycache__/response_create_params.cpython-310.pyc,, +openai/types/responses/__pycache__/response_created_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_custom_tool_call.cpython-310.pyc,, +openai/types/responses/__pycache__/response_custom_tool_call_input_delta_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_custom_tool_call_input_done_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_custom_tool_call_item.cpython-310.pyc,, +openai/types/responses/__pycache__/response_custom_tool_call_output.cpython-310.pyc,, +openai/types/responses/__pycache__/response_custom_tool_call_output_item.cpython-310.pyc,, +openai/types/responses/__pycache__/response_custom_tool_call_output_param.cpython-310.pyc,, +openai/types/responses/__pycache__/response_custom_tool_call_param.cpython-310.pyc,, +openai/types/responses/__pycache__/response_error.cpython-310.pyc,, +openai/types/responses/__pycache__/response_error_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_failed_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_file_search_call_completed_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_file_search_call_in_progress_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_file_search_call_searching_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_file_search_tool_call.cpython-310.pyc,, +openai/types/responses/__pycache__/response_file_search_tool_call_param.cpython-310.pyc,, +openai/types/responses/__pycache__/response_format_text_config.cpython-310.pyc,, +openai/types/responses/__pycache__/response_format_text_config_param.cpython-310.pyc,, +openai/types/responses/__pycache__/response_format_text_json_schema_config.cpython-310.pyc,, +openai/types/responses/__pycache__/response_format_text_json_schema_config_param.cpython-310.pyc,, +openai/types/responses/__pycache__/response_function_call_arguments_delta_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_function_call_arguments_done_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_function_call_output_item.cpython-310.pyc,, +openai/types/responses/__pycache__/response_function_call_output_item_list.cpython-310.pyc,, +openai/types/responses/__pycache__/response_function_call_output_item_list_param.cpython-310.pyc,, +openai/types/responses/__pycache__/response_function_call_output_item_param.cpython-310.pyc,, +openai/types/responses/__pycache__/response_function_shell_call_output_content.cpython-310.pyc,, +openai/types/responses/__pycache__/response_function_shell_call_output_content_param.cpython-310.pyc,, +openai/types/responses/__pycache__/response_function_shell_tool_call.cpython-310.pyc,, +openai/types/responses/__pycache__/response_function_shell_tool_call_output.cpython-310.pyc,, +openai/types/responses/__pycache__/response_function_tool_call.cpython-310.pyc,, +openai/types/responses/__pycache__/response_function_tool_call_item.cpython-310.pyc,, +openai/types/responses/__pycache__/response_function_tool_call_output_item.cpython-310.pyc,, +openai/types/responses/__pycache__/response_function_tool_call_param.cpython-310.pyc,, +openai/types/responses/__pycache__/response_function_web_search.cpython-310.pyc,, +openai/types/responses/__pycache__/response_function_web_search_param.cpython-310.pyc,, +openai/types/responses/__pycache__/response_image_gen_call_completed_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_image_gen_call_generating_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_image_gen_call_in_progress_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_image_gen_call_partial_image_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_in_progress_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_includable.cpython-310.pyc,, +openai/types/responses/__pycache__/response_incomplete_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_input.cpython-310.pyc,, +openai/types/responses/__pycache__/response_input_audio.cpython-310.pyc,, +openai/types/responses/__pycache__/response_input_audio_param.cpython-310.pyc,, +openai/types/responses/__pycache__/response_input_content.cpython-310.pyc,, +openai/types/responses/__pycache__/response_input_content_param.cpython-310.pyc,, +openai/types/responses/__pycache__/response_input_file.cpython-310.pyc,, +openai/types/responses/__pycache__/response_input_file_content.cpython-310.pyc,, +openai/types/responses/__pycache__/response_input_file_content_param.cpython-310.pyc,, +openai/types/responses/__pycache__/response_input_file_param.cpython-310.pyc,, +openai/types/responses/__pycache__/response_input_image.cpython-310.pyc,, +openai/types/responses/__pycache__/response_input_image_content.cpython-310.pyc,, +openai/types/responses/__pycache__/response_input_image_content_param.cpython-310.pyc,, +openai/types/responses/__pycache__/response_input_image_param.cpython-310.pyc,, +openai/types/responses/__pycache__/response_input_item.cpython-310.pyc,, +openai/types/responses/__pycache__/response_input_item_param.cpython-310.pyc,, +openai/types/responses/__pycache__/response_input_message_content_list.cpython-310.pyc,, +openai/types/responses/__pycache__/response_input_message_content_list_param.cpython-310.pyc,, +openai/types/responses/__pycache__/response_input_message_item.cpython-310.pyc,, +openai/types/responses/__pycache__/response_input_param.cpython-310.pyc,, +openai/types/responses/__pycache__/response_input_text.cpython-310.pyc,, +openai/types/responses/__pycache__/response_input_text_content.cpython-310.pyc,, +openai/types/responses/__pycache__/response_input_text_content_param.cpython-310.pyc,, +openai/types/responses/__pycache__/response_input_text_param.cpython-310.pyc,, +openai/types/responses/__pycache__/response_item.cpython-310.pyc,, +openai/types/responses/__pycache__/response_item_list.cpython-310.pyc,, +openai/types/responses/__pycache__/response_local_environment.cpython-310.pyc,, +openai/types/responses/__pycache__/response_mcp_call_arguments_delta_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_mcp_call_arguments_done_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_mcp_call_completed_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_mcp_call_failed_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_mcp_call_in_progress_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_mcp_list_tools_completed_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_mcp_list_tools_failed_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_mcp_list_tools_in_progress_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_output_item.cpython-310.pyc,, +openai/types/responses/__pycache__/response_output_item_added_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_output_item_done_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_output_message.cpython-310.pyc,, +openai/types/responses/__pycache__/response_output_message_param.cpython-310.pyc,, +openai/types/responses/__pycache__/response_output_refusal.cpython-310.pyc,, +openai/types/responses/__pycache__/response_output_refusal_param.cpython-310.pyc,, +openai/types/responses/__pycache__/response_output_text.cpython-310.pyc,, +openai/types/responses/__pycache__/response_output_text_annotation_added_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_output_text_param.cpython-310.pyc,, +openai/types/responses/__pycache__/response_prompt.cpython-310.pyc,, +openai/types/responses/__pycache__/response_prompt_param.cpython-310.pyc,, +openai/types/responses/__pycache__/response_queued_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_reasoning_item.cpython-310.pyc,, +openai/types/responses/__pycache__/response_reasoning_item_param.cpython-310.pyc,, +openai/types/responses/__pycache__/response_reasoning_summary_part_added_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_reasoning_summary_part_done_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_reasoning_summary_text_delta_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_reasoning_summary_text_done_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_reasoning_text_delta_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_reasoning_text_done_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_refusal_delta_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_refusal_done_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_retrieve_params.cpython-310.pyc,, +openai/types/responses/__pycache__/response_status.cpython-310.pyc,, +openai/types/responses/__pycache__/response_stream_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_text_config.cpython-310.pyc,, +openai/types/responses/__pycache__/response_text_config_param.cpython-310.pyc,, +openai/types/responses/__pycache__/response_text_delta_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_text_done_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_tool_search_call.cpython-310.pyc,, +openai/types/responses/__pycache__/response_tool_search_output_item.cpython-310.pyc,, +openai/types/responses/__pycache__/response_tool_search_output_item_param.cpython-310.pyc,, +openai/types/responses/__pycache__/response_tool_search_output_item_param_param.cpython-310.pyc,, +openai/types/responses/__pycache__/response_usage.cpython-310.pyc,, +openai/types/responses/__pycache__/response_web_search_call_completed_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_web_search_call_in_progress_event.cpython-310.pyc,, +openai/types/responses/__pycache__/response_web_search_call_searching_event.cpython-310.pyc,, +openai/types/responses/__pycache__/responses_client_event.cpython-310.pyc,, +openai/types/responses/__pycache__/responses_client_event_param.cpython-310.pyc,, +openai/types/responses/__pycache__/responses_server_event.cpython-310.pyc,, +openai/types/responses/__pycache__/skill_reference.cpython-310.pyc,, +openai/types/responses/__pycache__/skill_reference_param.cpython-310.pyc,, +openai/types/responses/__pycache__/tool.cpython-310.pyc,, +openai/types/responses/__pycache__/tool_choice_allowed.cpython-310.pyc,, +openai/types/responses/__pycache__/tool_choice_allowed_param.cpython-310.pyc,, +openai/types/responses/__pycache__/tool_choice_apply_patch.cpython-310.pyc,, +openai/types/responses/__pycache__/tool_choice_apply_patch_param.cpython-310.pyc,, +openai/types/responses/__pycache__/tool_choice_custom.cpython-310.pyc,, +openai/types/responses/__pycache__/tool_choice_custom_param.cpython-310.pyc,, +openai/types/responses/__pycache__/tool_choice_function.cpython-310.pyc,, +openai/types/responses/__pycache__/tool_choice_function_param.cpython-310.pyc,, +openai/types/responses/__pycache__/tool_choice_mcp.cpython-310.pyc,, +openai/types/responses/__pycache__/tool_choice_mcp_param.cpython-310.pyc,, +openai/types/responses/__pycache__/tool_choice_options.cpython-310.pyc,, +openai/types/responses/__pycache__/tool_choice_shell.cpython-310.pyc,, +openai/types/responses/__pycache__/tool_choice_shell_param.cpython-310.pyc,, +openai/types/responses/__pycache__/tool_choice_types.cpython-310.pyc,, +openai/types/responses/__pycache__/tool_choice_types_param.cpython-310.pyc,, +openai/types/responses/__pycache__/tool_param.cpython-310.pyc,, +openai/types/responses/__pycache__/tool_search_tool.cpython-310.pyc,, +openai/types/responses/__pycache__/tool_search_tool_param.cpython-310.pyc,, +openai/types/responses/__pycache__/web_search_preview_tool.cpython-310.pyc,, +openai/types/responses/__pycache__/web_search_preview_tool_param.cpython-310.pyc,, +openai/types/responses/__pycache__/web_search_tool.cpython-310.pyc,, +openai/types/responses/__pycache__/web_search_tool_param.cpython-310.pyc,, +openai/types/responses/apply_patch_tool.py,sha256=gO_CtGczaXdBPe8zSW-aEqV_dVJhn22GAh9AE4-xEq4,399 +openai/types/responses/apply_patch_tool_param.py,sha256=k3kqGLeZ_f9vyXh7ZMmYVeQ-xcVUbGmo4ZAqM9HhgzI,455 +openai/types/responses/compacted_response.py,sha256=qlkdM6GmpFWCcqU11xODEMqD16DinPF0W-o70Hg5VOk,934 +openai/types/responses/computer_action.py,sha256=DjDkbkXQ0fcrofKYUFnFCYYvOWmeFlcfWUXZgb-FsW0,4264 +openai/types/responses/computer_action_list.py,sha256=li-EdxfB7-WEEJuv9bKadJDK7DTayj24JHbL0g7OVjo,284 +openai/types/responses/computer_action_list_param.py,sha256=ZEmGBg7rEMfCYWyp6XYQi3ScDmo171K41T7r_J4lzmg,4760 +openai/types/responses/computer_action_param.py,sha256=EFGvt1dYVWbJWbt9vworHOBYRKPJ9_6VknuntwfCBLk,4659 +openai/types/responses/computer_tool.py,sha256=tlBdHzMlmGKcExeoT-bUUOQkXayhzqjSs9RAbQOn93Q,470 +openai/types/responses/computer_tool_param.py,sha256=bIdba_E8QIJWyNu0Dp8Wy1Dm3VaCPclU_zCUGxmPIZc,526 +openai/types/responses/computer_use_preview_tool.py,sha256=zcfYzJ4pXXo9acw3_SjhtsgrtlvePrsLaO-CwJXiNt8,787 +openai/types/responses/computer_use_preview_tool_param.py,sha256=_-XqPZkUSIh5RJxgIXzl1m1EmKXpYvOTl81rcs0bRTY,873 +openai/types/responses/container_auto.py,sha256=ALGiZ7omgS-nhmnvwcB52B54OfmeDFFCKqriztG5Dlo,1387 +openai/types/responses/container_auto_param.py,sha256=IzrcQ54ZTaoHEa4dq8jygBUktBjBhQpGnrnw3V-cbjw,1359 +openai/types/responses/container_network_policy_allowlist.py,sha256=xKQdNX8ddFxLAmEmkJv5qORr807h6gWA2QS3131n_d8,736 +openai/types/responses/container_network_policy_allowlist_param.py,sha256=E8qJGGSTxtmlI7FYAGuRGOFUzAMqc7sMyGGA8JnRXmw,847 +openai/types/responses/container_network_policy_disabled.py,sha256=gmrNAer5PmJhpZQAMDHQuyN8od2SHDIyjAb6KMXg7rI,348 +openai/types/responses/container_network_policy_disabled_param.py,sha256=k2LMUTt7jqPRJgERySqUsXs6UkX5x-a650yHHT8ZAas,404 +openai/types/responses/container_network_policy_domain_secret.py,sha256=It8cbjYtQgm6wiFGx-c4YW2Z-sFEm6H_ClRpJBqourM,433 +openai/types/responses/container_network_policy_domain_secret_param.py,sha256=Se-NZucKb8zChehCbPsXWes5drDMk5gfWEtQetroBF8,539 +openai/types/responses/container_reference.py,sha256=8BLN-nu_nRDb27wriaC7C8BSKdFUo27zYjIaYnxtdOM,416 +openai/types/responses/container_reference_param.py,sha256=R-W99lrUaKLRHuOTKc155AMPD9e47f6VezcoTfn4mt8,482 +openai/types/responses/custom_tool.py,sha256=VLB-bfof6pjbc63QaQWmYUIdr5sPjtiqL8yytn4JFuw,1044 +openai/types/responses/custom_tool_param.py,sha256=4PgHoduxMi9eCPz-PqhS84ngLRdITI0jzKYjxgc8yA8,1039 +openai/types/responses/easy_input_message.py,sha256=b7oxdNML4LOUCkwYjQCF9wzCXzgOgxsphqr-Sb5RrDg,1575 +openai/types/responses/easy_input_message_param.py,sha256=-FNC4c6OU37r1qSZUoAf2x7a7M7GFpxEHxGdyefbw7U,1634 +openai/types/responses/file_search_tool.py,sha256=HpPWubu_JTVOxtRefDRDZkhTtWfoekHCqiL6B702j9w,2259 +openai/types/responses/file_search_tool_param.py,sha256=CvxYOB2DFpRC18WWa05En3heqTNd9Lv2SCZ7uP-ZOG8,2329 +openai/types/responses/function_shell_tool.py,sha256=JYwVq4qI0-kSFZC8AzUpURpWtmUFWp7vd7NnAA6WCTw,818 +openai/types/responses/function_shell_tool_param.py,sha256=dr84qrYV3cLajnpWoM3yukVGkJ6mjmo2br1fyAnAfyQ,811 +openai/types/responses/function_tool.py,sha256=yc-CSVGOxKtOfbeiroFSlEoU4fJNMWkg6WCD063_2q8,1092 +openai/types/responses/function_tool_param.py,sha256=DX4IeY_F9adyHF0LD-RvRgr6OAMj00_VmiaZOnO3xGQ,1140 +openai/types/responses/inline_skill.py,sha256=4LgbMvau2oySN6IX61oweApFwtgr8h4-6ZyvfslBpAw,521 +openai/types/responses/inline_skill_param.py,sha256=jK6lTQy3e0zRsGPwh6K__N2UBDl558UuGPxOcz_v-CI,624 +openai/types/responses/inline_skill_source.py,sha256=IY_jsg4K_jn5AAq8ak_kwN2NR02OmKOnaa8CYvEzybc,538 +openai/types/responses/inline_skill_source_param.py,sha256=0QPSdkUhMvlzP8jbKVdLrm0fjKxrlNs2UXY86yND9Qc,614 +openai/types/responses/input_item_list_params.py,sha256=wazm2tELpbpBWdAQrXGBq88Bm5RsxWXmlVJAV3f_k-I,964 +openai/types/responses/input_token_count_params.py,sha256=xyV3RTi5jJBEYh-dKVl0tZ1yvLgQo22p8HvJZ3qPDKU,5684 +openai/types/responses/input_token_count_response.py,sha256=w8LogkiqiItGuty0-bXts8xy1Ug-bbSYKEm7DDKmoP0,310 +openai/types/responses/local_environment.py,sha256=HZR6za_LqRHnYOxCD8kIYdzKTUlUrZ3M2bBLssLDg5g,454 +openai/types/responses/local_environment_param.py,sha256=LAiH3gO24X8JmKSXI70bxVX65CQRGIyA3dSidozZMeA,508 +openai/types/responses/local_skill.py,sha256=OElgxKtJ_APlKukl5JFsqsvC8iq9WFPYOYTcw0GYIJs,359 +openai/types/responses/local_skill_param.py,sha256=DLP8b5tptYNCXrIDu2CorO3X38eZ0gm1YX90mdKRPas,465 +openai/types/responses/namespace_tool.py,sha256=_HpZ0gs_09yniaqHozCUyVwgbbQtVZoy8MYzt8Lh10c,1206 +openai/types/responses/namespace_tool_param.py,sha256=M4-_H-hmQh1j_O1F-fgl5ZLVrUsyuuubBXKSxePq-e8,1219 +openai/types/responses/parsed_response.py,sha256=hU-MkhoRK2VKaYVKFt9w3Pvp0GL2IufXCxPuPHSsTU8,4553 +openai/types/responses/response.py,sha256=zC5XhethSNLzZjR01lSxBVyQ4ODbnlOzyLjDWtaW4Fw,12721 +openai/types/responses/response_apply_patch_tool_call.py,sha256=dmqjz9eTdk5WNkxxWhuJayZ-ALygsPXTosRW6B9r4oQ,2217 +openai/types/responses/response_apply_patch_tool_call_output.py,sha256=Y3ZxBSHXFAv1yaUfpf_XOFZwvAgSKiBB6Bw8fOYEsvw,1024 +openai/types/responses/response_audio_delta_event.py,sha256=JWICz6tC6Zs-8Ax3y3hkUahWE2vxwJLLVguhDQJWzhk,574 +openai/types/responses/response_audio_done_event.py,sha256=8wQI1KQcdEBSC7_IGWGVgHfjEWSaEEwTdOglsyj8dWo,470 +openai/types/responses/response_audio_transcript_delta_event.py,sha256=ekRu3IEU7rZRzoSFu2K98btqFDm_vz1aunOl5Q_WvtA,597 +openai/types/responses/response_audio_transcript_done_event.py,sha256=mP_kZAh8gDCQ01ekkygstR6F5oD-s-8Ycfb1ZRGo_v4,521 +openai/types/responses/response_code_interpreter_call_code_delta_event.py,sha256=nxweCYi0ARKFednUF9Hya8lyuLqc1VqKquYbB4fRqvY,924 +openai/types/responses/response_code_interpreter_call_code_done_event.py,sha256=dZl7A5ZEdN-fyJG-d7XbBdkQ-cLrlcEaZ5f5nzwPGu0,885 +openai/types/responses/response_code_interpreter_call_completed_event.py,sha256=rUQ3-3KER-MRvNgUPuUyv5q6o7KsWqsQWZrjFzDscmE,823 +openai/types/responses/response_code_interpreter_call_in_progress_event.py,sha256=gC-u3RAQ08IcD9p2imVX27goYwH-HvukhScwLVORMfU,831 +openai/types/responses/response_code_interpreter_call_interpreting_event.py,sha256=gOWRUvIgcMVrp-KcmtAttp8PbeVknhmCmfgYg04-2K4,862 +openai/types/responses/response_code_interpreter_tool_call.py,sha256=r1NjHpBWawfNwy5-2gVoJjc1rjrHk2jJjlGsoAIU55I,1795 +openai/types/responses/response_code_interpreter_tool_call_param.py,sha256=uaywHPXN7U5uh9b7bi5xFL6xvXRM7lTJihYdZbi84Zw,1868 +openai/types/responses/response_compact_params.py,sha256=y1jZiNTa46aRRfl4m8BdIA2OnRaJmc09Q6w5fKj3Pok,5251 +openai/types/responses/response_compaction_item.py,sha256=FevR74gnDtJkGYJKhwaPHUMqDXkHxpPojBBgip93NK4,758 +openai/types/responses/response_compaction_item_param.py,sha256=cCRvAVU1LSLWhryYp54lU2j00wwHiaogpDcXBULI3PQ,673 +openai/types/responses/response_compaction_item_param_param.py,sha256=UYpgNuwAxAd11LxXJJ-EPHGLWR3TDP00lylHxytE6K4,732 +openai/types/responses/response_completed_event.py,sha256=fe5mGXdeFLkozUpasDitkCHe7Qv22xKUesRDNFcXazY,573 +openai/types/responses/response_computer_tool_call.py,sha256=LzcCIS2apardV9yWVh7s4RWCf4p4IH2E8lbaDrcVm38,5981 +openai/types/responses/response_computer_tool_call_output_item.py,sha256=WdgOAAba3uuG6qnbRjSnhm-QO_B31jfvUvDrIzZTrj4,1676 +openai/types/responses/response_computer_tool_call_output_screenshot.py,sha256=rhc-E2ECWZOqpvIFcVo7fi-j9rS94AwXU_1xuVyUYKc,734 +openai/types/responses/response_computer_tool_call_output_screenshot_param.py,sha256=iRdRiNE-wpwaNhBfnilJ4GaouMGh-oWn121LkSzDBA4,728 +openai/types/responses/response_computer_tool_call_param.py,sha256=kYKqyhHvQf_JrykguqPL26BCzLBE3P5RWo4pI9dQqSE,6389 +openai/types/responses/response_container_reference.py,sha256=QSKDvn-y5snt0t0wFD9tAU9hphgxlyrEGW9zQPE87ak,437 +openai/types/responses/response_content_part_added_event.py,sha256=lpdjp8MXrniMjY5aEchgOXAYx9nCRzqsGcm10A7k9oA,1432 +openai/types/responses/response_content_part_done_event.py,sha256=QHR1gB9E8AeAxL30xp2pTVr8YQxEojwozkZqJ-s_45E,1419 +openai/types/responses/response_conversation_param.py,sha256=NjSUgUHujBYPv_r1A3lYCWZrlZ8LOOGeRQX4TGWROss,323 +openai/types/responses/response_conversation_param_param.py,sha256=m-Uv1dNpMKXzHBrTF_lRTL5PzVYrEMykki-oAQnUvVo,409 +openai/types/responses/response_create_params.py,sha256=a8xEImaWtye7GOPIo6TE1AM_eoqwd7zCtRRaXirvXIw,14585 +openai/types/responses/response_created_event.py,sha256=3q0JhFTkp3vgkkJdjFzgLG690GfDFFfnpXrsjl81ES8,566 +openai/types/responses/response_custom_tool_call.py,sha256=bPBoDszKZZkIUGvN_5FMnrhzmDqpKg-opmFZA6kBWC8,881 +openai/types/responses/response_custom_tool_call_input_delta_event.py,sha256=70JVIwG8KfTnW2zzovAdDv-qIyvJU8cY2aQcxHiDPKw,786 +openai/types/responses/response_custom_tool_call_input_done_event.py,sha256=QQ8V5TNyMOdLRSQ1hxCCw2_LjxERccGqvXjjnUrvc_8,756 +openai/types/responses/response_custom_tool_call_item.py,sha256=68cRQA21U3HpFZqu5mCxHH8ReGAZCWEfdfIvD5qNhDY,762 +openai/types/responses/response_custom_tool_call_output.py,sha256=w2yJcnkB48PfpBvLikpUx_Iz8ryKuS7WtqyqsECr0ps,1307 +openai/types/responses/response_custom_tool_call_output_item.py,sha256=-IgN0G70UnJZPSRf6-25pfiiaH1kyD5D1ekJJs7x6gQ,833 +openai/types/responses/response_custom_tool_call_output_param.py,sha256=Nr6hV5PHkOeDRR3INuiyPtpk3ybd4zwLbMKYEfkv1Hw,1314 +openai/types/responses/response_custom_tool_call_param.py,sha256=BJk84KI0XoOeL_-wtbcqsa-EN6q9NADYJZ35XJiesCc,905 +openai/types/responses/response_error.py,sha256=AszYOuu1LOWaglgKy9tX9zO9q7Yid9alJc2cKINk9ro,996 +openai/types/responses/response_error_event.py,sha256=fjB964eSWEh0ciSk5s64TQGJyTsYjtNT8duSqztjhW0,617 +openai/types/responses/response_failed_event.py,sha256=FG812T2EKLJwrSyO8KPbs-QSpsg1e4n8YHpXiANlb04,551 +openai/types/responses/response_file_search_call_completed_event.py,sha256=gE4Zju0_edN_9zfOc07K7BepToGCjdOIBvqQx-jwfqM,744 +openai/types/responses/response_file_search_call_in_progress_event.py,sha256=0SKVai4oBjI9ayOjSZw4HlX5Alsm1QOUEe_UEM8EedE,734 +openai/types/responses/response_file_search_call_searching_event.py,sha256=h39eY-lBOJiN-9M1xKdbsij8nVe7CoJHRq1ncE4Djog,733 +openai/types/responses/response_file_search_tool_call.py,sha256=kz4aytPWtfajEkJjtxW395Gy_IZC90uSQr0gcFOqqPw,1838 +openai/types/responses/response_file_search_tool_call_param.py,sha256=rnHg_KmMbyduAwzE1iC6QcenZSMtAmrNq1r9hojH75M,1911 +openai/types/responses/response_format_text_config.py,sha256=Z1uv9YytZAXaMtD_faYD6SL9Q8kOjSvRQXFkSZc0_hY,647 +openai/types/responses/response_format_text_config_param.py,sha256=T6cMHds5NYojK9fZMMldWYBypWwVmywIIbkRm5e4pMc,625 +openai/types/responses/response_format_text_json_schema_config.py,sha256=qjE8Yx2p7fT2KUoEtlwEbgqqV11FwdWdmXdrEsEUAP0,1611 +openai/types/responses/response_format_text_json_schema_config_param.py,sha256=kmkEvymu058oqJngIz5ir0XKTDGbfRbc6G2GKJWa5SA,1593 +openai/types/responses/response_function_call_arguments_delta_event.py,sha256=EKF5hkCH9qMKFzVhIxatJJiXrcyG8HGByep0hi5h-w4,866 +openai/types/responses/response_function_call_arguments_done_event.py,sha256=483jGS7xNW-VSivfrgFCox5WI9AXakYRN3KaTVZ5Zzk,702 +openai/types/responses/response_function_call_output_item.py,sha256=mkRJ2mCmrrmjRbvijxt-zHw9eLU6-aLjM6___SmTiTw,633 +openai/types/responses/response_function_call_output_item_list.py,sha256=5NYWEt_FNPCyQVRMiIJDJt4fYV6GWUwbW9S8hCucIpw,367 +openai/types/responses/response_function_call_output_item_list_param.py,sha256=y6vpVbdTGurYpDVbg0UFp4GhSMtwYRium9Z5bbiyyuE,774 +openai/types/responses/response_function_call_output_item_param.py,sha256=VEe_wQ8z9PN0qJbLuCwfg9n4Lwe5-WNljzmNJ-fqnwM,629 +openai/types/responses/response_function_shell_call_output_content.py,sha256=QZlIb_3DHE9BX5W6HmdDEY14Vwy5c295707BzgH1Z_Q,1260 +openai/types/responses/response_function_shell_call_output_content_param.py,sha256=e8nFAciWLudLRQxr-CNH8U_9Nge65cZ6M1d-ZqE_h8g,1299 +openai/types/responses/response_function_shell_tool_call.py,sha256=Zi7ccDiGXEMZGw3BKDDEhpK9m_wR3XWt0Q8cHDw-9nU,1879 +openai/types/responses/response_function_shell_tool_call_output.py,sha256=mH94PBtKr9zXzb2RirDijvWXoNidElxPidqdYskMZ2c,2435 +openai/types/responses/response_function_tool_call.py,sha256=V4Cf292PPbK_agJEA-IfcQ5xzVowLy3sRO7dNtCXpVM,1171 +openai/types/responses/response_function_tool_call_item.py,sha256=PHesdM51kgNuiScu2b-UoYewAA3Gf93fiwoEuDJwL00,897 +openai/types/responses/response_function_tool_call_output_item.py,sha256=dPLQ5D0dq2YM-gQcOm3Gf37fW1Sg1k0NSoa7rp-k5G4,1476 +openai/types/responses/response_function_tool_call_param.py,sha256=YLIx22-QGyB9NdwZQRWK6Hh2vrNPQTCN9DKa_vOcfYQ,1178 +openai/types/responses/response_function_web_search.py,sha256=-CoTjkdMSJHmmdpDWlj5kcJ9ov6wA66LLFfsAhC1_Js,2375 +openai/types/responses/response_function_web_search_param.py,sha256=HgcLvlhOrRGsV4ylv_OqC6hTiGggQ9Jrqm92dwspuwI,2515 +openai/types/responses/response_image_gen_call_completed_event.py,sha256=4EVne_sRTbCxuPTTdt7YMRBblpH8nR3in4PkzzrHxBE,783 +openai/types/responses/response_image_gen_call_generating_event.py,sha256=Xu-lJZAHRZTDbiOGRVOBLCmXnAbHFQBYNRmPab2pFug,824 +openai/types/responses/response_image_gen_call_in_progress_event.py,sha256=LvCFXfC7VNqmZegn_b4xy021H-qO08SzGOspvK-6Wew,778 +openai/types/responses/response_image_gen_call_partial_image_event.py,sha256=Iss5tU9uBlv9qdnLMsnRh2g0rRJL5BDW04TTUHD8Shc,1059 +openai/types/responses/response_in_progress_event.py,sha256=oi8YtsItiH0TloP7rbkm0-XOY1-FKTV4o6Ia_y4pS6Q,571 +openai/types/responses/response_includable.py,sha256=tkia-hgFh4ttgy53H5lJtoBWsSQh6G2DzCXj-14o8Ko,505 +openai/types/responses/response_incomplete_event.py,sha256=WGBjWI-kwdaQpGBqzrIKfTehJ4Phzxsn2fvfDYoTV6w,592 +openai/types/responses/response_input.py,sha256=AMsHCZPd90LJYdaIbsDdKt_PtFHi9JbKUZIl8r07PUg,284 +openai/types/responses/response_input_audio.py,sha256=CLnaiuQjjF11emjSxbVBLL0yF_kONznqXgIB6m8lric,614 +openai/types/responses/response_input_audio_param.py,sha256=MXXWtLXdToypWHQYLSpfUXtC2U_PllaffzJLMy5LNYY,713 +openai/types/responses/response_input_content.py,sha256=MaZ-MNnZvhM2stSUKdhofXrdM9BzFjSJQal7UDVAQaI,542 +openai/types/responses/response_input_content_param.py,sha256=1q_4oG8Q0DAGnQlS-OBNZxMD7k69jfra7AnXkkqfyr4,537 +openai/types/responses/response_input_file.py,sha256=QIyszN_7qnpVxPKD9alwrCAzfrnPMPJYTEPGTAX-PqY,999 +openai/types/responses/response_input_file_content.py,sha256=UWvsJrrE8DHlADsfgvpHlc_k5G1_KFXWzJEmZSimmpc,1025 +openai/types/responses/response_input_file_content_param.py,sha256=MeoWQ6nWquRy_bwxr2HZujSck5UaEM_PxMCyblAl3I4,1036 +openai/types/responses/response_input_file_param.py,sha256=Uj2Sm2P4pbdD9Mg6TRl3q3cT29VWu9IqBO54ROC0CaI,980 +openai/types/responses/response_input_image.py,sha256=bS-0UYC6BXCDdwQ-b_vNoLT__hbjvdYK36ofwD_BIJw,928 +openai/types/responses/response_input_image_content.py,sha256=zlPxUmcAH3odBUY1XeIgWWstjGgUAP765ahZE8miktY,958 +openai/types/responses/response_input_image_content_param.py,sha256=nsll-Xnjkzv-EdZdLGrtXv7qrqK5ZM5DuYgnuRPs0K0,993 +openai/types/responses/response_input_image_param.py,sha256=jNhUX0syVx65g56bsOMNW4dNASfvrq7WHCw8kg56Qtg,980 +openai/types/responses/response_input_item.py,sha256=8kBwcRi5WLFXn08z390ZJhFLoWic68EKR74r1wUtluE,17265 +openai/types/responses/response_input_item_param.py,sha256=9yQKi1UaGcd0gRiFZjyReSuhDOg-hb8dnWdk6z-a914,17995 +openai/types/responses/response_input_message_content_list.py,sha256=LEaQ_x6dRt3w5Sl7R-Ewu89KlLyGFhMf31OHAHPD3U8,329 +openai/types/responses/response_input_message_content_list_param.py,sha256=cbbqvs4PcK8CRsNCQqoA4w6stJCRNOQSiJozwC18urs,666 +openai/types/responses/response_input_message_item.py,sha256=4nxX-UlZ7CFeso4-NiHaKc1mIGD-akFBGCMjy-TETD0,1012 +openai/types/responses/response_input_param.py,sha256=BKgnfnLJhcMBPF0rClznh2RSuPnqkv4UOr5kZeEKfl8,18089 +openai/types/responses/response_input_text.py,sha256=uCT-nKv5EEjOHmTyBlKJ01gLSCGue8lcjrBwzwWzPrE,413 +openai/types/responses/response_input_text_content.py,sha256=UPb4d4KHkbgN0rS6wkvoaTPZVGN_2aYo-VbL-zwMkpU,427 +openai/types/responses/response_input_text_content_param.py,sha256=nAOZRT6FsZqPr0va99wAFVB1lz5W8cinZ-9iEuAHgN0,493 +openai/types/responses/response_input_text_param.py,sha256=9DbrdxWlak_wHmcPhw9BIVlyWkBnuAfmYC4TDtM_Lqo,479 +openai/types/responses/response_item.py,sha256=RceWRQm4--slsdQRaMjXLtSeXG_u9gpuey7toydYTr8,7980 +openai/types/responses/response_item_list.py,sha256=JclJxBBJda7fjXVbeLfYeVUH8A_swQN24LWpUjIsuus,702 +openai/types/responses/response_local_environment.py,sha256=n5-0mDusTkCjp9CFxFHW3lUxM3_RApWz-Qav4dnsNrU,398 +openai/types/responses/response_mcp_call_arguments_delta_event.py,sha256=EUCaFYd-EgZS9zikqlXi8xqUzeC94MzVx2qrhUgm4a0,884 +openai/types/responses/response_mcp_call_arguments_done_event.py,sha256=LWMaw5HKV8AgiYNJxTB-14kmCcFc_T22tSCdqJjlp3Y,826 +openai/types/responses/response_mcp_call_completed_event.py,sha256=MFjkI21vxzlTzvEAvmRjntJ3vGCeDTViMFek6AIyQXM,670 +openai/types/responses/response_mcp_call_failed_event.py,sha256=bhC0gZ4b2qZPrux4Le6_ZDthm22Ck1wGZ6G5Mf0wsPQ,636 +openai/types/responses/response_mcp_call_in_progress_event.py,sha256=oTLlZyhdLsnnkZj4Fr3WYF2QRnupgdT6_4FIVl8gjUg,696 +openai/types/responses/response_mcp_list_tools_completed_event.py,sha256=3OdrqmMVVUgVTwl2nOf5vQ-4VVcbfS6VoF3G7z5DOjU,726 +openai/types/responses/response_mcp_list_tools_failed_event.py,sha256=9nvFQ-02kRXV6nOf_4o5aQhYw7-tSzppLbN-C7a2zHE,680 +openai/types/responses/response_mcp_list_tools_in_progress_event.py,sha256=V9IqBnh-oLKqtthuGA3LDNveWzx10kd2N6x3MpzATzM,756 +openai/types/responses/response_output_item.py,sha256=FAp4k-SgthM72nKlxQKvZ3GvzQcEk7yiX9388A86OHc,7866 +openai/types/responses/response_output_item_added_event.py,sha256=6rIwK1Dtgu2K0t1R2ForK1C70CUpcnihqMpWqlM0jtg,696 +openai/types/responses/response_output_item_done_event.py,sha256=n-T9NinnYm0xhOmPfDhqKso0JQYVhfs0IXa1MhkA2cc,707 +openai/types/responses/response_output_message.py,sha256=AH_2iyIM4mueix_xUv8b6PsEPTNUTX0aLHjYTwH7m3A,1566 +openai/types/responses/response_output_message_param.py,sha256=POWvupoVO0TWALFzZgZ-M5IhP89IrPraVFdokpCsaTs,1603 +openai/types/responses/response_output_refusal.py,sha256=VkWPvAhqWz3mZ_7X8CZA4CPjgCfkWpAsrUL_EEAp3mY,425 +openai/types/responses/response_output_refusal_param.py,sha256=RO2CI71fbzQPwsr3URyR-EP20oRNMaWAmLj9dMDeu1o,491 +openai/types/responses/response_output_text.py,sha256=LPESiPQE6UcQFa1bHRFr-Dxsvbyqc6UoCDsauGDAev0,3157 +openai/types/responses/response_output_text_annotation_added_event.py,sha256=Eg-nDtkqOX51T-kJOjUFVd_2vnnk6Ah1rE3lCdYe3f0,1034 +openai/types/responses/response_output_text_param.py,sha256=3G84IlzqWmex9echpQUFApOWLra_oWvwbBiweX6NFtU,3460 +openai/types/responses/response_prompt.py,sha256=YYeJIp7WbLKe8Y1EieKpNgRHSIqArcx9OdSBeAInPRk,1107 +openai/types/responses/response_prompt_param.py,sha256=n0Kh9RsuVkgfFlll_fwaSPmQ91iJoJXDEX2yQw97eEg,1198 +openai/types/responses/response_queued_event.py,sha256=yr1KhJ27RjkFrKFmTx1uncSpR5t5-RHEXOBTyFaazUc,582 +openai/types/responses/response_reasoning_item.py,sha256=Rxg9gZDFhwR_eswynvNae2NCa0BYGCqB0OkijLwfl8A,1843 +openai/types/responses/response_reasoning_item_param.py,sha256=rKLmJVQdld2ZNlo6VylJmeyScXGE3aRPF9gUiYj5UbE,1956 +openai/types/responses/response_reasoning_summary_part_added_event.py,sha256=z6fdUEOQYdkbM2Kbv-qR39uqLScYWHozlZc43AaUy_U,1113 +openai/types/responses/response_reasoning_summary_part_done_event.py,sha256=IVAfLcKqV0tN5DlcHoWj-7kgHPCJIZuRO2tjautGVag,1099 +openai/types/responses/response_reasoning_summary_text_delta_event.py,sha256=dtVBDqeHnL6rqfKkqS9S48iEG40XeL7HPHedYvAtPfo,916 +openai/types/responses/response_reasoning_summary_text_done_event.py,sha256=mKK-nrU1DChaUyRYLw0hKChMvYovs6e19ZChJDuW69I,896 +openai/types/responses/response_reasoning_text_delta_event.py,sha256=3_UV-GjQdCNjqpmABpDrxovTKqQIyJa_K5fKemPcezA,903 +openai/types/responses/response_reasoning_text_done_event.py,sha256=M9AZZ7cHvXj4NthBIsYEbY2h_RzFcn2YJ37_mXd_Q9M,843 +openai/types/responses/response_refusal_delta_event.py,sha256=nqAEXShLQDV84Qd2pr7po-UnzW3aJxgXCNNivmJHQOQ,827 +openai/types/responses/response_refusal_done_event.py,sha256=y-Dtjpa0CCA0hqqC8O_m5tRqKoSJayhYpTTBFDXOvK0,826 +openai/types/responses/response_retrieve_params.py,sha256=Y_4UacCQ7xUYXc7_QTCJt-zLzIuv-PWocNQ1k0RnPsw,2372 +openai/types/responses/response_status.py,sha256=289NTnFcyk0195A2E15KDILXNLpHbfo6q4tcvezYWgs,278 +openai/types/responses/response_stream_event.py,sha256=uPEbNTxXOaiEFRVt_PbdeecyfS9rgjaYU7m15NIvSbo,6916 +openai/types/responses/response_text_config.py,sha256=8mk0TYDQB9VNJxKAazvCHy3WIzOpPgmn95qLkwToK6o,1655 +openai/types/responses/response_text_config_param.py,sha256=Wq9RvKd2ZlOBRsTaUxWRmSekcQxH8mMoYJZGp2QHY30,1684 +openai/types/responses/response_text_delta_event.py,sha256=FO8mXzeZtLFVLouQd8ORw9RO2oCg-rNP1-jOm4Tkp5E,1696 +openai/types/responses/response_text_done_event.py,sha256=Tv5tAT9mQ9RQY7QPS1F1IFCDCPGxsypTD_aHK1FwzFo,1694 +openai/types/responses/response_tool_search_call.py,sha256=eLW0R-W4o2G3uYG3w9aqQSHDutOpjtFbmz69VZj7kew,963 +openai/types/responses/response_tool_search_output_item.py,sha256=92tXUFGFGZv_LDxWjJ7kaPjVR2w0j2HvhS4yiA-sg7k,1024 +openai/types/responses/response_tool_search_output_item_param.py,sha256=Pb4EshS1m1b_cypFI95R4beSiSztaJcfm8xDefs3ZVM,963 +openai/types/responses/response_tool_search_output_item_param_param.py,sha256=c46h1RVfeV_76h6TgadTBMie6WDyaOOid6NVkQHg8ig,1016 +openai/types/responses/response_usage.py,sha256=g1YqV35FbWEsFkDyXyQ95gK1CPT2vXaEj7dx35Nyllo,1204 +openai/types/responses/response_web_search_call_completed_event.py,sha256=huESBkfYVrHZUHUHeRknBgw7bMrIYEsVryEZrXHMiGc,754 +openai/types/responses/response_web_search_call_in_progress_event.py,sha256=MQIZTtd3LqdX4C46cG-vOSeNaLxQFvM2FaCfiDwUits,760 +openai/types/responses/response_web_search_call_searching_event.py,sha256=UucDvOvM6VjzBgCkwVO-UvRbttfidcBVCQdvgw-NUJk,754 +openai/types/responses/responses_client_event.py,sha256=-fWeAu4FuSOGunnE2SkUAz7kEql63957On4Q8sgcLUQ,13903 +openai/types/responses/responses_client_event_param.py,sha256=G8ia9_pwV9pIj0Do0oxnTquVrQKeq3edHAtiGu0xCCE,13918 +openai/types/responses/responses_server_event.py,sha256=LIMNujT4lLQDQ61xPmP62fE_nqhKExpNtYC54xkUXno,6918 +openai/types/responses/skill_reference.py,sha256=Ar8pzoXWFt5fDiHd9qtsrCsWalGHAoj1VjFCdacq1gw,540 +openai/types/responses/skill_reference_param.py,sha256=A8PjP6gdQ9q7V_Qmrcj8qi0lgCP-yNTiB1FlgVTkMIc,561 +openai/types/responses/tool.py,sha256=gvoNAcgHEzZMObwEOfNSzSUfZLL4UQBfsO8Me6lVuFs,12485 +openai/types/responses/tool_choice_allowed.py,sha256=Mq18Us-Yd-59WZppbXaWYjBPtUqSbHHE48IWCHdLFCI,1100 +openai/types/responses/tool_choice_allowed_param.py,sha256=6Yk0zOe8QGzTyrReDIEy56o3opFvPbS0FeuBN6DW8CM,1184 +openai/types/responses/tool_choice_apply_patch.py,sha256=zUFufN0Okg40AkOM3QmzUxtRX4DQKwR52fYQYdQDECk,404 +openai/types/responses/tool_choice_apply_patch_param.py,sha256=DVgCdqmlWw1hMyDigUfUU8O7R7nQahuPqEYL6rq2y24,460 +openai/types/responses/tool_choice_custom.py,sha256=W-rAidO4Rf7Hf-EE-K_hIJwjPiiASxo5Vt7t8wQCFSA,460 +openai/types/responses/tool_choice_custom_param.py,sha256=SygHwvYJsXDSPAVjsxWqioSZd0Gc1oayMlbZUcR5BlA,526 +openai/types/responses/tool_choice_function.py,sha256=ZmF4VEQWTEcLrj7IEBqVX8kQv5Mf_sf0FJDffs0uIog,459 +openai/types/responses/tool_choice_function_param.py,sha256=RfRfJNf27JsZBNYjabLnFgksPFZJIrkdy3ouVGdNrF8,525 +openai/types/responses/tool_choice_mcp.py,sha256=z3k0i7zbJyp4DBvKs-OsvWdMOFrm0CNSgCyB0nEqnBE,585 +openai/types/responses/tool_choice_mcp_param.py,sha256=-cnA3zk3wMmx93CkCwwOBiw3CROD2UanAmdQm__Gow0,644 +openai/types/responses/tool_choice_options.py,sha256=gJHrNT72mRECrN7hQKRHAOA-OS0JJo51YnXvUcMfqMQ,237 +openai/types/responses/tool_choice_shell.py,sha256=5k4381juLRA_qZc_h4x0DGtnW6wkSKAogWfnYLMEPxk,378 +openai/types/responses/tool_choice_shell_param.py,sha256=Qy0ySbnh_0eDYPJwzn5iHoHHuo79HAHwkk8zRhNYtdY,434 +openai/types/responses/tool_choice_types.py,sha256=a4hzq9AUvvXSPrjENn2osPPv984GYPbxn4UtTC9ivCc,1005 +openai/types/responses/tool_choice_types_param.py,sha256=HlrHFQ_RQw8hU2mqJjGKTmCA0wxK3KybQOfJQ-YhqJo,1111 +openai/types/responses/tool_param.py,sha256=nHGhXlvR3t3hlfXuvwHWNgzBIbXw2-N2w-lvBKI61KI,12426 +openai/types/responses/tool_search_tool.py,sha256=2PQnoOHaX4l2SFbaWmyYkqE6cCJm8gAYZqB-maAwtL4,774 +openai/types/responses/tool_search_tool_param.py,sha256=-GgHVU7HJE1xla2Vq8JqJ2sUgu2PJiXiHKFaSScQgj4,799 +openai/types/responses/web_search_preview_tool.py,sha256=ju0wvshkP_qFTGdXvT04bz06F0vSIsv_pCSNBhRfCn8,1771 +openai/types/responses/web_search_preview_tool_param.py,sha256=et38nUI-q2mElq8-8Xe0vVeUMbzZkOaA2D5rBr6AWvg,1781 +openai/types/responses/web_search_tool.py,sha256=rsN2LrO25vAvIVEl3sKCiLS5pAqvwxJyam0Cgys419g,2083 +openai/types/responses/web_search_tool_param.py,sha256=pXX6qVRcsVNBDhy91nHM0svtpzvKVoAPIg7ciOXmctg,2124 +openai/types/shared/__init__.py,sha256=rzdopc9nZmnXm-Am0Ix3s95nmQvfCWmhwVM6mG5oL2E,1330 +openai/types/shared/__pycache__/__init__.cpython-310.pyc,, +openai/types/shared/__pycache__/all_models.cpython-310.pyc,, +openai/types/shared/__pycache__/chat_model.cpython-310.pyc,, +openai/types/shared/__pycache__/comparison_filter.cpython-310.pyc,, +openai/types/shared/__pycache__/compound_filter.cpython-310.pyc,, +openai/types/shared/__pycache__/custom_tool_input_format.cpython-310.pyc,, +openai/types/shared/__pycache__/error_object.cpython-310.pyc,, +openai/types/shared/__pycache__/function_definition.cpython-310.pyc,, +openai/types/shared/__pycache__/function_parameters.cpython-310.pyc,, +openai/types/shared/__pycache__/metadata.cpython-310.pyc,, +openai/types/shared/__pycache__/oauth_error_code.cpython-310.pyc,, +openai/types/shared/__pycache__/reasoning.cpython-310.pyc,, +openai/types/shared/__pycache__/reasoning_effort.cpython-310.pyc,, +openai/types/shared/__pycache__/response_format_json_object.cpython-310.pyc,, +openai/types/shared/__pycache__/response_format_json_schema.cpython-310.pyc,, +openai/types/shared/__pycache__/response_format_text.cpython-310.pyc,, +openai/types/shared/__pycache__/response_format_text_grammar.cpython-310.pyc,, +openai/types/shared/__pycache__/response_format_text_python.cpython-310.pyc,, +openai/types/shared/__pycache__/responses_model.cpython-310.pyc,, +openai/types/shared/all_models.py,sha256=OggdrF27d8_oCWAsE-LyQQmtjflAesmOyogIvi-atAs,716 +openai/types/shared/chat_model.py,sha256=eanzUPrDvIwQq6oXG7sYa701rHy4uFgwosQltBuXeyw,2101 +openai/types/shared/comparison_filter.py,sha256=bpckFBnrbznCZ1lf7l9Xha7AZ_uama7_qSbAsuJPRr0,994 +openai/types/shared/compound_filter.py,sha256=Dk2EVAI9kgojEKyeaXnIsu93rz8kKPERW0y5Y9LpdzY,638 +openai/types/shared/custom_tool_input_format.py,sha256=qgYtTA-5KQssG4TCdI2V2s83GcNQHhHczjSQVj4oIhg,856 +openai/types/shared/error_object.py,sha256=G7SGPZ9Qw3gewTKbi3fK69eM6L2Ur0C2D57N8iEapJA,305 +openai/types/shared/function_definition.py,sha256=2F07J5Q7r2Iwg74dC5rarhwWTnt579Y5LUrNc8OdqSc,1475 +openai/types/shared/function_parameters.py,sha256=Dkc_pm98zCKyouQmYrl934cK8ZWX7heY_IIyunW8x7c,236 +openai/types/shared/metadata.py,sha256=DC0SFof2EeVvFK0EsmQH8W5b_HnpI_bdp47s51E5LKw,213 +openai/types/shared/oauth_error_code.py,sha256=obyk-3ZtHdz16b79-3TTss4BNNcxOjh8vmxpM-KcSrU,282 +openai/types/shared/reasoning.py,sha256=SnHlaG2jXpvgvUQ_d7Gp0WPcC8tG3AtGGfP7B357rt0,2011 +openai/types/shared/reasoning_effort.py,sha256=1t5QFutihQBbHg0rbwsCCmfLs1wTT7TPDyH5iUIvVSo,296 +openai/types/shared/response_format_json_object.py,sha256=XXcdZ9Sx6o6gTrF73MayEITLmCtnnwo-HjjI7dbnzOg,624 +openai/types/shared/response_format_json_schema.py,sha256=Dujs9kHbLPk1dVIcMEerJ54OLyDC3svF_aXaX5SaRec,1843 +openai/types/shared/response_format_text.py,sha256=klc3lCY1T1M-lX6Dd6MnMUuNZH2sxoZqZcRymDrahlM,395 +openai/types/shared/response_format_text_grammar.py,sha256=zjIlUfFTCfAyLCc4fmiV3IA-q1Rjcjzui97bCSVV2NY,606 +openai/types/shared/response_format_text_python.py,sha256=hWrzEgdP1hUAX80Slc-UddodqFE3HDEWM8w0T0tADr0,525 +openai/types/shared/responses_model.py,sha256=Ot5_u8itwSMhVUhZ8rHnt5Bdj2eI_Ux76WHQ8xKHt7E,726 +openai/types/shared_params/__init__.py,sha256=C6VX5UW34pTTDVkk76TnwzFAlftRB_sG0EEFFWUdZms,1039 +openai/types/shared_params/__pycache__/__init__.cpython-310.pyc,, +openai/types/shared_params/__pycache__/chat_model.cpython-310.pyc,, +openai/types/shared_params/__pycache__/comparison_filter.cpython-310.pyc,, +openai/types/shared_params/__pycache__/compound_filter.cpython-310.pyc,, +openai/types/shared_params/__pycache__/custom_tool_input_format.cpython-310.pyc,, +openai/types/shared_params/__pycache__/function_definition.cpython-310.pyc,, +openai/types/shared_params/__pycache__/function_parameters.cpython-310.pyc,, +openai/types/shared_params/__pycache__/metadata.cpython-310.pyc,, +openai/types/shared_params/__pycache__/oauth_error_code.cpython-310.pyc,, +openai/types/shared_params/__pycache__/reasoning.cpython-310.pyc,, +openai/types/shared_params/__pycache__/reasoning_effort.cpython-310.pyc,, +openai/types/shared_params/__pycache__/response_format_json_object.cpython-310.pyc,, +openai/types/shared_params/__pycache__/response_format_json_schema.cpython-310.pyc,, +openai/types/shared_params/__pycache__/response_format_text.cpython-310.pyc,, +openai/types/shared_params/__pycache__/responses_model.cpython-310.pyc,, +openai/types/shared_params/chat_model.py,sha256=wAR-4oRZzueww1WHi5KvccbeVP5HPxe7aNfDlVl-QXU,2137 +openai/types/shared_params/comparison_filter.py,sha256=OTaWOJD15rkcK2aB1f29lIyd3UHCU3C1fWYhAA8Fx6A,1102 +openai/types/shared_params/compound_filter.py,sha256=kpjER_a7NZT4rvAHxEj3hd6CgF_JHgBFl5WI9-HBzkY,703 +openai/types/shared_params/custom_tool_input_format.py,sha256=uv6tIPrdbzJ3_erNTbz7bDjVbMzAi8o22QG2wOhpRGQ,852 +openai/types/shared_params/function_definition.py,sha256=6JjuRmXIofTv76GCC4XFssqgZw-iKbBazjWqKerfq6Q,1510 +openai/types/shared_params/function_parameters.py,sha256=UvxKz_3b9b5ECwWr8RFrIH511htbU2JZsp9Z9BMkF-o,272 +openai/types/shared_params/metadata.py,sha256=YCb9eFyy17EuLwtVHjUBUjW2FU8SbWp4NV-aEr_it54,249 +openai/types/shared_params/oauth_error_code.py,sha256=e8ftf05RcSUYLGF6YgWJ-nypxfdvisyZ6jbu7mKZ0Io,318 +openai/types/shared_params/reasoning.py,sha256=wXoF46cFeHImN8acwAJ8DRzsPzuI_2zqteLW47OdZIY,2025 +openai/types/shared_params/reasoning_effort.py,sha256=CjSzyuVxoslnEBq_vQt2WWsVVgPe4jGjoHYu6chpGx0,332 +openai/types/shared_params/response_format_json_object.py,sha256=eEG54vILrwf5es7h1vja1zlyKOQiRy9zstuQicW2NLg,670 +openai/types/shared_params/response_format_json_schema.py,sha256=Rx2m7tbaMVWO0FQABF0B7jc8Cxo8_EmTq_tQwCX9XqU,1804 +openai/types/shared_params/response_format_text.py,sha256=zCKpz3Fl_w-EICrTTrarsBhxea_LvzaKG6J864zjF1c,441 +openai/types/shared_params/responses_model.py,sha256=r1tGQ9j25cW84o01POd2p74wb18DdSBe2OeBTJhVOc8,770 +openai/types/skill.py,sha256=xCnmIVIrzbmkdQZHuIxmIAS5wa2rzjmYuOQDAah0KHI,657 +openai/types/skill_create_params.py,sha256=tskcK2JrqgOHsOZ0uuNYn8KITbQoBzbq0UZGvgCbYTk,448 +openai/types/skill_list.py,sha256=10R_5DUqfjvhr3Ve_hDWUFyJbx7No4LZ_GR7JFHhur4,640 +openai/types/skill_list_params.py,sha256=JBkg2WnMVoXd86aEwF9YUwAWRGibg0Z1-YiQvd8N_pE,550 +openai/types/skill_update_params.py,sha256=cC1iOF7tBCM9dBm7rXlohfSfXO_8evxma1BY3vC_bsk,346 +openai/types/skills/__init__.py,sha256=9n6vxblrac4DrM-8_fK6R5BkyepfCtZJu1i3orvSWAw,476 +openai/types/skills/__pycache__/__init__.cpython-310.pyc,, +openai/types/skills/__pycache__/deleted_skill_version.cpython-310.pyc,, +openai/types/skills/__pycache__/skill_version.cpython-310.pyc,, +openai/types/skills/__pycache__/skill_version_list.cpython-310.pyc,, +openai/types/skills/__pycache__/version_create_params.cpython-310.pyc,, +openai/types/skills/__pycache__/version_list_params.cpython-310.pyc,, +openai/types/skills/deleted_skill_version.py,sha256=0BYiz1FTElv8DkpSD7H49K0ZWzASOJC4yNTg0P9sDys,366 +openai/types/skills/skill_version.py,sha256=aF549GDKzxlw7TnCUC1z8WbYXdl7Rv0vogAcHNDrCQU,712 +openai/types/skills/skill_version_list.py,sha256=_jevI1qhI6-ZEevLFkKsflI-02kTXJBq9WpeBfB_HeQ,677 +openai/types/skills/version_create_params.py,sha256=dqfTwBQn5ode8JnuwQ3lr7Uv5Ja26aCnoJsFu5-x0F4,526 +openai/types/skills/version_list_params.py,sha256=C_B2XBJuiXiZWCWNcykuTZTlkO4b1ghjjC5664g3qLY,462 +openai/types/skills/versions/__init__.py,sha256=OKfJYcKb4NObdiRObqJV_dOyDQ8feXekDUge2o_4pXQ,122 +openai/types/skills/versions/__pycache__/__init__.cpython-310.pyc,, +openai/types/static_file_chunking_strategy.py,sha256=JmAzT2-9eaG9ZTH8X0jS1IVCOE3Jgi1PzE11oMST3Fc,595 +openai/types/static_file_chunking_strategy_object.py,sha256=MTwQ1olGZHoC26xxCKw0U0RvWORIJLgWzNWRQ1V0KmA,424 +openai/types/static_file_chunking_strategy_object_param.py,sha256=tUsAYwR07qefkjFgt_qNwdUDbo2Rd-k9Xgu9OvtK9EE,597 +openai/types/static_file_chunking_strategy_param.py,sha256=kCMmgyOxO0XIF2wjCWjUXtyn9S6q_7mNmyUCauqrjsg,692 +openai/types/upload.py,sha256=_ePK_A-Hxr0bctSI3PfiAiJh22YRZwWXsBt0xdEQIk4,1281 +openai/types/upload_complete_params.py,sha256=PW5mCxJt7eg7F5sttX5LCE43m9FX8oZs3P5i9HvjRoU,527 +openai/types/upload_create_params.py,sha256=uOXPb_sdZhCqoR3gSSvpb4RpZ5K_Ppl1oAmJGbIAT3Y,1689 +openai/types/uploads/__init__.py,sha256=fDsmd3L0nIWbFldbViOLvcQavsFA4SL3jsXDfAueAck,242 +openai/types/uploads/__pycache__/__init__.cpython-310.pyc,, +openai/types/uploads/__pycache__/part_create_params.cpython-310.pyc,, +openai/types/uploads/__pycache__/upload_part.cpython-310.pyc,, +openai/types/uploads/part_create_params.py,sha256=pBByUzngaj70ov1knoSo_gpeBjaWP9D5EdiHwiG4G7U,362 +openai/types/uploads/upload_part.py,sha256=A_6PT8ptLJtR-jbU1b11jlpnVNLE10Kwoh1U985j9Y4,677 +openai/types/vector_store.py,sha256=rbjldzgYE-1TsFvAeBQYSOJqSiSWISrhYpmnkJTVsL0,2633 +openai/types/vector_store_create_params.py,sha256=nMpX4sfgUug_D67MDA1bNSNKgc4tP26_SNp2aca8iD4,1947 +openai/types/vector_store_deleted.py,sha256=BbtnlZ0Z5f4ncDyHLKrEfmY6Uuc0xOg3WBxvMoR8Wxk,307 +openai/types/vector_store_list_params.py,sha256=KeSeQaEdqO2EiPEVtq1Nun-uRRdkfwW0P8aHeCmL5zA,1226 +openai/types/vector_store_search_params.py,sha256=Uglni3jSE8d8-4c7eKRlxxEsxFNnhzuGBlUBnYPiJvA,1301 +openai/types/vector_store_search_response.py,sha256=qlhdAjqLPZg_JQmsqQCzAgT2Pxc2C-vGZmh64kR8y-M,1156 +openai/types/vector_store_update_params.py,sha256=-RQr2LnJzmpI8iFx-cGSZK8hg-24mYx9c497xtN_36k,1293 +openai/types/vector_stores/__init__.py,sha256=F_DyW6EqxOJTBPKE5LUSzgTibcZM6axMo-irysr52ro,818 +openai/types/vector_stores/__pycache__/__init__.cpython-310.pyc,, +openai/types/vector_stores/__pycache__/file_batch_create_params.cpython-310.pyc,, +openai/types/vector_stores/__pycache__/file_batch_list_files_params.cpython-310.pyc,, +openai/types/vector_stores/__pycache__/file_content_response.cpython-310.pyc,, +openai/types/vector_stores/__pycache__/file_create_params.cpython-310.pyc,, +openai/types/vector_stores/__pycache__/file_list_params.cpython-310.pyc,, +openai/types/vector_stores/__pycache__/file_update_params.cpython-310.pyc,, +openai/types/vector_stores/__pycache__/vector_store_file.cpython-310.pyc,, +openai/types/vector_stores/__pycache__/vector_store_file_batch.cpython-310.pyc,, +openai/types/vector_stores/__pycache__/vector_store_file_deleted.cpython-310.pyc,, +openai/types/vector_stores/file_batch_create_params.py,sha256=fDVyJN1skyJ6Sbjj53LJtRTpq_DaU0_nVuQE-QueoXA,3219 +openai/types/vector_stores/file_batch_list_files_params.py,sha256=FPpQvCQI2skyLB8YCuwdCj7RbO9ba1UjaHAtvrWxAbs,1451 +openai/types/vector_stores/file_content_response.py,sha256=uAFvFDE_NVRzg0xm1fLJ2zEd62qzq8rPYko7xpDjbaU,367 +openai/types/vector_stores/file_create_params.py,sha256=CVlhb4KjUZ2Dzq_bcjCssRaBeoK8SKfF6HA8YuVNm2c,1425 +openai/types/vector_stores/file_list_params.py,sha256=AIzmNH1oFuy-qlpRhj9eXu9yyTA-2z_IppLYFclMtZw,1385 +openai/types/vector_stores/file_update_params.py,sha256=NGah01luDW_W3psfsYa3ShlswH8pAhC_EebLMvd925I,781 +openai/types/vector_stores/vector_store_file.py,sha256=uHAXG0fdkbeJHS21gWmXourPYlc4GyyXkdam-EENwtU,2431 +openai/types/vector_stores/vector_store_file_batch.py,sha256=W1VoZE_PaiiOxRKG3empVJfr22oc7bE14dL9jheMG14,1512 +openai/types/vector_stores/vector_store_file_deleted.py,sha256=sOds3FSmDBFhe25zoSAz2vHsmG2bo4s2PASgB_M6UU0,321 +openai/types/video.py,sha256=Ggn_umAkyqVuwZdN0bWNuj5CfRRUOkt9fpUx_iSzqgI,1780 +openai/types/video_create_character_params.py,sha256=qGoGgMTLc3_PtUrnBz5Ze2VaG-6Gf5JwEowa8-WcGGI,459 +openai/types/video_create_character_response.py,sha256=qbqptjZ3jYkhZhJ4FZUg58P2ZEGenz9ZmE9JxYECAC8,490 +openai/types/video_create_error.py,sha256=DZpLbIAIOXOaZDNZk1dyVYMZHuxu81xB34krRLF6ddU,415 +openai/types/video_create_params.py,sha256=GxMfiZsty_DdNNI8jtO007Ei6rWQWQ9v-paC1dlKjZA,1240 +openai/types/video_delete_response.py,sha256=eiD7lHgtxXIl0sY-JzhrKzWfRFdiGne24LfPZ9tQIho,529 +openai/types/video_download_content_params.py,sha256=MXcSQOL67hzODH__CRf7g6i74hjXJG9I0zPIqqBjnlU,405 +openai/types/video_edit_params.py,sha256=vdYgJuW1vaVRDeUCzlYf_-1nzRF40R5mME8tiTziAas,784 +openai/types/video_extend_params.py,sha256=7FleFZMG05Yyzh5dWyGbi8ViFfESbfIrIejWGHVFfDs,988 +openai/types/video_get_character_response.py,sha256=SM_DKGQFfAtFm7GhvFZ5O8ymL1sxIrTlV3Zow6olvfU,484 +openai/types/video_list_params.py,sha256=pa8Nd6-hrc2fF8ZQRf4udebbMXpMDEKDrAAH9niSlgk,550 +openai/types/video_model.py,sha256=fkUBLAJ37g6TOBcXZGUgAMUhNNCDtSYCoEeMWiw0iJc,329 +openai/types/video_model_param.py,sha256=TeQQgBVyDxOuVo5qibiJIS9qJObnCtjbHGZEuam-SZc,375 +openai/types/video_remix_params.py,sha256=cFh9Tuaa1HH-cWyScfHPlw7N8nU-fg_AW0BL7S1yjR4,346 +openai/types/video_seconds.py,sha256=HyRb-NR4sVEGe2DoYZIQGig4kOrbbFfRYiqVejAgFbg,215 +openai/types/video_size.py,sha256=H1o0EhMbmicXdvaTC3wL-DnghhXzB7EkBChHL-gqdbI,243 +openai/types/webhooks/__init__.py,sha256=T8XC8KrJNXiNUPevxpO4PJi__C-HZgd0TMg7D2bRPh4,1828 +openai/types/webhooks/__pycache__/__init__.cpython-310.pyc,, +openai/types/webhooks/__pycache__/batch_cancelled_webhook_event.cpython-310.pyc,, +openai/types/webhooks/__pycache__/batch_completed_webhook_event.cpython-310.pyc,, +openai/types/webhooks/__pycache__/batch_expired_webhook_event.cpython-310.pyc,, +openai/types/webhooks/__pycache__/batch_failed_webhook_event.cpython-310.pyc,, +openai/types/webhooks/__pycache__/eval_run_canceled_webhook_event.cpython-310.pyc,, +openai/types/webhooks/__pycache__/eval_run_failed_webhook_event.cpython-310.pyc,, +openai/types/webhooks/__pycache__/eval_run_succeeded_webhook_event.cpython-310.pyc,, +openai/types/webhooks/__pycache__/fine_tuning_job_cancelled_webhook_event.cpython-310.pyc,, +openai/types/webhooks/__pycache__/fine_tuning_job_failed_webhook_event.cpython-310.pyc,, +openai/types/webhooks/__pycache__/fine_tuning_job_succeeded_webhook_event.cpython-310.pyc,, +openai/types/webhooks/__pycache__/realtime_call_incoming_webhook_event.cpython-310.pyc,, +openai/types/webhooks/__pycache__/response_cancelled_webhook_event.cpython-310.pyc,, +openai/types/webhooks/__pycache__/response_completed_webhook_event.cpython-310.pyc,, +openai/types/webhooks/__pycache__/response_failed_webhook_event.cpython-310.pyc,, +openai/types/webhooks/__pycache__/response_incomplete_webhook_event.cpython-310.pyc,, +openai/types/webhooks/__pycache__/unwrap_webhook_event.cpython-310.pyc,, +openai/types/webhooks/batch_cancelled_webhook_event.py,sha256=1iE0xOSTWzU8FJD5ruqgZazkOdCjmBZ_PB9_4Gmif7Y,862 +openai/types/webhooks/batch_completed_webhook_event.py,sha256=XCFcMnvn5xosPWdUwp3sO8wi4zYNefHWc_z6btzdGAE,862 +openai/types/webhooks/batch_expired_webhook_event.py,sha256=wNL76DW5xg9Jm8hqpPP-X5GHz3_wajmoNwc0jufgXtI,841 +openai/types/webhooks/batch_failed_webhook_event.py,sha256=_GpPkiVIL7N4bySS74Px97-niWeDM3hdzcDCViL6j1k,835 +openai/types/webhooks/eval_run_canceled_webhook_event.py,sha256=ZJkU4lAyr05OB-9t12njluzBmel81MbvhbSnOO2-L2M,840 +openai/types/webhooks/eval_run_failed_webhook_event.py,sha256=SbvytOgYKaIM33ud9pFLPjafUmRNAWF1juqAa-PLisI,819 +openai/types/webhooks/eval_run_succeeded_webhook_event.py,sha256=-ZZ3cfwXa4r2uyTrwPLvUxIQUZ4sjqTwdF6R2WE6fok,837 +openai/types/webhooks/fine_tuning_job_cancelled_webhook_event.py,sha256=IDUIOsMJqJTqE9AHOx2VNextcyWFkQcP2xTZ09bAAlk,892 +openai/types/webhooks/fine_tuning_job_failed_webhook_event.py,sha256=B2341NT-mry_Rv9kuQL-HQrRT6cyIidPR-vdlm3CCrE,865 +openai/types/webhooks/fine_tuning_job_succeeded_webhook_event.py,sha256=qxt7SsRh0bT0CSpEmRQhdoBpzCedzXZ06qaV2AiA3JI,883 +openai/types/webhooks/realtime_call_incoming_webhook_event.py,sha256=44kdeD1WbPjaqpf5S8EIfxtrSudjlpaaz74_9-rIzrw,1155 +openai/types/webhooks/response_cancelled_webhook_event.py,sha256=gmAVs2WIUoF1_HLbZ4whmTl6WPzEAsWzKFq6WiZsku8,870 +openai/types/webhooks/response_completed_webhook_event.py,sha256=mwNAM5x1-uqL39j_gCXPGSPLjzuPZoYwBZ-uo3ia5Dw,870 +openai/types/webhooks/response_failed_webhook_event.py,sha256=ka3VuDmBV7d9hxoFWktSZFXmtQrd4vrL4OinnMriyvQ,843 +openai/types/webhooks/response_incomplete_webhook_event.py,sha256=egeszUAnZW5j7-JBYXqNNUPNcDJc_Rl_shR2Lyz3iLM,878 +openai/types/webhooks/unwrap_webhook_event.py,sha256=KrfVL0-NsOuWHtRGiJfGMYwI8blUr09vUqUVJdZNpDQ,2039 +openai/types/websocket_connection_options.py,sha256=EA3rjUkBMdvNtsF31iW0gki0WDkEIWntW_cSqdHQTfQ,2041 +openai/types/websocket_reconnection.py,sha256=iCtg1V9UXeWotpvNnqlN_VPCyJ_ZJbxjsuCUNbZMUU8,1793 +openai/version.py,sha256=cjbXKO8Ut3aiv4YlQnugff7AdC48MpSndcx96q88Yb8,62 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/openai-2.36.0.dist-info/WHEEL b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/openai-2.36.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..21aaa72961a8af71c17d2cb3b76d5f7f567100e4 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/openai-2.36.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.26.3 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f1b3d6243d800c28469efad4bb452e40c76e6703 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/__init__.py @@ -0,0 +1,81 @@ +""" +.. codeauthor:: Tsuyoshi Hombashi +""" + +from .__version__ import __author__, __copyright__, __email__, __license__, __version__ +from ._base import AbstractSanitizer, AbstractValidator +from ._common import ( + ascii_symbols, + normalize_platform, + replace_ansi_escape, + replace_unprintable_char, + unprintable_ascii_chars, + validate_pathtype, + validate_unprintable_char, +) +from ._const import Platform +from ._filename import ( + FileNameSanitizer, + FileNameValidator, + is_valid_filename, + sanitize_filename, + validate_filename, +) +from ._filepath import ( + FilePathSanitizer, + FilePathValidator, + is_valid_filepath, + sanitize_filepath, + validate_filepath, +) +from ._ltsv import sanitize_ltsv_label, validate_ltsv_label +from ._symbol import replace_symbol, validate_symbol +from .error import ( + ErrorReason, + InvalidCharError, + InvalidReservedNameError, + NullNameError, + ReservedNameError, + ValidationError, + ValidReservedNameError, +) + + +__all__ = ( + "__author__", + "__copyright__", + "__email__", + "__license__", + "__version__", + "AbstractSanitizer", + "AbstractValidator", + "Platform", + "ascii_symbols", + "normalize_platform", + "replace_ansi_escape", + "replace_unprintable_char", + "unprintable_ascii_chars", + "validate_pathtype", + "validate_unprintable_char", + "FileNameSanitizer", + "FileNameValidator", + "is_valid_filename", + "sanitize_filename", + "validate_filename", + "FilePathSanitizer", + "FilePathValidator", + "is_valid_filepath", + "sanitize_filepath", + "validate_filepath", + "sanitize_ltsv_label", + "validate_ltsv_label", + "replace_symbol", + "validate_symbol", + "ErrorReason", + "InvalidCharError", + "InvalidReservedNameError", + "NullNameError", + "ReservedNameError", + "ValidationError", + "ValidReservedNameError", +) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/__version__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/__version__.py new file mode 100644 index 0000000000000000000000000000000000000000..f6e32a6ccba9ee9e711229bf8af8026a84d4651c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/__version__.py @@ -0,0 +1,9 @@ +from typing import Final + + +__author__: Final = "Tsuyoshi Hombashi" +__copyright__: Final = f"Copyright 2016-2025, {__author__}" +__license__: Final = "MIT License" +__version__ = "3.3.1" +__maintainer__: Final = __author__ +__email__: Final = "tsuyoshi.hombashi@gmail.com" diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/_base.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/_base.py new file mode 100644 index 0000000000000000000000000000000000000000..c74e842ee63ec9b744ffc9c9b6bc54906fc86a9f --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/_base.py @@ -0,0 +1,252 @@ +""" +.. codeauthor:: Tsuyoshi Hombashi +""" + +import abc +import os +import re +import sys +from collections.abc import Sequence +from typing import Final, Optional + +from ._common import normalize_platform, unprintable_ascii_chars +from ._const import DEFAULT_MIN_LEN, Platform +from ._types import PathType, PlatformType +from .error import ReservedNameError, ValidationError +from .handler import NullValueHandler, ReservedNameHandler, ValidationErrorHandler + + +class BaseFile: + _INVALID_PATH_CHARS: Final[str] = "".join(unprintable_ascii_chars) + _INVALID_FILENAME_CHARS: Final[str] = _INVALID_PATH_CHARS + "/" + _INVALID_WIN_PATH_CHARS: Final[str] = _INVALID_PATH_CHARS + ':*?"<>|\t\n\r\x0b\x0c' + _INVALID_WIN_FILENAME_CHARS: Final[str] = ( + _INVALID_FILENAME_CHARS + _INVALID_WIN_PATH_CHARS + "\\" + ) + + @property + def platform(self) -> Platform: + return self.__platform + + @property + def reserved_keywords(self) -> tuple[str, ...]: + return self._additional_reserved_names + + @property + def max_len(self) -> int: + return self._max_len + + def __init__( + self, + max_len: int, + fs_encoding: Optional[str], + additional_reserved_names: Optional[Sequence[str]] = None, + platform_max_len: Optional[int] = None, + platform: Optional[PlatformType] = None, + ) -> None: + if additional_reserved_names is None: + additional_reserved_names = tuple() + self._additional_reserved_names = tuple(n.upper() for n in additional_reserved_names) + + self.__platform = normalize_platform(platform) + + if platform_max_len is None: + platform_max_len = self._get_default_max_path_len() + + if max_len <= 0: + self._max_len = platform_max_len + else: + self._max_len = max_len + + self._max_len = min(self._max_len, platform_max_len) + + if fs_encoding: + self._fs_encoding = fs_encoding + else: + self._fs_encoding = sys.getfilesystemencoding() + + def _is_posix(self) -> bool: + return self.platform == Platform.POSIX + + def _is_universal(self) -> bool: + return self.platform == Platform.UNIVERSAL + + def _is_linux(self, include_universal: bool = False) -> bool: + if include_universal: + return self.platform in (Platform.UNIVERSAL, Platform.LINUX) + + return self.platform == Platform.LINUX + + def _is_windows(self, include_universal: bool = False) -> bool: + if include_universal: + return self.platform in (Platform.UNIVERSAL, Platform.WINDOWS) + + return self.platform == Platform.WINDOWS + + def _is_macos(self, include_universal: bool = False) -> bool: + if include_universal: + return self.platform in (Platform.UNIVERSAL, Platform.MACOS) + + return self.platform == Platform.MACOS + + def _get_default_max_path_len(self) -> int: + if self._is_linux(): + return 4096 + + if self._is_windows(): + return 260 + + if self._is_posix() or self._is_macos(): + return 1024 + + return 260 # universal + + +class AbstractValidator(BaseFile, metaclass=abc.ABCMeta): + def __init__( + self, + max_len: int, + fs_encoding: Optional[str], + check_reserved: bool, + additional_reserved_names: Optional[Sequence[str]] = None, + platform_max_len: Optional[int] = None, + platform: Optional[PlatformType] = None, + ) -> None: + self._check_reserved = check_reserved + + super().__init__( + max_len, + fs_encoding, + additional_reserved_names=additional_reserved_names, + platform_max_len=platform_max_len, + platform=platform, + ) + + @property + @abc.abstractmethod + def min_len(self) -> int: # pragma: no cover + pass + + @abc.abstractmethod + def validate(self, value: PathType) -> None: # pragma: no cover + pass + + def is_valid(self, value: PathType) -> bool: + try: + self.validate(value) + except (TypeError, ValidationError): + return False + + return True + + def _is_reserved_keyword(self, value: str) -> bool: + return value.upper() in self.reserved_keywords + + +class AbstractSanitizer(BaseFile, metaclass=abc.ABCMeta): + def __init__( + self, + validator: AbstractValidator, + max_len: int, + fs_encoding: Optional[str], + validate_after_sanitize: bool, + null_value_handler: Optional[ValidationErrorHandler] = None, + reserved_name_handler: Optional[ValidationErrorHandler] = None, + additional_reserved_names: Optional[Sequence[str]] = None, + platform_max_len: Optional[int] = None, + platform: Optional[PlatformType] = None, + ) -> None: + super().__init__( + max_len=max_len, + fs_encoding=fs_encoding, + additional_reserved_names=additional_reserved_names, + platform_max_len=platform_max_len, + platform=platform, + ) + + if null_value_handler is None: + null_value_handler = NullValueHandler.return_null_string + self._null_value_handler = null_value_handler + + if reserved_name_handler is None: + reserved_name_handler = ReservedNameHandler.add_trailing_underscore + self._reserved_name_handler = reserved_name_handler + + self._validate_after_sanitize = validate_after_sanitize + + self._validator = validator + + @abc.abstractmethod + def sanitize(self, value: PathType, replacement_text: str = "") -> PathType: # pragma: no cover + pass + + +class BaseValidator(AbstractValidator): + __RE_ROOT_NAME: Final = re.compile(r"([^\.]+)") + __RE_REPEAD_DOT: Final = re.compile(r"^\.{3,}") + + @property + def min_len(self) -> int: + return self._min_len + + def __init__( + self, + min_len: int, + max_len: int, + fs_encoding: Optional[str], + check_reserved: bool, + additional_reserved_names: Optional[Sequence[str]] = None, + platform_max_len: Optional[int] = None, + platform: Optional[PlatformType] = None, + ) -> None: + if min_len <= 0: + min_len = DEFAULT_MIN_LEN + self._min_len = max(min_len, 1) + + super().__init__( + max_len=max_len, + fs_encoding=fs_encoding, + check_reserved=check_reserved, + additional_reserved_names=additional_reserved_names, + platform_max_len=platform_max_len, + platform=platform, + ) + + self._validate_max_len() + + def _validate_reserved_keywords(self, name: str) -> None: + if not self._check_reserved: + return + + root_name = self.__extract_root_name(name) + base_name = os.path.basename(name) + + for name in (root_name, base_name): + if self._is_reserved_keyword(name): + raise ReservedNameError( + f"'{root_name}' is a reserved name", + reusable_name=False, + reserved_name=root_name, + platform=self.platform, + ) + + def _validate_max_len(self) -> None: + if self.max_len < 1: + raise ValueError("max_len must be greater or equal to one") + + if self.min_len > self.max_len: + raise ValueError("min_len must be lower than max_len") + + @classmethod + def __extract_root_name(cls, path: str) -> str: + if path in (".", ".."): + return path + + if cls.__RE_REPEAD_DOT.search(path): + return path + + match = cls.__RE_ROOT_NAME.match(os.path.basename(path)) + if match is None: + return "" + + return match.group(1) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/_common.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/_common.py new file mode 100644 index 0000000000000000000000000000000000000000..440c81ebbade0d1daa2f0bd72dd7dac0b10ea823 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/_common.py @@ -0,0 +1,163 @@ +""" +.. codeauthor:: Tsuyoshi Hombashi +""" + +import ntpath +import platform +import re +import string +import sys +from pathlib import PurePath +from typing import Any, Final, Optional + +from ._const import Platform +from ._types import PathType, PlatformType + + +_re_whitespaces: Final = re.compile(r"^[\s]+$") + + +def validate_pathtype( + text: PathType, allow_whitespaces: bool = False, error_msg: Optional[str] = None +) -> None: + from .error import ErrorReason, ValidationError + + if _is_not_null_string(text) or isinstance(text, PurePath): + return + + if allow_whitespaces and _re_whitespaces.search(str(text)): + return + + if is_null_string(text): + raise ValidationError(reason=ErrorReason.NULL_NAME) + + raise TypeError(f"text must be a string: actual={type(text)}") + + +def to_str(name: PathType) -> str: + if isinstance(name, PurePath): + return str(name) + + return name + + +def is_nt_abspath(value: str) -> bool: + ver_info = sys.version_info[:2] + if ver_info <= (3, 10): + if value.startswith("\\\\"): + return True + elif ver_info >= (3, 13): + return ntpath.isabs(value) + + drive, _tail = ntpath.splitdrive(value) + + return ntpath.isabs(value) and len(drive) > 0 + + +def is_null_string(value: Any) -> bool: + if value is None: + return True + + try: + return len(value.strip()) == 0 + except AttributeError: + return False + + +def _is_not_null_string(value: Any) -> bool: + try: + return len(value.strip()) > 0 + except AttributeError: + return False + + +def _get_unprintable_ascii_chars() -> list[str]: + return [chr(c) for c in range(128) if chr(c) not in string.printable] + + +unprintable_ascii_chars: Final = tuple(_get_unprintable_ascii_chars()) + + +def _get_ascii_symbols() -> list[str]: + symbol_list: list[str] = [] + + for i in range(128): + c = chr(i) + + if c in unprintable_ascii_chars or c in string.digits + string.ascii_letters: + continue + + symbol_list.append(c) + + return symbol_list + + +ascii_symbols: Final = tuple(_get_ascii_symbols()) + +__RE_UNPRINTABLE_CHARS: Final = re.compile( + "[{}]".format(re.escape("".join(unprintable_ascii_chars))), re.UNICODE +) +__RE_ANSI_ESCAPE: Final = re.compile( + r"(?:\x1B[@-Z\\-_]|[\x80-\x9A\x9C-\x9F]|(?:\x1B\[|\x9B)[0-?]*[ -/]*[@-~])" +) + + +def validate_unprintable_char(text: str) -> None: + from .error import InvalidCharError + + match_list = __RE_UNPRINTABLE_CHARS.findall(to_str(text)) + if match_list: + raise InvalidCharError(f"unprintable character found: {match_list}") + + +def replace_unprintable_char(text: str, replacement_text: str = "") -> str: + try: + return __RE_UNPRINTABLE_CHARS.sub(replacement_text, text) + except (TypeError, AttributeError): + raise TypeError("text must be a string") + + +def replace_ansi_escape(text: str, replacement_text: str = "") -> str: + try: + return __RE_ANSI_ESCAPE.sub(replacement_text, text) + except (TypeError, AttributeError): + raise TypeError("text must be a string") + + +def normalize_platform(name: Optional[PlatformType]) -> Platform: + if isinstance(name, Platform): + return name + + if not name: + return Platform.UNIVERSAL + + platform_str = name.strip().casefold() + + if platform_str == "posix": + return Platform.POSIX + + if platform_str == "auto": + platform_str = platform.system().casefold() + + if platform_str in ["linux"]: + return Platform.LINUX + + if platform_str and platform_str.startswith("win"): + return Platform.WINDOWS + + if platform_str in ["mac", "macos", "darwin"]: + return Platform.MACOS + + return Platform.UNIVERSAL + + +def findall_to_str(match: list[Any]) -> str: + uniq_list = {repr(text) for text in match} + return ", ".join(uniq_list) + + +def truncate_str(text: str, encoding: str, max_bytes: int) -> str: + str_bytes = text.encode(encoding) + str_bytes = str_bytes[:max_bytes] + # last char might be malformed, ignore it + return str_bytes.decode(encoding, "ignore") diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/_const.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/_const.py new file mode 100644 index 0000000000000000000000000000000000000000..4e8518ba9d9eead2401fcb1c8ecb3ab1d283bc8c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/_const.py @@ -0,0 +1,41 @@ +import enum +from typing import Final + + +DEFAULT_MIN_LEN: Final = 1 +INVALID_CHAR_ERR_MSG_TMPL: Final = "invalids=({invalid})" + + +_NTFS_RESERVED_FILE_NAMES: Final = ( + "$Mft", + "$MftMirr", + "$LogFile", + "$Volume", + "$AttrDef", + "$Bitmap", + "$Boot", + "$BadClus", + "$Secure", + "$Upcase", + "$Extend", + "$Quota", + "$ObjId", + "$Reparse", +) # Only in root directory + + +@enum.unique +class Platform(enum.Enum): + """ + Platform specifier enumeration. + """ + + #: POSIX compatible platform. + POSIX = "POSIX" + + #: platform independent. note that absolute paths cannot specify this. + UNIVERSAL = "universal" + + LINUX = "Linux" + WINDOWS = "Windows" + MACOS = "macOS" diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/_filename.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/_filename.py new file mode 100644 index 0000000000000000000000000000000000000000..f2651eddb8d97c2a2b78dee5103acca88d616d33 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/_filename.py @@ -0,0 +1,478 @@ +""" +.. codeauthor:: Tsuyoshi Hombashi +""" + +import itertools +import posixpath +import re +import warnings +from collections.abc import Sequence +from pathlib import Path, PurePath +from re import Pattern +from typing import Final, Optional + +from ._base import AbstractSanitizer, AbstractValidator, BaseFile, BaseValidator +from ._common import findall_to_str, is_nt_abspath, to_str, truncate_str, validate_pathtype +from ._const import DEFAULT_MIN_LEN, INVALID_CHAR_ERR_MSG_TMPL, Platform +from ._types import PathType, PlatformType +from .error import ErrorAttrKey, ErrorReason, InvalidCharError, ValidationError +from .handler import ReservedNameHandler, ValidationErrorHandler + + +_DEFAULT_MAX_FILENAME_LEN: Final = 255 +_RE_INVALID_FILENAME: Final = re.compile( + f"[{re.escape(BaseFile._INVALID_FILENAME_CHARS):s}]", re.UNICODE +) +_RE_INVALID_WIN_FILENAME: Final = re.compile( + f"[{re.escape(BaseFile._INVALID_WIN_FILENAME_CHARS):s}]", re.UNICODE +) + + +class FileNameSanitizer(AbstractSanitizer): + def __init__( + self, + max_len: int = _DEFAULT_MAX_FILENAME_LEN, + fs_encoding: Optional[str] = None, + platform: Optional[PlatformType] = None, + null_value_handler: Optional[ValidationErrorHandler] = None, + reserved_name_handler: Optional[ValidationErrorHandler] = None, + additional_reserved_names: Optional[Sequence[str]] = None, + validate_after_sanitize: bool = False, + validator: Optional[AbstractValidator] = None, + ) -> None: + if validator: + fname_validator = validator + else: + fname_validator = FileNameValidator( + min_len=DEFAULT_MIN_LEN, + max_len=max_len, + fs_encoding=fs_encoding, + check_reserved=True, + additional_reserved_names=additional_reserved_names, + platform=platform, + ) + + super().__init__( + max_len=max_len, + fs_encoding=fs_encoding, + null_value_handler=null_value_handler, + reserved_name_handler=reserved_name_handler, + additional_reserved_names=additional_reserved_names, + platform=platform, + validate_after_sanitize=validate_after_sanitize, + validator=fname_validator, + ) + + self._sanitize_regexp = self._get_sanitize_regexp() + + def sanitize(self, value: PathType, replacement_text: str = "") -> PathType: + try: + validate_pathtype(value, allow_whitespaces=not self._is_windows(include_universal=True)) + except ValidationError as e: + if e.reason == ErrorReason.NULL_NAME: + if isinstance(value, PurePath): + raise + + return self._null_value_handler(e) # type: ignore + raise + + sanitized_filename = self._sanitize_regexp.sub(replacement_text, str(value)) + sanitized_filename = truncate_str(sanitized_filename, self._fs_encoding, self.max_len) + + try: + self._validator.validate(sanitized_filename) + except ValidationError as e: + if e.reason == ErrorReason.RESERVED_NAME: + replacement_word = self._reserved_name_handler(e) + if e.reserved_name != replacement_word: + sanitized_filename = re.sub( + re.escape(e.reserved_name), replacement_word, sanitized_filename + ) + elif e.reason == ErrorReason.INVALID_CHARACTER and self._is_windows( + include_universal=True + ): + # Do not start a file or directory name with a space + sanitized_filename = sanitized_filename.lstrip(" ") + + # Do not end a file or directory name with a space or a period + sanitized_filename = sanitized_filename.rstrip(" ") + if sanitized_filename not in (".", ".."): + sanitized_filename = sanitized_filename.rstrip(" .") + elif e.reason == ErrorReason.NULL_NAME: + sanitized_filename = self._null_value_handler(e) + + if self._validate_after_sanitize: + try: + self._validator.validate(sanitized_filename) + except ValidationError as e: + raise ValidationError( + description=str(e), + reason=ErrorReason.INVALID_AFTER_SANITIZE, + platform=self.platform, + ) + + if isinstance(value, PurePath): + return Path(sanitized_filename) # type: ignore + + return sanitized_filename # type: ignore + + def _get_sanitize_regexp(self) -> Pattern[str]: + if self._is_windows(include_universal=True): + return _RE_INVALID_WIN_FILENAME + + return _RE_INVALID_FILENAME + + +class FileNameValidator(BaseValidator): + _WINDOWS_RESERVED_FILE_NAMES: Final = ( + ("CON", "PRN", "AUX", "CLOCK$", "NUL") + + tuple(f"{name:s}{num:d}" for name, num in itertools.product(("COM", "LPT"), range(0, 10))) + + tuple( + f"{name:s}{ssd:s}" + for name, ssd in itertools.product( + ("COM", "LPT"), + ("\N{SUPERSCRIPT ONE}", "\N{SUPERSCRIPT TWO}", "\N{SUPERSCRIPT THREE}"), + ) + ) + ) + _MACOS_RESERVED_FILE_NAMES: Final = (":",) + + @property + def reserved_keywords(self) -> tuple[str, ...]: + common_keywords = super().reserved_keywords + + if self._is_universal(): + word_set = set( + common_keywords + + self._WINDOWS_RESERVED_FILE_NAMES + + self._MACOS_RESERVED_FILE_NAMES + ) + elif self._is_windows(): + word_set = set(common_keywords + self._WINDOWS_RESERVED_FILE_NAMES) + elif self._is_posix() or self._is_macos(): + word_set = set(common_keywords + self._MACOS_RESERVED_FILE_NAMES) + else: + word_set = set(common_keywords) + + return tuple(sorted(word_set)) + + def __init__( + self, + min_len: int = DEFAULT_MIN_LEN, + max_len: int = _DEFAULT_MAX_FILENAME_LEN, + fs_encoding: Optional[str] = None, + platform: Optional[PlatformType] = None, + check_reserved: bool = True, + additional_reserved_names: Optional[Sequence[str]] = None, + ) -> None: + super().__init__( + min_len=min_len, + max_len=max_len, + fs_encoding=fs_encoding, + check_reserved=check_reserved, + additional_reserved_names=additional_reserved_names, + platform=platform, + ) + + def validate(self, value: PathType) -> None: + validate_pathtype(value, allow_whitespaces=not self._is_windows(include_universal=True)) + + unicode_filename = to_str(value) + byte_ct = len(unicode_filename.encode(self._fs_encoding)) + + self.validate_abspath(unicode_filename) + + err_kwargs = { + ErrorAttrKey.REASON: ErrorReason.INVALID_LENGTH, + ErrorAttrKey.PLATFORM: self.platform, + ErrorAttrKey.FS_ENCODING: self._fs_encoding, + ErrorAttrKey.BYTE_COUNT: byte_ct, + ErrorAttrKey.VALUE: unicode_filename, + } + if byte_ct > self.max_len: + raise ValidationError( + [ + f"filename is too long: expected<={self.max_len:d} bytes, actual={byte_ct:d} bytes" + ], + **err_kwargs, + ) + if byte_ct < self.min_len: + raise ValidationError( + [ + f"filename is too short: expected>={self.min_len:d} bytes, actual={byte_ct:d} bytes" + ], + **err_kwargs, + ) + + self._validate_reserved_keywords(unicode_filename) + self.__validate_universal_filename(unicode_filename) + + if self._is_windows(include_universal=True): + self.__validate_win_filename(unicode_filename) + + def validate_abspath(self, value: str) -> None: + err = ValidationError( + description=f"found an absolute path ({value!r}), expected a filename", + platform=self.platform, + reason=ErrorReason.FOUND_ABS_PATH, + ) + + if self._is_windows(include_universal=True): + if is_nt_abspath(value): + raise err + + if posixpath.isabs(value): + raise err + + def __validate_universal_filename(self, unicode_filename: str) -> None: + match = _RE_INVALID_FILENAME.findall(unicode_filename) + if match: + raise InvalidCharError( + INVALID_CHAR_ERR_MSG_TMPL.format( + invalid=findall_to_str(match), + ), + platform=Platform.UNIVERSAL, + value=unicode_filename, + ) + + def __validate_win_filename(self, unicode_filename: str) -> None: + match = _RE_INVALID_WIN_FILENAME.findall(unicode_filename) + if match: + raise InvalidCharError( + INVALID_CHAR_ERR_MSG_TMPL.format( + invalid=findall_to_str(match), + ), + platform=Platform.WINDOWS, + value=unicode_filename, + ) + + if unicode_filename in (".", ".."): + return + + KB2829981_err_tmpl = "{}. Refer: https://learn.microsoft.com/en-us/troubleshoot/windows-client/shell-experience/file-folder-name-whitespace-characters" # noqa: E501 + err_kwargs = { + ErrorAttrKey.PLATFORM: Platform.WINDOWS, + ErrorAttrKey.VALUE: unicode_filename, + } + + if unicode_filename[-1] in (" ", "."): + raise InvalidCharError( + INVALID_CHAR_ERR_MSG_TMPL.format(invalid=re.escape(unicode_filename[-1])), + description=KB2829981_err_tmpl.format( + "Do not end a file or directory name with a space or a period" + ), + **err_kwargs, + ) + + if unicode_filename[0] in (" "): + raise InvalidCharError( + INVALID_CHAR_ERR_MSG_TMPL.format(invalid=re.escape(unicode_filename[0])), + description=KB2829981_err_tmpl.format( + "Do not start a file or directory name with a space" + ), + **err_kwargs, + ) + + +def validate_filename( + filename: PathType, + platform: Optional[PlatformType] = None, + min_len: int = DEFAULT_MIN_LEN, + max_len: int = _DEFAULT_MAX_FILENAME_LEN, + fs_encoding: Optional[str] = None, + check_reserved: bool = True, + additional_reserved_names: Optional[Sequence[str]] = None, +) -> None: + """Verifying whether the ``filename`` is a valid file name or not. + + Args: + filename: + Filename to validate. + platform: + Target platform name of the filename. + + .. include:: platform.txt + min_len: + Minimum byte length of the ``filename``. The value must be greater or equal to one. + Defaults to ``1``. + max_len: + Maximum byte length of the ``filename``. The value must be lower than: + + - ``Linux``: 4096 + - ``macOS``: 1024 + - ``Windows``: 260 + - ``universal``: 260 + + Defaults to ``255``. + fs_encoding: + Filesystem encoding that is used to calculate the byte length of the filename. + If |None|, get the encoding from the execution environment. + check_reserved: + If |True|, check the reserved names of the ``platform``. + additional_reserved_names: + Additional reserved names to check. + Case insensitive. + + Raises: + ValidationError (ErrorReason.INVALID_LENGTH): + If the ``filename`` is longer than ``max_len`` characters. + ValidationError (ErrorReason.INVALID_CHARACTER): + If the ``filename`` includes invalid character(s) for a filename: + |invalid_filename_chars|. + The following characters are also invalid for Windows platforms: + |invalid_win_filename_chars|. + ValidationError (ErrorReason.RESERVED_NAME): + If the ``filename`` equals the reserved name by OS. + Windows reserved name is as follows: + ``"CON"``, ``"PRN"``, ``"AUX"``, ``"NUL"``, ``"COM[1-9]"``, ``"LPT[1-9]"``. + + Example: + :ref:`example-validate-filename` + + See Also: + `Naming Files, Paths, and Namespaces - Win32 apps | Microsoft Docs + `__ + """ + + FileNameValidator( + platform=platform, + min_len=min_len, + max_len=max_len, + fs_encoding=fs_encoding, + check_reserved=check_reserved, + additional_reserved_names=additional_reserved_names, + ).validate(filename) + + +def is_valid_filename( + filename: PathType, + platform: Optional[PlatformType] = None, + min_len: int = DEFAULT_MIN_LEN, + max_len: Optional[int] = None, + fs_encoding: Optional[str] = None, + check_reserved: bool = True, + additional_reserved_names: Optional[Sequence[str]] = None, +) -> bool: + """Check whether the ``filename`` is a valid name or not. + + Args: + filename: + A filename to be checked. + platform: + Target platform name of the filename. + + Example: + :ref:`example-is-valid-filename` + + See Also: + :py:func:`.validate_filename()` + """ + + return FileNameValidator( + platform=platform, + min_len=min_len, + max_len=-1 if max_len is None else max_len, + fs_encoding=fs_encoding, + check_reserved=check_reserved, + additional_reserved_names=additional_reserved_names, + ).is_valid(filename) + + +def sanitize_filename( + filename: PathType, + replacement_text: str = "", + platform: Optional[PlatformType] = None, + max_len: Optional[int] = _DEFAULT_MAX_FILENAME_LEN, + fs_encoding: Optional[str] = None, + check_reserved: Optional[bool] = None, + null_value_handler: Optional[ValidationErrorHandler] = None, + reserved_name_handler: Optional[ValidationErrorHandler] = None, + additional_reserved_names: Optional[Sequence[str]] = None, + validate_after_sanitize: bool = False, +) -> PathType: + """Make a valid filename from a string. + + To make a valid filename, the function does the following: + + - Replace invalid characters as file names included in the ``filename`` + with the ``replacement_text``. Invalid characters are: + + - unprintable characters + - |invalid_filename_chars| + - for Windows (or universal) only: |invalid_win_filename_chars| + + - Replace a value if a sanitized value is a reserved name by operating systems + with a specified handler by ``reserved_name_handler``. + + Args: + filename: Filename to sanitize. + replacement_text: + Replacement text for invalid characters. Defaults to ``""``. + platform: + Target platform name of the filename. + + .. include:: platform.txt + max_len: + Maximum byte length of the ``filename``. + Truncate the name length if the ``filename`` length exceeds this value. + Defaults to ``255``. + fs_encoding: + Filesystem encoding that is used to calculate the byte length of the filename. + If |None|, get the encoding from the execution environment. + check_reserved: + [Deprecated] Use 'reserved_name_handler' instead. + null_value_handler: + Function called when a value after sanitization is an empty string. + You can specify predefined handlers: + + - :py:func:`~.handler.NullValueHandler.return_null_string` + - :py:func:`~.handler.NullValueHandler.return_timestamp` + - :py:func:`~.handler.raise_error` + + Defaults to :py:func:`.handler.NullValueHandler.return_null_string` that just return ``""``. + reserved_name_handler: + Function called when a value after sanitization is a reserved name. + You can specify predefined handlers: + + - :py:meth:`~.handler.ReservedNameHandler.add_leading_underscore` + - :py:meth:`~.handler.ReservedNameHandler.add_trailing_underscore` + - :py:meth:`~.handler.ReservedNameHandler.as_is` + - :py:func:`~.handler.raise_error` + + Defaults to :py:func:`.handler.add_trailing_underscore`. + additional_reserved_names: + Additional reserved names to sanitize. + Case insensitive. + validate_after_sanitize: + Execute validation after sanitization to the file name. + + Returns: + Same type as the ``filename`` (str or PathLike object): + Sanitized filename. + + Raises: + ValueError: + If the ``filename`` is an invalid filename. + + Example: + :ref:`example-sanitize-filename` + """ + + if check_reserved is not None: + warnings.warn( + "'check_reserved' is deprecated. Use 'reserved_name_handler' instead.", + DeprecationWarning, + ) + + if check_reserved is False: + reserved_name_handler = ReservedNameHandler.as_is + + return FileNameSanitizer( + platform=platform, + max_len=-1 if max_len is None else max_len, + fs_encoding=fs_encoding, + null_value_handler=null_value_handler, + reserved_name_handler=reserved_name_handler, + additional_reserved_names=additional_reserved_names, + validate_after_sanitize=validate_after_sanitize, + ).sanitize(filename, replacement_text) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/_filepath.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/_filepath.py new file mode 100644 index 0000000000000000000000000000000000000000..df49ed437b13c2aff27ea72978bea4ccaee0c729 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/_filepath.py @@ -0,0 +1,516 @@ +""" +.. codeauthor:: Tsuyoshi Hombashi +""" + +import ntpath +import os.path +import posixpath +import re +import warnings +from collections.abc import Sequence +from pathlib import Path, PurePath +from re import Pattern +from typing import Final, Optional + +from ._base import AbstractSanitizer, AbstractValidator, BaseFile, BaseValidator +from ._common import findall_to_str, is_nt_abspath, to_str, validate_pathtype +from ._const import _NTFS_RESERVED_FILE_NAMES, DEFAULT_MIN_LEN, INVALID_CHAR_ERR_MSG_TMPL, Platform +from ._filename import FileNameSanitizer, FileNameValidator +from ._types import PathType, PlatformType +from .error import ErrorAttrKey, ErrorReason, InvalidCharError, ReservedNameError, ValidationError +from .handler import ReservedNameHandler, ValidationErrorHandler + + +_RE_INVALID_PATH: Final = re.compile(f"[{re.escape(BaseFile._INVALID_PATH_CHARS):s}]", re.UNICODE) +_RE_INVALID_WIN_PATH: Final = re.compile( + f"[{re.escape(BaseFile._INVALID_WIN_PATH_CHARS):s}]", re.UNICODE +) + + +class FilePathSanitizer(AbstractSanitizer): + def __init__( + self, + max_len: int = -1, + fs_encoding: Optional[str] = None, + platform: Optional[PlatformType] = None, + null_value_handler: Optional[ValidationErrorHandler] = None, + reserved_name_handler: Optional[ValidationErrorHandler] = None, + additional_reserved_names: Optional[Sequence[str]] = None, + normalize: bool = True, + validate_after_sanitize: bool = False, + validator: Optional[AbstractValidator] = None, + ) -> None: + if validator: + fpath_validator = validator + else: + fpath_validator = FilePathValidator( + min_len=DEFAULT_MIN_LEN, + max_len=max_len, + fs_encoding=fs_encoding, + check_reserved=True, + additional_reserved_names=additional_reserved_names, + platform=platform, + ) + super().__init__( + max_len=max_len, + fs_encoding=fs_encoding, + validator=fpath_validator, + null_value_handler=null_value_handler, + reserved_name_handler=reserved_name_handler, + additional_reserved_names=additional_reserved_names, + platform=platform, + validate_after_sanitize=validate_after_sanitize, + ) + + self._sanitize_regexp = self._get_sanitize_regexp() + self.__fname_sanitizer = FileNameSanitizer( + max_len=self.max_len, + fs_encoding=fs_encoding, + null_value_handler=null_value_handler, + reserved_name_handler=reserved_name_handler, + additional_reserved_names=additional_reserved_names, + platform=self.platform, + validate_after_sanitize=validate_after_sanitize, + ) + self.__normalize = normalize + + if self._is_windows(include_universal=True): + self.__split_drive = ntpath.splitdrive + else: + self.__split_drive = posixpath.splitdrive + + def sanitize(self, value: PathType, replacement_text: str = "") -> PathType: + try: + validate_pathtype(value, allow_whitespaces=not self._is_windows(include_universal=True)) + except ValidationError as e: + if e.reason == ErrorReason.NULL_NAME: + if isinstance(value, PurePath): + raise + + return self._null_value_handler(e) # type: ignore + raise + + unicode_filepath = to_str(value) + drive, unicode_filepath = self.__split_drive(unicode_filepath) + unicode_filepath = self._sanitize_regexp.sub(replacement_text, unicode_filepath) + if self.__normalize and unicode_filepath: + unicode_filepath = os.path.normpath(unicode_filepath) + sanitized_path = unicode_filepath + + sanitized_entries: list[str] = [] + if drive: + sanitized_entries.append(drive) + for entry in sanitized_path.replace("\\", "/").split("/"): + if entry in _NTFS_RESERVED_FILE_NAMES: + sanitized_entries.append(f"{entry}_") + continue + + sanitized_entry = str( + self.__fname_sanitizer.sanitize(entry, replacement_text=replacement_text) + ) + if not sanitized_entry: + if not sanitized_entries: + sanitized_entries.append("") + continue + + sanitized_entries.append(sanitized_entry) + + sanitized_path = self.__get_path_separator().join(sanitized_entries) + try: + self._validator.validate(sanitized_path) + except ValidationError as e: + if e.reason == ErrorReason.NULL_NAME: + sanitized_path = self._null_value_handler(e) + + if self._validate_after_sanitize: + self._validator.validate(sanitized_path) + + if isinstance(value, PurePath): + return Path(sanitized_path) # type: ignore + + return sanitized_path # type: ignore + + def _get_sanitize_regexp(self) -> Pattern[str]: + if self._is_windows(include_universal=True): + return _RE_INVALID_WIN_PATH + + return _RE_INVALID_PATH + + def __get_path_separator(self) -> str: + if self._is_windows(): + return "\\" + + return "/" + + +class FilePathValidator(BaseValidator): + _RE_NTFS_RESERVED: Final = re.compile( + "|".join(f"^/{re.escape(pattern)}$" for pattern in _NTFS_RESERVED_FILE_NAMES), + re.IGNORECASE, + ) + _MACOS_RESERVED_FILE_PATHS: Final = ("/", ":") + + @property + def reserved_keywords(self) -> tuple[str, ...]: + common_keywords = super().reserved_keywords + + if any([self._is_universal(), self._is_posix(), self._is_macos()]): + return common_keywords + self._MACOS_RESERVED_FILE_PATHS + + if self._is_linux(): + return common_keywords + ("/",) + + return common_keywords + + def __init__( + self, + min_len: int = DEFAULT_MIN_LEN, + max_len: int = -1, + fs_encoding: Optional[str] = None, + platform: Optional[PlatformType] = None, + check_reserved: bool = True, + additional_reserved_names: Optional[Sequence[str]] = None, + ) -> None: + super().__init__( + min_len=min_len, + max_len=max_len, + fs_encoding=fs_encoding, + check_reserved=check_reserved, + additional_reserved_names=additional_reserved_names, + platform=platform, + ) + + self.__fname_validator = FileNameValidator( + min_len=min_len, + max_len=self.max_len, + fs_encoding=fs_encoding, + check_reserved=check_reserved, + additional_reserved_names=additional_reserved_names, + platform=platform, + ) + + if self._is_windows(include_universal=True): + self.__split_drive = ntpath.splitdrive + else: + self.__split_drive = posixpath.splitdrive + + def validate(self, value: PathType) -> None: + validate_pathtype(value, allow_whitespaces=not self._is_windows(include_universal=True)) + self.validate_abspath(value) + + _drive, tail = self.__split_drive(value) + if not tail: + return + + unicode_filepath = to_str(tail) + byte_ct = len(unicode_filepath.encode(self._fs_encoding)) + err_kwargs = { + ErrorAttrKey.REASON: ErrorReason.INVALID_LENGTH, + ErrorAttrKey.PLATFORM: self.platform, + ErrorAttrKey.FS_ENCODING: self._fs_encoding, + ErrorAttrKey.BYTE_COUNT: byte_ct, + ErrorAttrKey.VALUE: unicode_filepath, + } + + if byte_ct > self.max_len: + raise ValidationError( + [ + f"file path is too long: expected<={self.max_len:d} bytes, actual={byte_ct:d} bytes" + ], + **err_kwargs, + ) + if byte_ct < self.min_len: + raise ValidationError( + [ + "file path is too short: expected>={:d} bytes, actual={:d} bytes".format( + self.min_len, byte_ct + ) + ], + **err_kwargs, + ) + + self._validate_reserved_keywords(unicode_filepath) + unicode_filepath = unicode_filepath.replace("\\", "/") + for entry in unicode_filepath.split("/"): + if not entry or entry in (".", ".."): + continue + + self.__fname_validator.validate(entry) + + if self._is_windows(include_universal=True): + self.__validate_win_filepath(unicode_filepath) + else: + self.__validate_unix_filepath(unicode_filepath) + + def validate_abspath(self, value: PathType) -> None: + is_posix_abs = posixpath.isabs(value) + is_nt_abs = is_nt_abspath(to_str(value)) + + if any([self._is_windows() and is_nt_abs, self._is_posix() and is_posix_abs]): + return + + if self._is_universal() and any([is_nt_abs, is_posix_abs]): + ValidationError( + "platform-independent absolute file path is not supported", + platform=self.platform, + reason=ErrorReason.MALFORMED_ABS_PATH, + ) + + err_object = ValidationError( + description=( + f"an invalid absolute file path ({value!r}) for the platform ({self.platform.value})." + + " to avoid the error, specify an appropriate platform corresponding to" + + " the path format or 'auto'." + ), + platform=self.platform, + reason=ErrorReason.MALFORMED_ABS_PATH, + ) + + if self._is_windows(include_universal=True) and is_posix_abs: + raise err_object + + if not self._is_windows(): + drive, _tail = ntpath.splitdrive(value) + if drive and is_nt_abs: + raise err_object + + def __validate_unix_filepath(self, unicode_filepath: str) -> None: + match = _RE_INVALID_PATH.findall(unicode_filepath) + if match: + raise InvalidCharError( + INVALID_CHAR_ERR_MSG_TMPL.format(invalid=findall_to_str(match)), + value=unicode_filepath, + ) + + def __validate_win_filepath(self, unicode_filepath: str) -> None: + match = _RE_INVALID_WIN_PATH.findall(unicode_filepath) + if match: + raise InvalidCharError( + INVALID_CHAR_ERR_MSG_TMPL.format(invalid=findall_to_str(match)), + platform=Platform.WINDOWS, + value=unicode_filepath, + ) + + _drive, value = self.__split_drive(unicode_filepath) + if value: + match_reserved = self._RE_NTFS_RESERVED.search(value) + if match_reserved: + reserved_name = match_reserved.group() + raise ReservedNameError( + f"'{reserved_name}' is a reserved name", + reusable_name=False, + reserved_name=reserved_name, + platform=self.platform, + ) + + +def validate_filepath( + file_path: PathType, + platform: Optional[PlatformType] = None, + min_len: int = DEFAULT_MIN_LEN, + max_len: Optional[int] = None, + fs_encoding: Optional[str] = None, + check_reserved: bool = True, + additional_reserved_names: Optional[Sequence[str]] = None, +) -> None: + """Verifying whether the ``file_path`` is a valid file path or not. + + Args: + file_path (PathType): + File path to be validated. + platform (Optional[PlatformType], optional): + Target platform name of the file path. + + .. include:: platform.txt + min_len (int, optional): + Minimum byte length of the ``file_path``. The value must be greater or equal to one. + Defaults to ``1``. + max_len (Optional[int], optional): + Maximum byte length of the ``file_path``. If the value is |None| or minus, + automatically determined by the ``platform``: + + - ``Linux``: 4096 + - ``macOS``: 1024 + - ``Windows``: 260 + - ``universal``: 260 + fs_encoding (Optional[str], optional): + Filesystem encoding that is used to calculate the byte length of the file path. + If |None|, get the encoding from the execution environment. + check_reserved (bool, optional): + If |True|, check the reserved names of the ``platform``. + Defaults to |True|. + additional_reserved_names (Optional[Sequence[str]], optional): + Additional reserved names to check. + + Raises: + ValidationError (ErrorReason.INVALID_CHARACTER): + If the ``file_path`` includes invalid char(s): + |invalid_file_path_chars|. + The following characters are also invalid for Windows platforms: + |invalid_win_file_path_chars| + ValidationError (ErrorReason.INVALID_LENGTH): + If the ``file_path`` is longer than ``max_len`` characters. + ValidationError: + If ``file_path`` includes invalid values. + + Example: + :ref:`example-validate-file-path` + + See Also: + `Naming Files, Paths, and Namespaces - Win32 apps | Microsoft Docs + `__ + """ + + FilePathValidator( + platform=platform, + min_len=min_len, + max_len=-1 if max_len is None else max_len, + fs_encoding=fs_encoding, + check_reserved=check_reserved, + additional_reserved_names=additional_reserved_names, + ).validate(file_path) + + +def is_valid_filepath( + file_path: PathType, + platform: Optional[PlatformType] = None, + min_len: int = DEFAULT_MIN_LEN, + max_len: Optional[int] = None, + fs_encoding: Optional[str] = None, + check_reserved: bool = True, + additional_reserved_names: Optional[Sequence[str]] = None, +) -> bool: + """Check whether the ``file_path`` is a valid name or not. + + Args: + file_path: + A filepath to be checked. + platform: + Target platform name of the file path. + + Example: + :ref:`example-is-valid-filepath` + + See Also: + :py:func:`.validate_filepath()` + """ + + return FilePathValidator( + platform=platform, + min_len=min_len, + max_len=-1 if max_len is None else max_len, + fs_encoding=fs_encoding, + check_reserved=check_reserved, + additional_reserved_names=additional_reserved_names, + ).is_valid(file_path) + + +def sanitize_filepath( + file_path: PathType, + replacement_text: str = "", + platform: Optional[PlatformType] = None, + max_len: Optional[int] = None, + fs_encoding: Optional[str] = None, + check_reserved: Optional[bool] = None, + null_value_handler: Optional[ValidationErrorHandler] = None, + reserved_name_handler: Optional[ValidationErrorHandler] = None, + additional_reserved_names: Optional[Sequence[str]] = None, + normalize: bool = True, + validate_after_sanitize: bool = False, +) -> PathType: + """Make a valid file path from a string. + + To make a valid file path, the function does the following: + + - Replace invalid characters for a file path within the ``file_path`` + with the ``replacement_text``. Invalid characters are as follows: + + - unprintable characters + - |invalid_file_path_chars| + - for Windows (or universal) only: |invalid_win_file_path_chars| + + - Replace a value if a sanitized value is a reserved name by operating systems + with a specified handler by ``reserved_name_handler``. + + Args: + file_path: + File path to sanitize. + replacement_text: + Replacement text for invalid characters. + Defaults to ``""``. + platform: + Target platform name of the file path. + + .. include:: platform.txt + max_len: + Maximum byte length of the file path. + Truncate the path if the value length exceeds the `max_len`. + If the value is |None| or minus, ``max_len`` will automatically determined by the ``platform``: + + - ``Linux``: 4096 + - ``macOS``: 1024 + - ``Windows``: 260 + - ``universal``: 260 + fs_encoding: + Filesystem encoding that is used to calculate the byte length of the file path. + If |None|, get the encoding from the execution environment. + check_reserved: + [Deprecated] Use 'reserved_name_handler' instead. + null_value_handler: + Function called when a value after sanitization is an empty string. + You can specify predefined handlers: + + - :py:func:`.handler.NullValueHandler.return_null_string` + - :py:func:`.handler.NullValueHandler.return_timestamp` + - :py:func:`.handler.raise_error` + + Defaults to :py:func:`.handler.NullValueHandler.return_null_string` that just return ``""``. + reserved_name_handler: + Function called when a value after sanitization is one of the reserved names. + You can specify predefined handlers: + + - :py:meth:`~.handler.ReservedNameHandler.add_leading_underscore` + - :py:meth:`~.handler.ReservedNameHandler.add_trailing_underscore` + - :py:meth:`~.handler.ReservedNameHandler.as_is` + - :py:func:`~.handler.raise_error` + + Defaults to :py:func:`.handler.add_trailing_underscore`. + additional_reserved_names: + Additional reserved names to sanitize. + Case insensitive. + normalize: + If |True|, normalize the the file path. + validate_after_sanitize: + Execute validation after sanitization to the file path. + + Returns: + Same type as the argument (str or PathLike object): + Sanitized filepath. + + Raises: + ValueError: + If the ``file_path`` is an invalid file path. + + Example: + :ref:`example-sanitize-file-path` + """ + + if check_reserved is not None: + warnings.warn( + "'check_reserved' is deprecated. Use 'reserved_name_handler' instead.", + DeprecationWarning, + ) + + if check_reserved is False: + reserved_name_handler = ReservedNameHandler.as_is + + return FilePathSanitizer( + platform=platform, + max_len=-1 if max_len is None else max_len, + fs_encoding=fs_encoding, + normalize=normalize, + null_value_handler=null_value_handler, + reserved_name_handler=reserved_name_handler, + additional_reserved_names=additional_reserved_names, + validate_after_sanitize=validate_after_sanitize, + ).sanitize(file_path, replacement_text) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/_ltsv.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/_ltsv.py new file mode 100644 index 0000000000000000000000000000000000000000..134224a52a3ed8e9a8422c230f58e095a0104bd1 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/_ltsv.py @@ -0,0 +1,44 @@ +""" +.. codeauthor:: Tsuyoshi Hombashi +""" + +import re +from typing import Final + +from ._common import to_str, validate_pathtype +from .error import InvalidCharError + + +__RE_INVALID_LTSV_LABEL: Final = re.compile("[^0-9A-Za-z_.-]", re.UNICODE) + + +def validate_ltsv_label(label: str) -> None: + """ + Verifying whether ``label`` is a valid + `Labeled Tab-separated Values (LTSV) `__ label or not. + + :param label: Label to validate. + :raises pathvalidate.ValidationError: + If invalid character(s) found in the ``label`` for a LTSV format label. + """ + + validate_pathtype(label, allow_whitespaces=False) + + match_list = __RE_INVALID_LTSV_LABEL.findall(to_str(label)) + if match_list: + raise InvalidCharError(f"invalid character found for a LTSV format label: {match_list}") + + +def sanitize_ltsv_label(label: str, replacement_text: str = "") -> str: + """ + Replace all of the symbols in text. + + :param label: Input text. + :param replacement_text: Replacement text. + :return: A replacement string. + :rtype: str + """ + + validate_pathtype(label, allow_whitespaces=False) + + return __RE_INVALID_LTSV_LABEL.sub(replacement_text, to_str(label)) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/_symbol.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/_symbol.py new file mode 100644 index 0000000000000000000000000000000000000000..29cf608552ac4234143d5fa35992719a2ceded39 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/_symbol.py @@ -0,0 +1,93 @@ +""" +.. codeauthor:: Tsuyoshi Hombashi +""" + +import re +from collections.abc import Sequence +from typing import Final + +from ._common import ascii_symbols, to_str, unprintable_ascii_chars +from .error import InvalidCharError + + +__RE_SYMBOL: Final = re.compile( + "[{}]".format(re.escape("".join(ascii_symbols + unprintable_ascii_chars))), re.UNICODE +) + + +def validate_symbol(text: str) -> None: + """ + Verifying whether symbol(s) included in the ``text`` or not. + + Args: + text: + Input text to validate. + + Raises: + ValidationError (ErrorReason.INVALID_CHARACTER): + If symbol(s) included in the ``text``. + """ + + match_list = __RE_SYMBOL.findall(to_str(text)) + if match_list: + raise InvalidCharError(f"invalid symbols found: {match_list}") + + +def replace_symbol( + text: str, + replacement_text: str = "", + exclude_symbols: Sequence[str] = [], + is_replace_consecutive_chars: bool = False, + is_strip: bool = False, +) -> str: + """ + Replace all of the symbols in the ``text``. + + Args: + text: + Input text. + replacement_text: + Replacement text. + exclude_symbols: + Symbols that were excluded from the replacement. + is_replace_consecutive_chars: + If |True|, replace consecutive multiple ``replacement_text`` characters + to a single character. + is_strip: + If |True|, strip ``replacement_text`` from the beginning/end of the replacement text. + + Returns: + A replacement string. + + Example: + + :ref:`example-sanitize-symbol` + """ + + if exclude_symbols: + regexp = re.compile( + "[{}]".format( + re.escape( + "".join(set(ascii_symbols + unprintable_ascii_chars) - set(exclude_symbols)) + ) + ), + re.UNICODE, + ) + else: + regexp = __RE_SYMBOL + + try: + new_text = regexp.sub(replacement_text, to_str(text)) + except TypeError: + raise TypeError("text must be a string") + + if not replacement_text: + return new_text + + if is_replace_consecutive_chars: + new_text = re.sub(f"{re.escape(replacement_text)}+", replacement_text, new_text) + + if is_strip: + new_text = new_text.strip(replacement_text) + + return new_text diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/_types.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/_types.py new file mode 100644 index 0000000000000000000000000000000000000000..c946842489cb1998c4e9a2dbcb95ec9286e0a528 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/_types.py @@ -0,0 +1,8 @@ +from pathlib import Path +from typing import TypeVar + +from ._const import Platform + + +PathType = TypeVar("PathType", str, Path) +PlatformType = TypeVar("PlatformType", str, Platform) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/argparse.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/argparse.py new file mode 100644 index 0000000000000000000000000000000000000000..baeafe2751f007276ed14fa273f4fe206673d744 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/argparse.py @@ -0,0 +1,47 @@ +""" +.. codeauthor:: Tsuyoshi Hombashi +""" + +from argparse import ArgumentTypeError + +from ._filename import sanitize_filename, validate_filename +from ._filepath import sanitize_filepath, validate_filepath +from .error import ValidationError + + +def validate_filename_arg(value: str) -> str: + if not value: + return "" + + try: + validate_filename(value) + except ValidationError as e: + raise ArgumentTypeError(e) + + return value + + +def validate_filepath_arg(value: str) -> str: + if not value: + return "" + + try: + validate_filepath(value, platform="auto") + except ValidationError as e: + raise ArgumentTypeError(e) + + return value + + +def sanitize_filename_arg(value: str) -> str: + if not value: + return "" + + return sanitize_filename(value) + + +def sanitize_filepath_arg(value: str) -> str: + if not value: + return "" + + return sanitize_filepath(value, platform="auto") diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/click.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/click.py new file mode 100644 index 0000000000000000000000000000000000000000..9de84ebe2280a1f13f5eed5c929c5b2a182dfa61 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/click.py @@ -0,0 +1,50 @@ +""" +.. codeauthor:: Tsuyoshi Hombashi +""" + +from typing import Union + +import click +from click import Context, Option, Parameter + +from ._filename import sanitize_filename, validate_filename +from ._filepath import sanitize_filepath, validate_filepath +from .error import ValidationError + + +def validate_filename_arg(ctx: Context, param: Union[Option, Parameter], value: str) -> str: + if not value: + return "" + + try: + validate_filename(value) + except ValidationError as e: + raise click.BadParameter(str(e)) + + return value + + +def validate_filepath_arg(ctx: Context, param: Union[Option, Parameter], value: str) -> str: + if not value: + return "" + + try: + validate_filepath(value) + except ValidationError as e: + raise click.BadParameter(str(e)) + + return value + + +def sanitize_filename_arg(ctx: Context, param: Union[Option, Parameter], value: str) -> str: + if not value: + return "" + + return sanitize_filename(value) + + +def sanitize_filepath_arg(ctx: Context, param: Union[Option, Parameter], value: str) -> str: + if not value: + return "" + + return sanitize_filepath(value) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/error.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/error.py new file mode 100644 index 0000000000000000000000000000000000000000..3331a72900c29d167a71c916c9269cb59affc15b --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/error.py @@ -0,0 +1,259 @@ +""" +.. codeauthor:: Tsuyoshi Hombashi +""" + +import enum +from typing import Final, Optional + +from ._const import Platform + + +def _to_error_code(code: int) -> str: + return f"PV{code:04d}" + + +class ErrorAttrKey: + BYTE_COUNT: Final = "byte_count" + DESCRIPTION: Final = "description" + FS_ENCODING: Final = "fs_encoding" + PLATFORM: Final = "platform" + REASON: Final = "reason" + RESERVED_NAME: Final = "reserved_name" + REUSABLE_NAME: Final = "reusable_name" + VALUE: Final = "value" + + +@enum.unique +class ErrorReason(enum.Enum): + """ + Validation error reasons. + """ + + NULL_NAME = (_to_error_code(1001), "NULL_NAME", "the value must not be an empty string") + RESERVED_NAME = ( + _to_error_code(1002), + "RESERVED_NAME", + "found a reserved name by a platform", + ) + INVALID_CHARACTER = ( + _to_error_code(1100), + "INVALID_CHARACTER", + "invalid characters found", + ) + INVALID_LENGTH = ( + _to_error_code(1101), + "INVALID_LENGTH", + "found an invalid string length", + ) + FOUND_ABS_PATH = ( + _to_error_code(1200), + "FOUND_ABS_PATH", + "found an absolute path where must be a relative path", + ) + MALFORMED_ABS_PATH = ( + _to_error_code(1201), + "MALFORMED_ABS_PATH", + "found a malformed absolute path", + ) + INVALID_AFTER_SANITIZE = ( + _to_error_code(2000), + "INVALID_AFTER_SANITIZE", + "found invalid value after sanitizing", + ) + + @property + def code(self) -> str: + """str: Error code.""" + return self.__code + + @property + def name(self) -> str: + """str: Error reason name.""" + return self.__name + + @property + def description(self) -> str: + """str: Error reason description.""" + return self.__description + + def __init__(self, code: str, name: str, description: str) -> None: + self.__name = name + self.__code = code + self.__description = description + + def __str__(self) -> str: + return f"[{self.__code}] {self.__description}" + + +class ValidationError(ValueError): + """ + Exception class of validation errors. + """ + + @property + def platform(self) -> Optional[Platform]: + """ + :py:class:`~pathvalidate.Platform`: Platform information. + """ + return self.__platform + + @property + def reason(self) -> ErrorReason: + """ + :py:class:`~pathvalidate.error.ErrorReason`: The cause of the error. + """ + return self.__reason + + @property + def description(self) -> Optional[str]: + """Optional[str]: Error description.""" + return self.__description + + @property + def reserved_name(self) -> str: + """str: Reserved name.""" + return self.__reserved_name + + @property + def reusable_name(self) -> Optional[bool]: + """Optional[bool]: Whether the name is reusable or not.""" + return self.__reusable_name + + @property + def fs_encoding(self) -> Optional[str]: + """Optional[str]: File system encoding.""" + return self.__fs_encoding + + @property + def byte_count(self) -> Optional[int]: + """Optional[int]: Byte count of the path.""" + return self.__byte_count + + def __init__(self, *args, **kwargs) -> None: # type: ignore + if ErrorAttrKey.REASON not in kwargs: + raise ValueError(f"{ErrorAttrKey.REASON} must be specified") + + self.__reason: ErrorReason = kwargs.pop(ErrorAttrKey.REASON) + self.__byte_count: Optional[int] = kwargs.pop(ErrorAttrKey.BYTE_COUNT, None) + self.__platform: Optional[Platform] = kwargs.pop(ErrorAttrKey.PLATFORM, None) + self.__description: Optional[str] = kwargs.pop(ErrorAttrKey.DESCRIPTION, None) + self.__reserved_name: str = kwargs.pop(ErrorAttrKey.RESERVED_NAME, "") + self.__reusable_name: Optional[bool] = kwargs.pop(ErrorAttrKey.REUSABLE_NAME, None) + self.__fs_encoding: Optional[str] = kwargs.pop(ErrorAttrKey.FS_ENCODING, None) + self.__value: Optional[str] = kwargs.pop(ErrorAttrKey.VALUE, None) + + try: + super().__init__(*args[0], **kwargs) + except IndexError: + super().__init__(*args, **kwargs) + + def as_slog(self) -> dict[str, str]: + """Return a dictionary representation of the error. + + Returns: + Dict[str, str]: A dictionary representation of the error. + """ + + slog: dict[str, str] = { + "code": self.reason.code, + ErrorAttrKey.DESCRIPTION: self.reason.description, + } + if self.platform: + slog[ErrorAttrKey.PLATFORM] = self.platform.value + if self.description: + slog[ErrorAttrKey.DESCRIPTION] = self.description + if self.__reusable_name is not None: + slog[ErrorAttrKey.REUSABLE_NAME] = str(self.__reusable_name) + if self.__fs_encoding: + slog[ErrorAttrKey.FS_ENCODING] = self.__fs_encoding + if self.__byte_count: + slog[ErrorAttrKey.BYTE_COUNT] = str(self.__byte_count) + if self.__value: + slog[ErrorAttrKey.VALUE] = self.__value + + return slog + + def __str__(self) -> str: + item_list = [] + header = str(self.reason) + + if Exception.__str__(self): + item_list.append(Exception.__str__(self)) + + if self.platform: + item_list.append(f"{ErrorAttrKey.PLATFORM}={self.platform.value}") + if self.description: + item_list.append(f"{ErrorAttrKey.DESCRIPTION}={self.description}") + if self.__reusable_name is not None: + item_list.append(f"{ErrorAttrKey.REUSABLE_NAME}={self.reusable_name}") + if self.__fs_encoding: + item_list.append(f"{ErrorAttrKey.FS_ENCODING}={self.__fs_encoding}") + if self.__byte_count is not None: + item_list.append(f"{ErrorAttrKey.BYTE_COUNT}={self.__byte_count:,d}") + if self.__value: + item_list.append(f"{ErrorAttrKey.VALUE}={self.__value!r}") + + if item_list: + header += ": " + + return header + ", ".join(item_list).strip() + + def __repr__(self) -> str: + return self.__str__() + + +class NullNameError(ValidationError): + """[Deprecated] + Exception raised when a name is empty. + """ + + def __init__(self, *args, **kwargs) -> None: # type: ignore + kwargs[ErrorAttrKey.REASON] = ErrorReason.NULL_NAME + + super().__init__(args, **kwargs) + + +class InvalidCharError(ValidationError): + """ + Exception raised when includes invalid character(s) within a string. + """ + + def __init__(self, *args, **kwargs) -> None: # type: ignore[no-untyped-def] + kwargs[ErrorAttrKey.REASON] = ErrorReason.INVALID_CHARACTER + + super().__init__(args, **kwargs) + + +class ReservedNameError(ValidationError): + """ + Exception raised when a string matched a reserved name. + """ + + def __init__(self, *args, **kwargs) -> None: # type: ignore[no-untyped-def] + kwargs[ErrorAttrKey.REASON] = ErrorReason.RESERVED_NAME + + super().__init__(args, **kwargs) + + +class ValidReservedNameError(ReservedNameError): + """[Deprecated] + Exception raised when a string matched a reserved name. + However, it can be used as a name. + """ + + def __init__(self, *args, **kwargs) -> None: # type: ignore[no-untyped-def] + kwargs[ErrorAttrKey.REUSABLE_NAME] = True + + super().__init__(args, **kwargs) + + +class InvalidReservedNameError(ReservedNameError): + """[Deprecated] + Exception raised when a string matched a reserved name. + Moreover, the reserved name is invalid as a name. + """ + + def __init__(self, *args, **kwargs) -> None: # type: ignore[no-untyped-def] + kwargs[ErrorAttrKey.REUSABLE_NAME] = False + + super().__init__(args, **kwargs) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/handler.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/handler.py new file mode 100644 index 0000000000000000000000000000000000000000..0e44bbfd2cea5f1424fe47f67f7f456b216ad4db --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/handler.py @@ -0,0 +1,138 @@ +""" +.. codeauthor:: Tsuyoshi Hombashi +""" + +import warnings +from datetime import datetime +from typing import Callable + +from .error import ValidationError + + +ValidationErrorHandler = Callable[[ValidationError], str] + + +def return_null_string(e: ValidationError) -> str: + """Null value handler that always returns an empty string. + + Args: + e (ValidationError): A validation error. + + Returns: + str: An empty string. + """ + + warnings.warn( + "'return_null_string' is deprecated. Use 'NullValueHandler.return_null_string' instead.", + DeprecationWarning, + ) + + return "" + + +def return_timestamp(e: ValidationError) -> str: + """Null value handler that returns a timestamp of when the function was called. + + Args: + e (ValidationError): A validation error. + + Returns: + str: A timestamp. + """ + + warnings.warn( + "'return_timestamp' is deprecated. Use 'NullValueHandler.reserved_name_handler' instead.", + DeprecationWarning, + ) + + return str(datetime.now().timestamp()) + + +def raise_error(e: ValidationError) -> str: + """Null value handler that always raises an exception. + + Args: + e (ValidationError): A validation error. + + Raises: + ValidationError: Always raised. + """ + + raise e + + +class NullValueHandler: + @classmethod + def return_null_string(cls, e: ValidationError) -> str: + """Null value handler that always returns an empty string. + + Args: + e (ValidationError): A validation error. + + Returns: + str: An empty string. + """ + + return "" + + @classmethod + def return_timestamp(cls, e: ValidationError) -> str: + """Null value handler that returns a timestamp of when the function was called. + + Args: + e (ValidationError): A validation error. + + Returns: + str: A timestamp. + """ + + return str(datetime.now().timestamp()) + + +class ReservedNameHandler: + @classmethod + def add_leading_underscore(cls, e: ValidationError) -> str: + """Reserved name handler that adds a leading underscore (``"_"``) to the name + except for ``"."`` and ``".."``. + + Args: + e (ValidationError): A reserved name error. + + Returns: + str: The converted name. + """ + + if e.reserved_name in (".", "..") or e.reusable_name: + return e.reserved_name + + return f"_{e.reserved_name}" + + @classmethod + def add_trailing_underscore(cls, e: ValidationError) -> str: + """Reserved name handler that adds a trailing underscore (``"_"``) to the name + except for ``"."`` and ``".."``. + + Args: + e (ValidationError): A reserved name error. + + Returns: + str: The converted name. + """ + + if e.reserved_name in (".", "..") or e.reusable_name: + return e.reserved_name + + return f"{e.reserved_name}_" + + @classmethod + def as_is(cls, e: ValidationError) -> str: + """Reserved name handler that returns the name as is. + + Args: + e (ValidationError): A reserved name error. + + Returns: + str: The name as is. + """ + + return e.reserved_name diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/py.typed b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pathvalidate/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy-1.0.2.dist-info/INSTALLER b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy-1.0.2.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy-1.0.2.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy-1.0.2.dist-info/METADATA b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy-1.0.2.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..e09097c20cbda9cf5a9f2cc2119fb52005ad754d --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy-1.0.2.dist-info/METADATA @@ -0,0 +1,89 @@ +Metadata-Version: 2.4 +Name: patsy +Version: 1.0.2 +Summary: A Python package for describing statistical models and for building design matrices. +Home-page: https://github.com/pydata/patsy +Author: Nathaniel J. Smith +Author-email: njs@pobox.com +License: 2-clause BSD +Classifier: Development Status :: 6 - Mature +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Science/Research +Classifier: Intended Audience :: Financial and Insurance Industry +Classifier: License :: OSI Approved :: BSD License +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.6 +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.13 +Classifier: Topic :: Scientific/Engineering +Requires-Python: >=3.6 +Description-Content-Type: text/markdown +License-File: LICENSE.txt +Requires-Dist: numpy>=1.4 +Provides-Extra: test +Requires-Dist: pytest; extra == "test" +Requires-Dist: pytest-cov; extra == "test" +Requires-Dist: scipy; extra == "test" +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: description-content-type +Dynamic: home-page +Dynamic: license +Dynamic: license-file +Dynamic: provides-extra +Dynamic: requires-dist +Dynamic: requires-python +Dynamic: summary + +# Patsy + +**Notice:** `patsy` is no longer under active development. As of August 2021, +Matthew Wardrop (@matthewwardrop) and Tomás Capretto (@tomicapretto) have taken +on responsibility from Nathaniel Smith (@njsmith) for keeping the lights on, but +no new feature development is planned. The spiritual successor of this project +is [Formulaic](https://github.com/matthewwardrop/formulaic), and we +recommend that users [migrate](https://matthewwardrop.github.io/formulaic/migration/) +when possible. For the time being, until major software packages have successfully +transitioned, we will attempt to keep `patsy` working in its current state with +current releases in the Python ecosystem. + +--- + +Patsy is a Python library for describing statistical models +(especially linear models, or models that have a linear component) and +building design matrices. Patsy brings the convenience of [R](http://www.r-project.org/) "formulas" to Python. + +[![PyPI - Version](https://img.shields.io/pypi/v/patsy.svg)](https://pypi.org/project/spec-classes/) +![PyPI - Python Version](https://img.shields.io/pypi/pyversions/patsy.svg) +![https://patsy.readthedocs.io/](https://img.shields.io/badge/docs-read%20now-blue.svg) +![PyPI - Status](https://img.shields.io/pypi/status/patsy.svg) +[![https://coveralls.io/r/pydata/patsy?branch=master](https://coveralls.io/repos/pydata/patsy/badge.png?branch=master)](https://coveralls.io/github/pydata/patsy) +![https://doi.org/10.5281/zenodo.592075](https://zenodo.org/badge/DOI/10.5281/zenodo.592075.svg) + +- **Documentation:** +- **Downloads:** +- **Code and issues:** +- **Mailing list:** () + + +## Dependencies + + * Python (3.6+) + * numpy + * Optional: + * pytest/pytest-cov: needed to run tests + * scipy: needed for spline-related functions like ``bs`` + +## Installation + ``pip install patsy`` (or, for traditionalists: ``python setup.py install``) + +## License + +2-clause BSD, see LICENSE.txt for details. diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy-1.0.2.dist-info/RECORD b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy-1.0.2.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..7f1d6640a0d09b3fb4fafeb5ad93d4e691e9409f --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy-1.0.2.dist-info/RECORD @@ -0,0 +1,66 @@ +patsy-1.0.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +patsy-1.0.2.dist-info/METADATA,sha256=wJXZSPFbm9FvE9ClJ0naZwMarVO9BWUpXFMC8ZPky68,3626 +patsy-1.0.2.dist-info/RECORD,, +patsy-1.0.2.dist-info/WHEEL,sha256=AeO2BvogYWm3eGaHCvhzmUYt8ia7KfURiHzO_1atlys,109 +patsy-1.0.2.dist-info/licenses/LICENSE.txt,sha256=PySjI5M9NnkQ8yir-yH40XiR7zhn2UEBXecpOluoTrw,4313 +patsy-1.0.2.dist-info/top_level.txt,sha256=twKfN4KbeHgauQL25IXZRyHkuO4js0wIeKSnzXzYB2o,6 +patsy/__init__.py,sha256=HYe3BrOSFypfnQ04GBWygF5A9k2xBsVJHt6kh0Vq9Hg,3645 +patsy/__pycache__/__init__.cpython-310.pyc,, +patsy/__pycache__/build.cpython-310.pyc,, +patsy/__pycache__/builtins.cpython-310.pyc,, +patsy/__pycache__/categorical.cpython-310.pyc,, +patsy/__pycache__/compat.cpython-310.pyc,, +patsy/__pycache__/compat_ordereddict.cpython-310.pyc,, +patsy/__pycache__/constraint.cpython-310.pyc,, +patsy/__pycache__/contrasts.cpython-310.pyc,, +patsy/__pycache__/desc.cpython-310.pyc,, +patsy/__pycache__/design_info.cpython-310.pyc,, +patsy/__pycache__/eval.cpython-310.pyc,, +patsy/__pycache__/highlevel.cpython-310.pyc,, +patsy/__pycache__/infix_parser.cpython-310.pyc,, +patsy/__pycache__/mgcv_cubic_splines.cpython-310.pyc,, +patsy/__pycache__/missing.cpython-310.pyc,, +patsy/__pycache__/origin.cpython-310.pyc,, +patsy/__pycache__/parse_formula.cpython-310.pyc,, +patsy/__pycache__/redundancy.cpython-310.pyc,, +patsy/__pycache__/splines.cpython-310.pyc,, +patsy/__pycache__/state.cpython-310.pyc,, +patsy/__pycache__/test_build.cpython-310.pyc,, +patsy/__pycache__/test_highlevel.cpython-310.pyc,, +patsy/__pycache__/test_regressions.cpython-310.pyc,, +patsy/__pycache__/test_splines_bs_data.cpython-310.pyc,, +patsy/__pycache__/test_splines_crs_data.cpython-310.pyc,, +patsy/__pycache__/test_state.cpython-310.pyc,, +patsy/__pycache__/tokens.cpython-310.pyc,, +patsy/__pycache__/user_util.cpython-310.pyc,, +patsy/__pycache__/util.cpython-310.pyc,, +patsy/__pycache__/version.cpython-310.pyc,, +patsy/build.py,sha256=HL7yiFd_WnbsxzSt21HJ_JKq5lKUBYE9gp2JTQTjf9A,40374 +patsy/builtins.py,sha256=Wt6ECIRaLldvZj5RvtkQNHyOIAes_Cis9YFwTL9f7xc,3141 +patsy/categorical.py,sha256=oTLgFkbQqAQyml0vnqYXJ_obIXzW2xXq9zaTqtvtEOM,18978 +patsy/compat.py,sha256=MzTdXp4hw6JygZ5dsbSRN-_HQHbRKQh9OQuJQYVbHsc,1487 +patsy/compat_ordereddict.py,sha256=YiLUc0pFm1HdpkV4sUoiVkZBJiPFS9eGy6J7Rilfuxc,9178 +patsy/constraint.py,sha256=XUlEga8GW8odT6Nf7ps6z1tJOsWorZBJcSI0cj7MSQo,19851 +patsy/contrasts.py,sha256=Ur0HVW6PXNhauoBPB13iHH0FcR-6q-RiWVZk9ijEmp4,22987 +patsy/desc.py,sha256=3mt8My1_0d-ulrltKl4se2yRMIaH6clne0_lXR7qGVQ,22137 +patsy/design_info.py,sha256=6iUowe1hlaJjziWEhAOX6ROrIHRpx2tanRMHZp1AtQE,49789 +patsy/eval.py,sha256=WLaPWQrs_INqs8p1-21BXDNg6t31x7bDcnKae3-44T8,30874 +patsy/highlevel.py,sha256=mmlvwJiPOD4Z6ARhrffpLdWljvG7h3zooNStTkk3SPw,13601 +patsy/infix_parser.py,sha256=8S1SHsOLdr3CFmjmcFe0BmH4MQiX2-KHn2HbXESv-xA,9515 +patsy/mgcv_cubic_splines.py,sha256=JPWLfD72YSEN6rmWaqhJl2FlYHWl6g9bnTYUH7S5tW0,45193 +patsy/missing.py,sha256=M1-52gRFmVp_Z0jnyZfTUDqbyMTbmhaTcRt-P7H9J28,11384 +patsy/origin.py,sha256=T8vdAy3YMOWWHZPI4BsHKyy6Ntbi2VT9ar1sLfpfk7c,4598 +patsy/parse_formula.py,sha256=6FW0lxRzHzU5BsM7tuvLrH3frHl32O-K-wJsKW3mQzM,9401 +patsy/redundancy.py,sha256=XEDe6Ym4v4w4MnK63oRfQmWV5PzQQI--2Tdulte__v4,10632 +patsy/splines.py,sha256=1UgHJKtQZlpoSlU0V92lyrb3lfjxK0AM0Dtvs3lNbMU,16969 +patsy/state.py,sha256=W8eSHxDr7F-AfpcdRpzqBxESJwG9cZFepSQ8sQr5EBU,6830 +patsy/test_build.py,sha256=2Yj0P8X0LdCRm1UrjoVD0_bOqoT_Hdv4bjZAgmd6T0w,27428 +patsy/test_highlevel.py,sha256=Ldevqn9xrdqPrgOcLCiUsWFBrZxZVwLUBJID415YTf8,29244 +patsy/test_regressions.py,sha256=4c_Gdg8KitwKzcPYs4RlFZdtezT7iitqLds7ALzgQBk,849 +patsy/test_splines_bs_data.py,sha256=ocC_FOzdkoLKcwElhw96csdBQBteZSjL7DZBAcTxXqY,144178 +patsy/test_splines_crs_data.py,sha256=9QigM3tZxXWgEwSJKyKer_ka1ccrpnHTI7spRUvsO8o,133390 +patsy/test_state.py,sha256=foA55_WQYoLJNN5N4u9yxhCpDRWOga8feTibONPLLUc,7855 +patsy/tokens.py,sha256=yfSsQ7pse59mp9KigxSqxT-Rko1_2_Gljc6Xzf_qw4s,8138 +patsy/user_util.py,sha256=E53372TfMoGX2czUoaW4djN_TVRaIOu4pcYroC2P_p8,9308 +patsy/util.py,sha256=LlrdFWu6EZ3YsLL5X0NjfDjEYCM2xzjKIOvowvRUWFs,29219 +patsy/version.py,sha256=FFnFMPQM6hWTPPJkNhp2Y9LfFrIRyjbfuzsRpI58Guk,823 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy-1.0.2.dist-info/WHEEL b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy-1.0.2.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..586ed37c553156cb4053308fd11fb4992e46261a --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy-1.0.2.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: setuptools (79.0.1) +Root-Is-Purelib: true +Tag: py2-none-any +Tag: py3-none-any + diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy-1.0.2.dist-info/top_level.txt b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy-1.0.2.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..c8990fe096a12e0d34d48731947c381079324049 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy-1.0.2.dist-info/top_level.txt @@ -0,0 +1 @@ +patsy diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..50431ec93857b82503d65d345cc3612df7aa634f --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/__init__.py @@ -0,0 +1,140 @@ +# This file is part of Patsy +# Copyright (C) 2011-2013 Nathaniel Smith +# See file LICENSE.txt for license information. + +"""patsy is a Python package for describing statistical models and building +design matrices. It is closely inspired by the 'formula' mini-language used in +R and S.""" + +from patsy.version import __version__ + +# Do this first, to make it easy to check for warnings while testing: +import os + +if os.environ.get("PATSY_FORCE_NO_WARNINGS"): + import warnings + + warnings.filterwarnings("error", module="^patsy") + warnings.filterwarnings( + "ignore", + "is_categorical_dtype is deprecated", + DeprecationWarning, + module="^patsy", + ) + del warnings +del os + +import patsy.origin + + +class PatsyError(Exception): + """This is the main error type raised by Patsy functions. + + In addition to the usual Python exception features, you can pass a second + argument to this function specifying the origin of the error; this is + included in any error message, and used to help the user locate errors + arising from malformed formulas. This second argument should be an + :class:`Origin` object, or else an arbitrary object with a ``.origin`` + attribute. (If it is neither of these things, then it will simply be + ignored.) + + For ordinary display to the user with default formatting, use + ``str(exc)``. If you want to do something cleverer, you can use the + ``.message`` and ``.origin`` attributes directly. (The latter may be + None.) + """ + + def __init__(self, message, origin=None): + Exception.__init__(self, message) + self.message = message + self.origin = None + self.set_origin(origin) + + def __str__(self): + if self.origin is None: + return self.message + else: + return "%s\n%s" % (self.message, self.origin.caretize(indent=4)) + + def set_origin(self, origin): + # This is useful to modify an exception to add origin information as + # it "passes by", without losing traceback information. (In Python 3 + # we can use the built-in exception wrapping stuff, but it will be + # some time before we can count on that...) + if self.origin is None: + if hasattr(origin, "origin"): + origin = origin.origin + if not isinstance(origin, patsy.origin.Origin): + origin = None + self.origin = origin + + +__all__ = ["PatsyError"] + +# We make a rich API available for explicit use. To see what exactly is +# exported, check each module's __all__, or import this module and look at its +# __all__. + + +def _reexport(mod): + __all__.extend(mod.__all__) + for var in mod.__all__: + globals()[var] = getattr(mod, var) + + +# This used to have less copy-paste, but explicit import statements make +# packaging tools like py2exe and py2app happier. Sigh. +import patsy.highlevel + +_reexport(patsy.highlevel) + +import patsy.build + +_reexport(patsy.build) + +import patsy.constraint + +_reexport(patsy.constraint) + +import patsy.contrasts + +_reexport(patsy.contrasts) + +import patsy.desc + +_reexport(patsy.desc) + +import patsy.design_info + +_reexport(patsy.design_info) + +import patsy.eval + +_reexport(patsy.eval) + +import patsy.origin + +_reexport(patsy.origin) + +import patsy.state + +_reexport(patsy.state) + +import patsy.user_util + +_reexport(patsy.user_util) + +import patsy.missing + +_reexport(patsy.missing) + +import patsy.splines + +_reexport(patsy.splines) + +import patsy.mgcv_cubic_splines + +_reexport(patsy.mgcv_cubic_splines) + +# XX FIXME: we aren't exporting any of the explicit parsing interface +# yet. Need to figure out how to do that. diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/build.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/build.py new file mode 100644 index 0000000000000000000000000000000000000000..cbe25248c5fed323b894d04322ac4829744013f4 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/build.py @@ -0,0 +1,1026 @@ +# This file is part of Patsy +# Copyright (C) 2011-2015 Nathaniel Smith +# See file LICENSE.txt for license information. + +# This file defines the core design matrix building functions. + +# These are made available in the patsy.* namespace +__all__ = ["design_matrix_builders", "build_design_matrices"] + +import itertools + +import numpy as np +from patsy import PatsyError +from patsy.categorical import guess_categorical, CategoricalSniffer, categorical_to_int +from patsy.util import ( + atleast_2d_column_default, + have_pandas, + asarray_or_pandas, + safe_issubdtype, +) +from patsy.design_info import DesignMatrix, DesignInfo, FactorInfo, SubtermInfo +from patsy.redundancy import pick_contrasts_for_term +from patsy.eval import EvalEnvironment +from patsy.contrasts import code_contrast_matrix, Treatment +from patsy.compat import OrderedDict +from patsy.missing import NAAction + +if have_pandas: + import pandas + + +class _MockFactor(object): + def __init__(self, name="MOCKMOCK"): + self._name = name + + def eval(self, state, env): + return env["mock"] + + def name(self): + return self._name + + +def _max_allowed_dim(dim, arr, factor): + if arr.ndim > dim: + msg = ( + "factor '%s' evaluates to an %s-dimensional array; I only " + "handle arrays with dimension <= %s" % (factor.name(), arr.ndim, dim) + ) + raise PatsyError(msg, factor) + + +def test__max_allowed_dim(): + import pytest + + f = _MockFactor() + _max_allowed_dim(1, np.array(1), f) + _max_allowed_dim(1, np.array([1]), f) + pytest.raises(PatsyError, _max_allowed_dim, 1, np.array([[1]]), f) + pytest.raises(PatsyError, _max_allowed_dim, 1, np.array([[[1]]]), f) + _max_allowed_dim(2, np.array(1), f) + _max_allowed_dim(2, np.array([1]), f) + _max_allowed_dim(2, np.array([[1]]), f) + pytest.raises(PatsyError, _max_allowed_dim, 2, np.array([[[1]]]), f) + + +def _eval_factor(factor_info, data, NA_action): + factor = factor_info.factor + result = factor.eval(factor_info.state, data) + # Returns either a 2d ndarray, or a DataFrame, plus is_NA mask + if factor_info.type == "numerical": + result = atleast_2d_column_default(result, preserve_pandas=True) + _max_allowed_dim(2, result, factor) + if result.shape[1] != factor_info.num_columns: + raise PatsyError( + "when evaluating factor %s, I got %s columns " + "instead of the %s I was expecting" + % (factor.name(), factor_info.num_columns, result.shape[1]), + factor, + ) + if not safe_issubdtype(np.asarray(result).dtype, np.number): + raise PatsyError( + "when evaluating numeric factor %s, " + "I got non-numeric data of type '%s'" % (factor.name(), result.dtype), + factor, + ) + return result, NA_action.is_numerical_NA(result) + # returns either a 1d ndarray or a pandas.Series, plus is_NA mask + else: + assert factor_info.type == "categorical" + result = categorical_to_int( + result, factor_info.categories, NA_action, origin=factor_info.factor + ) + assert result.ndim == 1 + return result, np.asarray(result == -1) + + +def test__eval_factor_numerical(): + import pytest + + naa = NAAction() + f = _MockFactor() + + fi1 = FactorInfo(f, "numerical", {}, num_columns=1, categories=None) + + assert fi1.factor is f + eval123, is_NA = _eval_factor(fi1, {"mock": [1, 2, 3]}, naa) + assert eval123.shape == (3, 1) + assert np.all(eval123 == [[1], [2], [3]]) + assert is_NA.shape == (3,) + assert np.all(~is_NA) + pytest.raises(PatsyError, _eval_factor, fi1, {"mock": [[[1]]]}, naa) + pytest.raises(PatsyError, _eval_factor, fi1, {"mock": [[1, 2]]}, naa) + pytest.raises(PatsyError, _eval_factor, fi1, {"mock": ["a", "b"]}, naa) + pytest.raises(PatsyError, _eval_factor, fi1, {"mock": [True, False]}, naa) + fi2 = FactorInfo(_MockFactor(), "numerical", {}, num_columns=2, categories=None) + eval123321, is_NA = _eval_factor(fi2, {"mock": [[1, 3], [2, 2], [3, 1]]}, naa) + assert eval123321.shape == (3, 2) + assert np.all(eval123321 == [[1, 3], [2, 2], [3, 1]]) + assert is_NA.shape == (3,) + assert np.all(~is_NA) + pytest.raises(PatsyError, _eval_factor, fi2, {"mock": [1, 2, 3]}, naa) + pytest.raises(PatsyError, _eval_factor, fi2, {"mock": [[1, 2, 3]]}, naa) + + ev_nan, is_NA = _eval_factor( + fi1, {"mock": [1, 2, np.nan]}, NAAction(NA_types=["NaN"]) + ) + assert np.array_equal(is_NA, [False, False, True]) + ev_nan, is_NA = _eval_factor(fi1, {"mock": [1, 2, np.nan]}, NAAction(NA_types=[])) + assert np.array_equal(is_NA, [False, False, False]) + + if have_pandas: + eval_ser, _ = _eval_factor( + fi1, {"mock": pandas.Series([1, 2, 3], index=[10, 20, 30])}, naa + ) + assert isinstance(eval_ser, pandas.DataFrame) + assert np.array_equal(eval_ser, [[1], [2], [3]]) + assert np.array_equal(eval_ser.index, [10, 20, 30]) + eval_df1, _ = _eval_factor( + fi1, {"mock": pandas.DataFrame([[2], [1], [3]], index=[20, 10, 30])}, naa + ) + assert isinstance(eval_df1, pandas.DataFrame) + assert np.array_equal(eval_df1, [[2], [1], [3]]) + assert np.array_equal(eval_df1.index, [20, 10, 30]) + eval_df2, _ = _eval_factor( + fi2, + {"mock": pandas.DataFrame([[2, 3], [1, 4], [3, -1]], index=[20, 30, 10])}, + naa, + ) + assert isinstance(eval_df2, pandas.DataFrame) + assert np.array_equal(eval_df2, [[2, 3], [1, 4], [3, -1]]) + assert np.array_equal(eval_df2.index, [20, 30, 10]) + + pytest.raises( + PatsyError, + _eval_factor, + fi2, + {"mock": pandas.Series([1, 2, 3], index=[10, 20, 30])}, + naa, + ) + pytest.raises( + PatsyError, + _eval_factor, + fi1, + {"mock": pandas.DataFrame([[2, 3], [1, 4], [3, -1]], index=[20, 30, 10])}, + naa, + ) + + +def test__eval_factor_categorical(): + import pytest + from patsy.categorical import C + + naa = NAAction() + f = _MockFactor() + fi1 = FactorInfo(f, "categorical", {}, num_columns=None, categories=("a", "b")) + assert fi1.factor is f + cat1, _ = _eval_factor(fi1, {"mock": ["b", "a", "b"]}, naa) + assert cat1.shape == (3,) + assert np.all(cat1 == [1, 0, 1]) + pytest.raises(PatsyError, _eval_factor, fi1, {"mock": ["c"]}, naa) + pytest.raises(PatsyError, _eval_factor, fi1, {"mock": C(["a", "c"])}, naa) + pytest.raises( + PatsyError, _eval_factor, fi1, {"mock": C(["a", "b"], levels=["b", "a"])}, naa + ) + pytest.raises(PatsyError, _eval_factor, fi1, {"mock": [1, 0, 1]}, naa) + bad_cat = np.asarray(["b", "a", "a", "b"]) + bad_cat.resize((2, 2)) + pytest.raises(PatsyError, _eval_factor, fi1, {"mock": bad_cat}, naa) + + cat1_NA, is_NA = _eval_factor( + fi1, {"mock": ["a", None, "b"]}, NAAction(NA_types=["None"]) + ) + assert np.array_equal(is_NA, [False, True, False]) + assert np.array_equal(cat1_NA, [0, -1, 1]) + pytest.raises( + PatsyError, _eval_factor, fi1, {"mock": ["a", None, "b"]}, NAAction(NA_types=[]) + ) + + fi2 = FactorInfo( + _MockFactor(), "categorical", {}, num_columns=None, categories=[False, True] + ) + cat2, _ = _eval_factor(fi2, {"mock": [True, False, False, True]}, naa) + assert cat2.shape == (4,) + assert np.all(cat2 == [1, 0, 0, 1]) + + if have_pandas: + s = pandas.Series(["b", "a"], index=[10, 20]) + cat_s, _ = _eval_factor(fi1, {"mock": s}, naa) + assert isinstance(cat_s, pandas.Series) + assert np.array_equal(cat_s, [1, 0]) + assert np.array_equal(cat_s.index, [10, 20]) + sbool = pandas.Series([True, False], index=[11, 21]) + cat_sbool, _ = _eval_factor(fi2, {"mock": sbool}, naa) + assert isinstance(cat_sbool, pandas.Series) + assert np.array_equal(cat_sbool, [1, 0]) + assert np.array_equal(cat_sbool.index, [11, 21]) + + +def _column_combinations(columns_per_factor): + # For consistency with R, the left-most item iterates fastest: + iterators = [range(n) for n in reversed(columns_per_factor)] + for reversed_combo in itertools.product(*iterators): + yield reversed_combo[::-1] + + +def test__column_combinations(): + assert list(_column_combinations([2, 3])) == [ + (0, 0), + (1, 0), + (0, 1), + (1, 1), + (0, 2), + (1, 2), + ] + assert list(_column_combinations([3])) == [(0,), (1,), (2,)] + assert list(_column_combinations([])) == [()] + + +def _subterm_column_combinations(factor_infos, subterm): + columns_per_factor = [] + for factor in subterm.factors: + if factor in subterm.contrast_matrices: + columns = subterm.contrast_matrices[factor].matrix.shape[1] + else: + columns = factor_infos[factor].num_columns + columns_per_factor.append(columns) + return _column_combinations(columns_per_factor) + + +def _subterm_column_names_iter(factor_infos, subterm): + total = 0 + for i, column_idxs in enumerate( + _subterm_column_combinations(factor_infos, subterm) + ): + name_pieces = [] + for factor, column_idx in zip(subterm.factors, column_idxs): + fi = factor_infos[factor] + if fi.type == "numerical": + if fi.num_columns > 1: + name_pieces.append("%s[%s]" % (factor.name(), column_idx)) + else: + assert column_idx == 0 + name_pieces.append(factor.name()) + else: + assert fi.type == "categorical" + contrast = subterm.contrast_matrices[factor] + suffix = contrast.column_suffixes[column_idx] + name_pieces.append("%s%s" % (factor.name(), suffix)) + if not name_pieces: + yield "Intercept" + else: + yield ":".join(name_pieces) + total += 1 + assert total == subterm.num_columns + + +def _build_subterm(subterm, factor_infos, factor_values, out): + assert subterm.num_columns == out.shape[1] + out[...] = 1 + for i, column_idxs in enumerate( + _subterm_column_combinations(factor_infos, subterm) + ): + for factor, column_idx in zip(subterm.factors, column_idxs): + if factor_infos[factor].type == "categorical": + contrast = subterm.contrast_matrices[factor] + if np.any(factor_values[factor] < 0): + raise PatsyError( + "can't build a design matrix containing missing values", + factor, + ) + out[:, i] *= contrast.matrix[factor_values[factor], column_idx] + else: + assert factor_infos[factor].type == "numerical" + assert ( + factor_values[factor].shape[1] == factor_infos[factor].num_columns + ) + out[:, i] *= factor_values[factor][:, column_idx] + + +def test__subterm_column_names_iter_and__build_subterm(): + import pytest + from patsy.contrasts import ContrastMatrix + from patsy.categorical import C + + f1 = _MockFactor("f1") + f2 = _MockFactor("f2") + f3 = _MockFactor("f3") + contrast = ContrastMatrix(np.array([[0, 0.5], [3, 0]]), ["[c1]", "[c2]"]) + + factor_infos1 = { + f1: FactorInfo(f1, "numerical", {}, num_columns=1, categories=None), + f2: FactorInfo(f2, "categorical", {}, num_columns=None, categories=["a", "b"]), + f3: FactorInfo(f3, "numerical", {}, num_columns=1, categories=None), + } + contrast_matrices = {f2: contrast} + subterm1 = SubtermInfo([f1, f2, f3], contrast_matrices, 2) + assert list(_subterm_column_names_iter(factor_infos1, subterm1)) == [ + "f1:f2[c1]:f3", + "f1:f2[c2]:f3", + ] + + mat = np.empty((3, 2)) + _build_subterm( + subterm1, + factor_infos1, + { + f1: atleast_2d_column_default([1, 2, 3]), + f2: np.asarray([0, 0, 1]), + f3: atleast_2d_column_default([7.5, 2, -12]), + }, + mat, + ) + assert np.allclose(mat, [[0, 0.5 * 1 * 7.5], [0, 0.5 * 2 * 2], [3 * 3 * -12, 0]]) + # Check that missing categorical values blow up + pytest.raises( + PatsyError, + _build_subterm, + subterm1, + factor_infos1, + { + f1: atleast_2d_column_default([1, 2, 3]), + f2: np.asarray([0, -1, 1]), + f3: atleast_2d_column_default([7.5, 2, -12]), + }, + mat, + ) + + factor_infos2 = dict(factor_infos1) + factor_infos2[f1] = FactorInfo(f1, "numerical", {}, num_columns=2, categories=None) + subterm2 = SubtermInfo([f1, f2, f3], contrast_matrices, 4) + assert list(_subterm_column_names_iter(factor_infos2, subterm2)) == [ + "f1[0]:f2[c1]:f3", + "f1[1]:f2[c1]:f3", + "f1[0]:f2[c2]:f3", + "f1[1]:f2[c2]:f3", + ] + + mat2 = np.empty((3, 4)) + _build_subterm( + subterm2, + factor_infos2, + { + f1: atleast_2d_column_default([[1, 2], [3, 4], [5, 6]]), + f2: np.asarray([0, 0, 1]), + f3: atleast_2d_column_default([7.5, 2, -12]), + }, + mat2, + ) + assert np.allclose( + mat2, + [ + [0, 0, 0.5 * 1 * 7.5, 0.5 * 2 * 7.5], + [0, 0, 0.5 * 3 * 2, 0.5 * 4 * 2], + [3 * 5 * -12, 3 * 6 * -12, 0, 0], + ], + ) + + subterm_int = SubtermInfo([], {}, 1) + assert list(_subterm_column_names_iter({}, subterm_int)) == ["Intercept"] + + mat3 = np.empty((3, 1)) + _build_subterm(subterm_int, {}, {f1: [1, 2, 3], f2: [1, 2, 3], f3: [1, 2, 3]}, mat3) + assert np.allclose(mat3, 1) + + +def _factors_memorize(factors, data_iter_maker, eval_env): + # First, start off the memorization process by setting up each factor's + # state and finding out how many passes it will need: + factor_states = {} + passes_needed = {} + for factor in factors: + state = {} + which_pass = factor.memorize_passes_needed(state, eval_env) + factor_states[factor] = state + passes_needed[factor] = which_pass + # Now, cycle through the data until all the factors have finished + # memorizing everything: + memorize_needed = set() + for factor, passes in passes_needed.items(): + if passes > 0: + memorize_needed.add(factor) + which_pass = 0 + while memorize_needed: + for data in data_iter_maker(): + for factor in memorize_needed: + state = factor_states[factor] + factor.memorize_chunk(state, which_pass, data) + for factor in list(memorize_needed): + factor.memorize_finish(factor_states[factor], which_pass) + if which_pass == passes_needed[factor] - 1: + memorize_needed.remove(factor) + which_pass += 1 + return factor_states + + +def test__factors_memorize(): + class MockFactor(object): + def __init__(self, requested_passes, token): + self._requested_passes = requested_passes + self._token = token + self._chunk_in_pass = 0 + self._seen_passes = 0 + + def memorize_passes_needed(self, state, eval_env): + state["calls"] = [] + state["token"] = self._token + return self._requested_passes + + def memorize_chunk(self, state, which_pass, data): + state["calls"].append(("memorize_chunk", which_pass)) + assert data["chunk"] == self._chunk_in_pass + self._chunk_in_pass += 1 + + def memorize_finish(self, state, which_pass): + state["calls"].append(("memorize_finish", which_pass)) + self._chunk_in_pass = 0 + + class Data(object): + CHUNKS = 3 + + def __init__(self): + self.calls = 0 + self.data = [{"chunk": i} for i in range(self.CHUNKS)] + + def __call__(self): + self.calls += 1 + return iter(self.data) + + data = Data() + f0 = MockFactor(0, "f0") + f1 = MockFactor(1, "f1") + f2a = MockFactor(2, "f2a") + f2b = MockFactor(2, "f2b") + factor_states = _factors_memorize(set([f0, f1, f2a, f2b]), data, {}) + assert data.calls == 2 + mem_chunks0 = [("memorize_chunk", 0)] * data.CHUNKS + mem_chunks1 = [("memorize_chunk", 1)] * data.CHUNKS + expected = { + f0: { + "calls": [], + "token": "f0", + }, + f1: { + "calls": mem_chunks0 + [("memorize_finish", 0)], + "token": "f1", + }, + f2a: { + "calls": mem_chunks0 + + [("memorize_finish", 0)] + + mem_chunks1 + + [("memorize_finish", 1)], + "token": "f2a", + }, + f2b: { + "calls": mem_chunks0 + + [("memorize_finish", 0)] + + mem_chunks1 + + [("memorize_finish", 1)], + "token": "f2b", + }, + } + assert factor_states == expected + + +def _examine_factor_types(factors, factor_states, data_iter_maker, NA_action): + num_column_counts = {} + cat_sniffers = {} + examine_needed = set(factors) + for data in data_iter_maker(): + for factor in list(examine_needed): + value = factor.eval(factor_states[factor], data) + if factor in cat_sniffers or guess_categorical(value): + if factor not in cat_sniffers: + cat_sniffers[factor] = CategoricalSniffer(NA_action, factor.origin) + done = cat_sniffers[factor].sniff(value) + if done: + examine_needed.remove(factor) + else: + # Numeric + value = atleast_2d_column_default(value) + _max_allowed_dim(2, value, factor) + column_count = value.shape[1] + num_column_counts[factor] = column_count + examine_needed.remove(factor) + if not examine_needed: + break + # Pull out the levels + cat_levels_contrasts = {} + for factor, sniffer in cat_sniffers.items(): + cat_levels_contrasts[factor] = sniffer.levels_contrast() + return (num_column_counts, cat_levels_contrasts) + + +def test__examine_factor_types(): + from patsy.categorical import C + + class MockFactor(object): + def __init__(self): + # You should check this using 'is', not '==' + from patsy.origin import Origin + + self.origin = Origin("MOCK", 1, 2) + + def eval(self, state, data): + return state[data] + + def name(self): + return "MOCK MOCK" + + # This hacky class can only be iterated over once, but it keeps track of + # how far it got. + class DataIterMaker(object): + def __init__(self): + self.i = -1 + + def __call__(self): + return self + + def __iter__(self): + return self + + def next(self): + self.i += 1 + if self.i > 1: + raise StopIteration + return self.i + + __next__ = next + + num_1dim = MockFactor() + num_1col = MockFactor() + num_4col = MockFactor() + categ_1col = MockFactor() + bool_1col = MockFactor() + string_1col = MockFactor() + object_1col = MockFactor() + object_levels = (object(), object(), object()) + factor_states = { + num_1dim: ([1, 2, 3], [4, 5, 6]), + num_1col: ([[1], [2], [3]], [[4], [5], [6]]), + num_4col: (np.zeros((3, 4)), np.ones((3, 4))), + categ_1col: ( + C(["a", "b", "c"], levels=("a", "b", "c"), contrast="MOCK CONTRAST"), + C(["c", "b", "a"], levels=("a", "b", "c"), contrast="MOCK CONTRAST"), + ), + bool_1col: ([True, True, False], [False, True, True]), + # It has to read through all the data to see all the possible levels: + string_1col: (["a", "a", "a"], ["c", "b", "a"]), + object_1col: ([object_levels[0]] * 3, object_levels), + } + + it = DataIterMaker() + ( + num_column_counts, + cat_levels_contrasts, + ) = _examine_factor_types(factor_states.keys(), factor_states, it, NAAction()) + assert it.i == 2 + iterations = 0 + assert num_column_counts == {num_1dim: 1, num_1col: 1, num_4col: 4} + assert cat_levels_contrasts == { + categ_1col: (("a", "b", "c"), "MOCK CONTRAST"), + bool_1col: ((False, True), None), + string_1col: (("a", "b", "c"), None), + object_1col: (tuple(sorted(object_levels, key=id)), None), + } + + # Check that it doesn't read through all the data if that's not necessary: + it = DataIterMaker() + no_read_necessary = [num_1dim, num_1col, num_4col, categ_1col, bool_1col] + ( + num_column_counts, + cat_levels_contrasts, + ) = _examine_factor_types(no_read_necessary, factor_states, it, NAAction()) + assert it.i == 0 + assert num_column_counts == {num_1dim: 1, num_1col: 1, num_4col: 4} + assert cat_levels_contrasts == { + categ_1col: (("a", "b", "c"), "MOCK CONTRAST"), + bool_1col: ((False, True), None), + } + + # Illegal inputs: + bool_3col = MockFactor() + num_3dim = MockFactor() + # no such thing as a multi-dimensional Categorical + # categ_3dim = MockFactor() + string_3col = MockFactor() + object_3col = MockFactor() + illegal_factor_states = { + num_3dim: (np.zeros((3, 3, 3)), np.ones((3, 3, 3))), + string_3col: ([["a", "b", "c"]], [["b", "c", "a"]]), + object_3col: ([[[object()]]], [[[object()]]]), + } + import pytest + + for illegal_factor in illegal_factor_states: + it = DataIterMaker() + try: + _examine_factor_types( + [illegal_factor], illegal_factor_states, it, NAAction() + ) + except PatsyError as e: + assert e.origin is illegal_factor.origin + else: + assert False + + +def _make_subterm_infos(terms, num_column_counts, cat_levels_contrasts): + # Sort each term into a bucket based on the set of numeric factors it + # contains: + term_buckets = OrderedDict() + bucket_ordering = [] + for term in terms: + num_factors = [] + for factor in term.factors: + if factor in num_column_counts: + num_factors.append(factor) + bucket = frozenset(num_factors) + if bucket not in term_buckets: + bucket_ordering.append(bucket) + term_buckets.setdefault(bucket, []).append(term) + # Special rule: if there is a no-numerics bucket, then it always comes + # first: + if frozenset() in term_buckets: + bucket_ordering.remove(frozenset()) + bucket_ordering.insert(0, frozenset()) + term_to_subterm_infos = OrderedDict() + new_term_order = [] + # Then within each bucket, work out which sort of contrasts we want to use + # for each term to avoid redundancy + for bucket in bucket_ordering: + bucket_terms = term_buckets[bucket] + # Sort by degree of interaction + bucket_terms.sort(key=lambda t: len(t.factors)) + new_term_order += bucket_terms + used_subterms = set() + for term in bucket_terms: + subterm_infos = [] + factor_codings = pick_contrasts_for_term( + term, num_column_counts, used_subterms + ) + # Construct one SubtermInfo for each subterm + for factor_coding in factor_codings: + subterm_factors = [] + contrast_matrices = {} + subterm_columns = 1 + # In order to preserve factor ordering information, the + # coding_for_term just returns dicts, and we refer to + # the original factors to figure out which are included in + # each subterm, and in what order + for factor in term.factors: + # Numeric factors are included in every subterm + if factor in num_column_counts: + subterm_factors.append(factor) + subterm_columns *= num_column_counts[factor] + elif factor in factor_coding: + subterm_factors.append(factor) + levels, contrast = cat_levels_contrasts[factor] + # This is where the default coding is set to + # Treatment: + coded = code_contrast_matrix( + factor_coding[factor], levels, contrast, default=Treatment + ) + contrast_matrices[factor] = coded + subterm_columns *= coded.matrix.shape[1] + subterm_infos.append( + SubtermInfo(subterm_factors, contrast_matrices, subterm_columns) + ) + term_to_subterm_infos[term] = subterm_infos + assert new_term_order == list(term_to_subterm_infos) + return term_to_subterm_infos + + +def design_matrix_builders(termlists, data_iter_maker, eval_env, NA_action="drop"): + """Construct several :class:`DesignInfo` objects from termlists. + + This is one of Patsy's fundamental functions. This function and + :func:`build_design_matrices` together form the API to the core formula + interpretation machinery. + + :arg termlists: A list of termlists, where each termlist is a list of + :class:`Term` objects which together specify a design matrix. + :arg data_iter_maker: A zero-argument callable which returns an iterator + over dict-like data objects. This must be a callable rather than a + simple iterator because sufficiently complex formulas may require + multiple passes over the data (e.g. if there are nested stateful + transforms). + :arg eval_env: Either a :class:`EvalEnvironment` which will be used to + look up any variables referenced in `termlists` that cannot be + found in `data_iter_maker`, or else a depth represented as an + integer which will be passed to :meth:`EvalEnvironment.capture`. + ``eval_env=0`` means to use the context of the function calling + :func:`design_matrix_builders` for lookups. If calling this function + from a library, you probably want ``eval_env=1``, which means that + variables should be resolved in *your* caller's namespace. + :arg NA_action: An :class:`NAAction` object or string, used to determine + what values count as 'missing' for purposes of determining the levels of + categorical factors. + :returns: A list of :class:`DesignInfo` objects, one for each + termlist passed in. + + This function performs zero or more iterations over the data in order to + sniff out any necessary information about factor types, set up stateful + transforms, pick column names, etc. + + See :ref:`formulas` for details. + + .. versionadded:: 0.2.0 + The ``NA_action`` argument. + .. versionadded:: 0.4.0 + The ``eval_env`` argument. + """ + # People upgrading from versions prior to 0.4.0 could potentially have + # passed NA_action as the 3rd positional argument. Fortunately + # EvalEnvironment.capture only accepts int and EvalEnvironment objects, + # and we improved its error messages to make this clear. + eval_env = EvalEnvironment.capture(eval_env, reference=1) + if isinstance(NA_action, str): + NA_action = NAAction(NA_action) + all_factors = set() + for termlist in termlists: + for term in termlist: + all_factors.update(term.factors) + factor_states = _factors_memorize(all_factors, data_iter_maker, eval_env) + # Now all the factors have working eval methods, so we can evaluate them + # on some data to find out what type of data they return. + (num_column_counts, cat_levels_contrasts) = _examine_factor_types( + all_factors, factor_states, data_iter_maker, NA_action + ) + # Now we need the factor infos, which encapsulate the knowledge of + # how to turn any given factor into a chunk of data: + factor_infos = {} + for factor in all_factors: + if factor in num_column_counts: + fi = FactorInfo( + factor, + "numerical", + factor_states[factor], + num_columns=num_column_counts[factor], + categories=None, + ) + else: + assert factor in cat_levels_contrasts + categories = cat_levels_contrasts[factor][0] + fi = FactorInfo( + factor, + "categorical", + factor_states[factor], + num_columns=None, + categories=categories, + ) + factor_infos[factor] = fi + # And now we can construct the DesignInfo for each termlist: + design_infos = [] + for termlist in termlists: + term_to_subterm_infos = _make_subterm_infos( + termlist, num_column_counts, cat_levels_contrasts + ) + assert isinstance(term_to_subterm_infos, OrderedDict) + assert frozenset(term_to_subterm_infos) == frozenset(termlist) + this_design_factor_infos = {} + for term in termlist: + for factor in term.factors: + this_design_factor_infos[factor] = factor_infos[factor] + column_names = [] + for subterms in term_to_subterm_infos.values(): + for subterm in subterms: + for column_name in _subterm_column_names_iter(factor_infos, subterm): + column_names.append(column_name) + design_infos.append( + DesignInfo( + column_names, + factor_infos=this_design_factor_infos, + term_codings=term_to_subterm_infos, + ) + ) + return design_infos + + +def _build_design_matrix(design_info, factor_info_to_values, dtype): + factor_to_values = {} + need_reshape = False + num_rows = None + for factor_info, value in factor_info_to_values.items(): + # It's possible that the same factor appears in multiple different + # FactorInfo objects (e.g. if someone is simultaneously building two + # DesignInfo objects that started out as part of different + # formulas). Skip any factor_info that is not our expected + # factor_info. + if design_info.factor_infos.get(factor_info.factor) is not factor_info: + continue + factor_to_values[factor_info.factor] = value + if num_rows is not None: + assert num_rows == value.shape[0] + else: + num_rows = value.shape[0] + if num_rows is None: + # We have no dependence on the data -- e.g. an empty termlist, or + # only an intercept term. + num_rows = 1 + need_reshape = True + shape = (num_rows, len(design_info.column_names)) + m = DesignMatrix(np.empty(shape, dtype=dtype), design_info) + start_column = 0 + for term, subterms in design_info.term_codings.items(): + for subterm in subterms: + end_column = start_column + subterm.num_columns + m_slice = m[:, start_column:end_column] + _build_subterm(subterm, design_info.factor_infos, factor_to_values, m_slice) + start_column = end_column + assert start_column == m.shape[1] + return need_reshape, m + + +class _CheckMatch(object): + def __init__(self, name, eq_fn): + self._name = name + self._eq_fn = eq_fn + self.value = None + self._value_desc = None + self._value_origin = None + + def check(self, seen_value, desc, origin): + if self.value is None: + self.value = seen_value + self._value_desc = desc + self._value_origin = origin + else: + if not self._eq_fn(self.value, seen_value): + msg = "%s mismatch between %s and %s" % ( + self._name, + self._value_desc, + desc, + ) + if isinstance(self.value, int): + msg += " (%r versus %r)" % (self.value, seen_value) + # XX FIXME: this is a case where having discontiguous Origins + # would be useful... + raise PatsyError(msg, origin) + + +def build_design_matrices( + design_infos, data, NA_action="drop", return_type="matrix", dtype=np.dtype(float) +): + """Construct several design matrices from :class:`DesignMatrixBuilder` + objects. + + This is one of Patsy's fundamental functions. This function and + :func:`design_matrix_builders` together form the API to the core formula + interpretation machinery. + + :arg design_infos: A list of :class:`DesignInfo` objects describing the + design matrices to be built. + :arg data: A dict-like object which will be used to look up data. + :arg NA_action: What to do with rows that contain missing values. You can + ``"drop"`` them, ``"raise"`` an error, or for customization, pass an + :class:`NAAction` object. See :class:`NAAction` for details on what + values count as 'missing' (and how to alter this). + :arg return_type: Either ``"matrix"`` or ``"dataframe"``. See below. + :arg dtype: The dtype of the returned matrix. Useful if you want to use + single-precision or extended-precision. + + This function returns either a list of :class:`DesignMatrix` objects (for + ``return_type="matrix"``) or a list of :class:`pandas.DataFrame` objects + (for ``return_type="dataframe"``). In both cases, all returned design + matrices will have ``.design_info`` attributes containing the appropriate + :class:`DesignInfo` objects. + + Note that unlike :func:`design_matrix_builders`, this function takes only + a simple data argument, not any kind of iterator. That's because this + function doesn't need a global view of the data -- everything that depends + on the whole data set is already encapsulated in the ``design_infos``. If + you are incrementally processing a large data set, simply call this + function for each chunk. + + Index handling: This function always checks for indexes in the following + places: + + * If ``data`` is a :class:`pandas.DataFrame`, its ``.index`` attribute. + * If any factors evaluate to a :class:`pandas.Series` or + :class:`pandas.DataFrame`, then their ``.index`` attributes. + + If multiple indexes are found, they must be identical (same values in the + same order). If no indexes are found, then a default index is generated + using ``np.arange(num_rows)``. One way or another, we end up with a single + index for all the data. If ``return_type="dataframe"``, then this index is + used as the index of the returned DataFrame objects. Examining this index + makes it possible to determine which rows were removed due to NAs. + + Determining the number of rows in design matrices: This is not as obvious + as it might seem, because it's possible to have a formula like "~ 1" that + doesn't depend on the data (it has no factors). For this formula, it's + obvious what every row in the design matrix should look like (just the + value ``1``); but, how many rows like this should there be? To determine + the number of rows in a design matrix, this function always checks in the + following places: + + * If ``data`` is a :class:`pandas.DataFrame`, then its number of rows. + * The number of entries in any factors present in any of the design + * matrices being built. + + All these values much match. In particular, if this function is called to + generate multiple design matrices at once, then they must all have the + same number of rows. + + .. versionadded:: 0.2.0 + The ``NA_action`` argument. + + """ + if isinstance(NA_action, str): + NA_action = NAAction(NA_action) + if return_type == "dataframe" and not have_pandas: + raise PatsyError("pandas.DataFrame was requested, but pandas is not installed") + if return_type not in ("matrix", "dataframe"): + raise PatsyError( + "unrecognized output type %r, should be " + "'matrix' or 'dataframe'" % (return_type,) + ) + # Evaluate factors + factor_info_to_values = {} + factor_info_to_isNAs = {} + rows_checker = _CheckMatch("Number of rows", lambda a, b: a == b) + index_checker = _CheckMatch("Index", lambda a, b: a.equals(b)) + if have_pandas and isinstance(data, pandas.DataFrame): + index_checker.check(data.index, "data.index", None) + rows_checker.check(data.shape[0], "data argument", None) + for design_info in design_infos: + # We look at evaluators rather than factors here, because it might + # happen that we have the same factor twice, but with different + # memorized state. + for factor_info in design_info.factor_infos.values(): + if factor_info not in factor_info_to_values: + value, is_NA = _eval_factor(factor_info, data, NA_action) + factor_info_to_isNAs[factor_info] = is_NA + # value may now be a Series, DataFrame, or ndarray + name = factor_info.factor.name() + origin = factor_info.factor.origin + rows_checker.check(value.shape[0], name, origin) + if have_pandas and isinstance(value, (pandas.Series, pandas.DataFrame)): + index_checker.check(value.index, name, origin) + # Strategy: we work with raw ndarrays for doing the actual + # combining; DesignMatrixBuilder objects never sees pandas + # objects. Then at the end, if a DataFrame was requested, we + # convert. So every entry in this dict is either a 2-d array + # of floats, or a 1-d array of integers (representing + # categories). + value = np.asarray(value) + factor_info_to_values[factor_info] = value + # Handle NAs + values = list(factor_info_to_values.values()) + is_NAs = list(factor_info_to_isNAs.values()) + origins = [factor_info.factor.origin for factor_info in factor_info_to_values] + pandas_index = index_checker.value + num_rows = rows_checker.value + # num_rows is None iff evaluator_to_values (and associated sets like + # 'values') are empty, i.e., we have no actual evaluators involved + # (formulas like "~ 1"). + if return_type == "dataframe" and num_rows is not None: + if pandas_index is None: + pandas_index = np.arange(num_rows) + values.append(pandas_index) + is_NAs.append(np.zeros(len(pandas_index), dtype=bool)) + origins.append(None) + new_values = NA_action.handle_NA(values, is_NAs, origins) + # NA_action may have changed the number of rows. + if new_values: + num_rows = new_values[0].shape[0] + if return_type == "dataframe" and num_rows is not None: + pandas_index = new_values.pop() + factor_info_to_values = dict(zip(factor_info_to_values, new_values)) + # Build factor values into matrices + results = [] + for design_info in design_infos: + results.append(_build_design_matrix(design_info, factor_info_to_values, dtype)) + matrices = [] + for need_reshape, matrix in results: + if need_reshape: + # There is no data-dependence, at all -- a formula like "1 ~ 1". + # In this case the builder just returns a single-row matrix, and + # we have to broadcast it vertically to the appropriate size. If + # we can figure out what that is... + assert matrix.shape[0] == 1 + if num_rows is not None: + matrix = DesignMatrix( + np.repeat(matrix, num_rows, axis=0), matrix.design_info + ) + else: + raise PatsyError( + "No design matrix has any non-trivial factors, " + "the data object is not a DataFrame. " + "I can't tell how many rows the design matrix should " + "have!" + ) + matrices.append(matrix) + if return_type == "dataframe": + assert have_pandas + for i, matrix in enumerate(matrices): + di = matrix.design_info + matrices[i] = pandas.DataFrame( + matrix, columns=di.column_names, index=pandas_index + ) + matrices[i].design_info = di + return matrices + + +# It should be possible to do just the factors -> factor_infos stuff +# alone, since that, well, makes logical sense to do. diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/builtins.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/builtins.py new file mode 100644 index 0000000000000000000000000000000000000000..fb4b319329c84ad768257e6699edf49a2f4a884a --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/builtins.py @@ -0,0 +1,107 @@ +# This file is part of Patsy +# Copyright (C) 2011-2013 Nathaniel Smith +# See file LICENSE.txt for license information. + +# This module sets up the namespace of stuff that is available to formulas by +# default. All formulas are interpreted in an environment that acts as if +# from patsy.builtins import * +# has been executed. (Of course, you can also execute this yourself if you +# want to use these in your regular code for some reason.) + +__all__ = ["I", "Q"] + +from patsy.contrasts import ContrastMatrix, Treatment, Poly, Sum, Helmert, Diff + +__all__ += ["ContrastMatrix", "Treatment", "Poly", "Sum", "Helmert", "Diff"] + +from patsy.categorical import C + +__all__ += ["C"] + +from patsy.state import center, standardize, scale + +__all__ += ["center", "standardize", "scale"] + +from patsy.splines import bs + +__all__ += ["bs"] + +from patsy.mgcv_cubic_splines import cr, cc, te + +__all__ += ["cr", "cc", "te"] + + +def I(x): + """The identity function. Simply returns its input unchanged. + + Since Patsy's formula parser ignores anything inside a function call + syntax, this is useful to 'hide' arithmetic operations from it. For + instance:: + + y ~ x1 + x2 + + has ``x1`` and ``x2`` as two separate predictors. But in:: + + y ~ I(x1 + x2) + + we instead have a single predictor, defined to be the sum of ``x1`` and + ``x2``.""" + return x + + +def test_I(): + assert I(1) == 1 + assert I(None) is None + + +def Q(name): + """A way to 'quote' variable names, especially ones that do not otherwise + meet Python's variable name rules. + + If ``x`` is a variable, ``Q("x")`` returns the value of ``x``. (Note that + ``Q`` takes the *string* ``"x"``, not the value of ``x`` itself.) This + works even if instead of ``x``, we have a variable name that would not + otherwise be legal in Python. + + For example, if you have a column of data named ``weight.in.kg``, then you + can't write:: + + y ~ weight.in.kg + + because Python will try to find a variable named ``weight``, that has an + attribute named ``in``, that has an attribute named ``kg``. (And worse + yet, ``in`` is a reserved word, which makes this example doubly broken.) + Instead, write:: + + y ~ Q("weight.in.kg") + + and all will be well. Note, though, that this requires embedding a Python + string inside your formula, which may require some care with your quote + marks. Some standard options include:: + + my_fit_function("y ~ Q('weight.in.kg')", ...) + my_fit_function('y ~ Q("weight.in.kg")', ...) + my_fit_function("y ~ Q(\\"weight.in.kg\\")", ...) + + Note also that ``Q`` is an ordinary Python function, which means that you + can use it in more complex expressions. For example, this is a legal + formula:: + + y ~ np.sqrt(Q("weight.in.kg")) + """ + from patsy.eval import EvalEnvironment + + env = EvalEnvironment.capture(1) + try: + return env.namespace[name] + except KeyError: + raise NameError("no data named %r found" % (name,)) + + +def test_Q(): + a = 1 + assert Q("a") == 1 + assert Q("Q") is Q + import pytest + + pytest.raises(NameError, Q, "asdfsadfdsad") diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/categorical.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/categorical.py new file mode 100644 index 0000000000000000000000000000000000000000..c88ecd50d485ff9c2fbff700d0853402941e3366 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/categorical.py @@ -0,0 +1,528 @@ +# This file is part of Patsy +# Copyright (C) 2011-2013 Nathaniel Smith +# See file LICENSE.txt for license information. + +__all__ = ["C", "guess_categorical", "CategoricalSniffer", "categorical_to_int"] + +# How we handle categorical data: the big picture +# ----------------------------------------------- +# +# There is no Python/NumPy standard for how to represent categorical data. +# There is no Python/NumPy standard for how to represent missing data. +# +# Together, these facts mean that when we receive some data object, we must be +# able to heuristically infer what levels it has -- and this process must be +# sensitive to the current missing data handling, because maybe 'None' is a +# level and maybe it is missing data. +# +# We don't know how missing data is represented until we get into the actual +# builder code, so anything which runs before this -- e.g., the 'C()' builtin +# -- cannot actually do *anything* meaningful with the data. +# +# Therefore, C() simply takes some data and arguments, and boxes them all up +# together into an object called (appropriately enough) _CategoricalBox. All +# the actual work of handling the various different sorts of categorical data +# (lists, string arrays, bool arrays, pandas.Categorical, etc.) happens inside +# the builder code, and we just extend this so that it also accepts +# _CategoricalBox objects as yet another categorical type. +# +# Originally this file contained a container type (called 'Categorical'), and +# the various sniffing, conversion, etc., functions were written as methods on +# that type. But we had to get rid of that type, so now this file just +# provides a set of plain old functions which are used by patsy.build to +# handle the different stages of categorical data munging. + +import numpy as np + +from patsy import PatsyError +from patsy.util import ( + SortAnythingKey, + safe_scalar_isnan, + iterable, + have_pandas, + have_pandas_categorical, + have_pandas_categorical_dtype, + safe_is_pandas_categorical, + pandas_Categorical_from_codes, + pandas_Categorical_categories, + pandas_Categorical_codes, + safe_issubdtype, + no_pickling, + assert_no_pickling, +) + +if have_pandas: + import pandas + + +# Objects of this type will always be treated as categorical, with the +# specified levels and contrast (if given). +class _CategoricalBox(object): + def __init__(self, data, contrast, levels): + self.data = data + self.contrast = contrast + self.levels = levels + + __getstate__ = no_pickling + + +def C(data, contrast=None, levels=None): + """ + Marks some `data` as being categorical, and specifies how to interpret + it. + + This is used for three reasons: + + * To explicitly mark some data as categorical. For instance, integer data + is by default treated as numerical. If you have data that is stored + using an integer type, but where you want patsy to treat each different + value as a different level of a categorical factor, you can wrap it in a + call to `C` to accomplish this. E.g., compare:: + + dmatrix("a", {"a": [1, 2, 3]}) + dmatrix("C(a)", {"a": [1, 2, 3]}) + + * To explicitly set the levels or override the default level ordering for + categorical data, e.g.:: + + dmatrix("C(a, levels=["a2", "a1"])", balanced(a=2)) + * To override the default coding scheme for categorical data. The + `contrast` argument can be any of: + + * A :class:`ContrastMatrix` object + * A simple 2d ndarray (which is treated the same as a ContrastMatrix + object except that you can't specify column names) + * An object with methods called `code_with_intercept` and + `code_without_intercept`, like the built-in contrasts + (:class:`Treatment`, :class:`Diff`, :class:`Poly`, etc.). See + :ref:`categorical-coding` for more details. + * A callable that returns one of the above. + """ + if isinstance(data, _CategoricalBox): + if contrast is None: + contrast = data.contrast + if levels is None: + levels = data.levels + data = data.data + return _CategoricalBox(data, contrast, levels) + + +def test_C(): + c1 = C("asdf") + assert isinstance(c1, _CategoricalBox) + assert c1.data == "asdf" + assert c1.levels is None + assert c1.contrast is None + c2 = C("DATA", "CONTRAST", "LEVELS") + assert c2.data == "DATA" + assert c2.contrast == "CONTRAST" + assert c2.levels == "LEVELS" + c3 = C(c2, levels="NEW LEVELS") + assert c3.data == "DATA" + assert c3.contrast == "CONTRAST" + assert c3.levels == "NEW LEVELS" + c4 = C(c2, "NEW CONTRAST") + assert c4.data == "DATA" + assert c4.contrast == "NEW CONTRAST" + assert c4.levels == "LEVELS" + + assert_no_pickling(c4) + + +def guess_categorical(data): + if safe_is_pandas_categorical(data): + return True + if isinstance(data, _CategoricalBox): + return True + data = np.asarray(data) + if safe_issubdtype(data.dtype, np.number): + return False + return True + + +def test_guess_categorical(): + if have_pandas_categorical: + c = pandas.Categorical([1, 2, 3]) + assert guess_categorical(c) + if have_pandas_categorical_dtype: + assert guess_categorical(pandas.Series(c)) + assert guess_categorical(C([1, 2, 3])) + assert guess_categorical([True, False]) + assert guess_categorical(["a", "b"]) + assert guess_categorical(["a", "b", np.nan]) + assert guess_categorical(["a", "b", None]) + assert not guess_categorical([1, 2, 3]) + assert not guess_categorical([1, 2, 3, np.nan]) + assert not guess_categorical([1.0, 2.0, 3.0]) + assert not guess_categorical([1.0, 2.0, 3.0, np.nan]) + + +def _categorical_shape_fix(data): + # helper function + # data should not be a _CategoricalBox or pandas Categorical or anything + # -- it should be an actual iterable of data, but which might have the + # wrong shape. + if hasattr(data, "ndim") and data.ndim > 1: + raise PatsyError("categorical data cannot be >1-dimensional") + # coerce scalars into 1d, which is consistent with what we do for numeric + # factors. (See statsmodels/statsmodels#1881) + if not iterable(data) or isinstance(data, (str, bytes)): + data = [data] + return data + + +class CategoricalSniffer(object): + def __init__(self, NA_action, origin=None): + self._NA_action = NA_action + self._origin = origin + self._contrast = None + self._levels = None + self._level_set = set() + + def levels_contrast(self): + if self._levels is None: + levels = list(self._level_set) + levels.sort(key=SortAnythingKey) + self._levels = levels + return tuple(self._levels), self._contrast + + def sniff(self, data): + if hasattr(data, "contrast"): + self._contrast = data.contrast + # returns a bool: are we confident that we found all the levels? + if isinstance(data, _CategoricalBox): + if data.levels is not None: + self._levels = tuple(data.levels) + return True + else: + # unbox and fall through + data = data.data + if safe_is_pandas_categorical(data): + # pandas.Categorical has its own NA detection, so don't try to + # second-guess it. + self._levels = tuple(pandas_Categorical_categories(data)) + return True + # fastpath to avoid doing an item-by-item iteration over boolean + # arrays, as requested by #44 + if hasattr(data, "dtype") and safe_issubdtype(data.dtype, np.bool_): + self._level_set = set([True, False]) + return True + + data = _categorical_shape_fix(data) + + for value in data: + if self._NA_action.is_categorical_NA(value): + continue + if value is True or value is False: + self._level_set.update([True, False]) + else: + try: + self._level_set.add(value) + except TypeError: + raise PatsyError( + "Error interpreting categorical data: " + "all items must be hashable", + self._origin, + ) + # If everything we've seen is boolean, assume that everything else + # would be too. Otherwise we need to keep looking. + return self._level_set == set([True, False]) + + __getstate__ = no_pickling + + +def test_CategoricalSniffer(): + from patsy.missing import NAAction + + def t(NA_types, datas, exp_finish_fast, exp_levels, exp_contrast=None): + sniffer = CategoricalSniffer(NAAction(NA_types=NA_types)) + for data in datas: + done = sniffer.sniff(data) + if done: + assert exp_finish_fast + break + else: + assert not exp_finish_fast + assert sniffer.levels_contrast() == (exp_levels, exp_contrast) + + if have_pandas_categorical: + # We make sure to test with both boxed and unboxed pandas objects, + # because we used to have a bug where boxed pandas objects would be + # treated as categorical, but their levels would be lost... + preps = [lambda x: x, C] + if have_pandas_categorical_dtype: + preps += [pandas.Series, lambda x: C(pandas.Series(x))] + for prep in preps: + t([], [prep(pandas.Categorical([1, 2, None]))], True, (1, 2)) + # check order preservation + t( + [], + [prep(pandas_Categorical_from_codes([1, 0], ["a", "b"]))], + True, + ("a", "b"), + ) + t( + [], + [prep(pandas_Categorical_from_codes([1, 0], ["b", "a"]))], + True, + ("b", "a"), + ) + # check that if someone sticks a .contrast field onto our object + obj = prep(pandas.Categorical(["a", "b"])) + obj.contrast = "CONTRAST" + t([], [obj], True, ("a", "b"), "CONTRAST") + + t([], [C([1, 2]), C([3, 2])], False, (1, 2, 3)) + # check order preservation + t([], [C([1, 2], levels=[1, 2, 3]), C([4, 2])], True, (1, 2, 3)) + t([], [C([1, 2], levels=[3, 2, 1]), C([4, 2])], True, (3, 2, 1)) + + # do some actual sniffing with NAs in + t(["None", "NaN"], [C([1, np.nan]), C([10, None])], False, (1, 10)) + # But 'None' can be a type if we don't make it represent NA: + sniffer = CategoricalSniffer(NAAction(NA_types=["NaN"])) + sniffer.sniff(C([1, np.nan, None])) + # The level order here is different on py2 and py3 :-( Because there's no + # consistent way to sort mixed-type values on both py2 and py3. Honestly + # people probably shouldn't use this, but I don't know how to give a + # sensible error. + levels, _ = sniffer.levels_contrast() + assert set(levels) == set([None, 1]) + + # bool special cases + t(["None", "NaN"], [C([True, np.nan, None])], True, (False, True)) + t([], [C([10, 20]), C([False]), C([30, 40])], False, (False, True, 10, 20, 30, 40)) + # exercise the fast-path + t([], [np.asarray([True, False]), ["foo"]], True, (False, True)) + + # check tuples too + t( + ["None", "NaN"], + [C([("b", 2), None, ("a", 1), np.nan, ("c", None)])], + False, + (("a", 1), ("b", 2), ("c", None)), + ) + + # contrasts + t([], [C([10, 20], contrast="FOO")], False, (10, 20), "FOO") + + # no box + t([], [[10, 30], [20]], False, (10, 20, 30)) + t([], [["b", "a"], ["a"]], False, ("a", "b")) + + # 0d + t([], ["b"], False, ("b",)) + + import pytest + + # unhashable level error: + sniffer = CategoricalSniffer(NAAction()) + pytest.raises(PatsyError, sniffer.sniff, [{}]) + + # >1d is illegal + pytest.raises(PatsyError, sniffer.sniff, np.asarray([["b"]])) + + +# returns either a 1d ndarray or a pandas.Series +def categorical_to_int(data, levels, NA_action, origin=None): + assert isinstance(levels, tuple) + # In this function, missing values are always mapped to -1 + + if safe_is_pandas_categorical(data): + data_levels_tuple = tuple(pandas_Categorical_categories(data)) + if not data_levels_tuple == levels: + raise PatsyError( + "mismatching levels: expected %r, got %r" % (levels, data_levels_tuple), + origin, + ) + # pandas.Categorical also uses -1 to indicate NA, and we don't try to + # second-guess its NA detection, so we can just pass it back. + return pandas_Categorical_codes(data) + + if isinstance(data, _CategoricalBox): + if data.levels is not None and tuple(data.levels) != levels: + raise PatsyError( + "mismatching levels: expected %r, got %r" + % (levels, tuple(data.levels)), + origin, + ) + data = data.data + + data = _categorical_shape_fix(data) + + try: + level_to_int = dict(zip(levels, range(len(levels)))) + except TypeError: + raise PatsyError( + "Error interpreting categorical data: all items must be hashable", origin + ) + + # fastpath to avoid doing an item-by-item iteration over boolean arrays, + # as requested by #44 + if hasattr(data, "dtype") and safe_issubdtype(data.dtype, np.bool_): + if level_to_int[False] == 0 and level_to_int[True] == 1: + return data.astype(np.int_) + out = np.empty(len(data), dtype=int) + for i, value in enumerate(data): + if NA_action.is_categorical_NA(value): + out[i] = -1 + else: + try: + out[i] = level_to_int[value] + except KeyError: + SHOW_LEVELS = 4 + level_strs = [] + if len(levels) <= SHOW_LEVELS: + level_strs += [repr(level) for level in levels] + else: + level_strs += [repr(level) for level in levels[: SHOW_LEVELS // 2]] + level_strs.append("...") + level_strs += [repr(level) for level in levels[-SHOW_LEVELS // 2 :]] + level_str = "[%s]" % (", ".join(level_strs)) + raise PatsyError( + "Error converting data to categorical: " + "observation with value %r does not match " + "any of the expected levels (expected: %s)" % (value, level_str), + origin, + ) + except TypeError: + raise PatsyError( + "Error converting data to categorical: " + "encountered unhashable value %r" % (value,), + origin, + ) + if have_pandas and isinstance(data, pandas.Series): + out = pandas.Series(out, index=data.index) + return out + + +def test_categorical_to_int(): + import pytest + from patsy.missing import NAAction + + if have_pandas: + s = pandas.Series(["a", "b", "c"], index=[10, 20, 30]) + c_pandas = categorical_to_int(s, ("a", "b", "c"), NAAction()) + assert np.all(c_pandas == [0, 1, 2]) + assert np.all(c_pandas.index == [10, 20, 30]) + # Input must be 1-dimensional + pytest.raises( + PatsyError, + categorical_to_int, + pandas.DataFrame({10: s}), + ("a", "b", "c"), + NAAction(), + ) + if have_pandas_categorical: + constructors = [pandas_Categorical_from_codes] + if have_pandas_categorical_dtype: + + def Series_from_codes(codes, categories): + c = pandas_Categorical_from_codes(codes, categories) + return pandas.Series(c) + + constructors.append(Series_from_codes) + for con in constructors: + cat = con([1, 0, -1], ("a", "b")) + conv = categorical_to_int(cat, ("a", "b"), NAAction()) + assert np.all(conv == [1, 0, -1]) + # Trust pandas NA marking + cat2 = con([1, 0, -1], ("a", "None")) + conv2 = categorical_to_int(cat, ("a", "b"), NAAction(NA_types=["None"])) + assert np.all(conv2 == [1, 0, -1]) + # But levels must match + pytest.raises( + PatsyError, + categorical_to_int, + con([1, 0], ("a", "b")), + ("a", "c"), + NAAction(), + ) + pytest.raises( + PatsyError, + categorical_to_int, + con([1, 0], ("a", "b")), + ("b", "a"), + NAAction(), + ) + + def t(data, levels, expected, NA_action=NAAction()): + got = categorical_to_int(data, levels, NA_action) + assert np.array_equal(got, expected) + + t(["a", "b", "a"], ("a", "b"), [0, 1, 0]) + t(np.asarray(["a", "b", "a"]), ("a", "b"), [0, 1, 0]) + t(np.asarray(["a", "b", "a"], dtype=object), ("a", "b"), [0, 1, 0]) + t([0, 1, 2], (1, 2, 0), [2, 0, 1]) + t(np.asarray([0, 1, 2]), (1, 2, 0), [2, 0, 1]) + t(np.asarray([0, 1, 2], dtype=float), (1, 2, 0), [2, 0, 1]) + t(np.asarray([0, 1, 2], dtype=object), (1, 2, 0), [2, 0, 1]) + t(["a", "b", "a"], ("a", "d", "z", "b"), [0, 3, 0]) + t([("a", 1), ("b", 0), ("a", 1)], (("a", 1), ("b", 0)), [0, 1, 0]) + + pytest.raises( + PatsyError, categorical_to_int, ["a", "b", "a"], ("a", "c"), NAAction() + ) + + t(C(["a", "b", "a"]), ("a", "b"), [0, 1, 0]) + t(C(["a", "b", "a"]), ("b", "a"), [1, 0, 1]) + t(C(["a", "b", "a"], levels=["b", "a"]), ("b", "a"), [1, 0, 1]) + # Mismatch between C() levels and expected levels + pytest.raises( + PatsyError, + categorical_to_int, + C(["a", "b", "a"], levels=["a", "b"]), + ("b", "a"), + NAAction(), + ) + + # ndim == 0 is okay + t("a", ("a", "b"), [0]) + t("b", ("a", "b"), [1]) + t(True, (False, True), [1]) + + # ndim == 2 is disallowed + pytest.raises( + PatsyError, + categorical_to_int, + np.asarray([["a", "b"], ["b", "a"]]), + ("a", "b"), + NAAction(), + ) + + # levels must be hashable + pytest.raises( + PatsyError, categorical_to_int, ["a", "b"], ("a", "b", {}), NAAction() + ) + pytest.raises( + PatsyError, categorical_to_int, ["a", "b", {}], ("a", "b"), NAAction() + ) + + t( + ["b", None, np.nan, "a"], + ("a", "b"), + [1, -1, -1, 0], + NAAction(NA_types=["None", "NaN"]), + ) + t( + ["b", None, np.nan, "a"], + ("a", "b", None), + [1, -1, -1, 0], + NAAction(NA_types=["None", "NaN"]), + ) + t( + ["b", None, np.nan, "a"], + ("a", "b", None), + [1, 2, -1, 0], + NAAction(NA_types=["NaN"]), + ) + + # Smoke test for the branch that formats the ellipsized list of levels in + # the error message: + pytest.raises( + PatsyError, + categorical_to_int, + ["a", "b", "q"], + ("a", "b", "c", "d", "e", "f", "g", "h"), + NAAction(), + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/compat.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/compat.py new file mode 100644 index 0000000000000000000000000000000000000000..5d56d228d7b48282f662d4c1e9ed2052aaf135da --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/compat.py @@ -0,0 +1,43 @@ +# This file is part of Patsy +# Copyright (C) 2012 Nathaniel Smith +# See file LICENSE.txt for license information. + +# This file contains compatibility code for supporting old versions of Python +# and numpy. (If we can concentrate it here, hopefully it'll make it easier to +# get rid of weird hacks once we drop support for old versions). + +##### Numpy + +import os + +# To force use of the compat code, set this env var to a non-empty value: +optional_dep_ok = not os.environ.get("PATSY_AVOID_OPTIONAL_DEPENDENCIES") + +##### Python standard library + +# The Python license requires that all derivative works contain a "brief +# summary of the changes made to Python". Both for license compliance, and for +# our own sanity, therefore, please add a note at the top of any snippets you +# add here explaining their provenance, any changes made, and what versions of +# Python require them: + +# OrderedDict is only available in Python 2.7+. compat_ordereddict.py has +# comments at the top. +import collections + +if optional_dep_ok and hasattr(collections, "OrderedDict"): + from collections import OrderedDict +else: + from patsy.compat_ordereddict import OrderedDict + +# 'raise from' available in Python 3+ +import sys +from patsy import PatsyError + + +def call_and_wrap_exc(msg, origin, f, *args, **kwargs): + try: + return f(*args, **kwargs) + except Exception as e: + new_exc = PatsyError("%s: %s: %s" % (msg, e.__class__.__name__, e), origin) + raise new_exc from e diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/compat_ordereddict.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/compat_ordereddict.py new file mode 100644 index 0000000000000000000000000000000000000000..644a6626160956a0fe610d9e6064193c84202e52 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/compat_ordereddict.py @@ -0,0 +1,270 @@ +# Backport of OrderedDict() class that runs on Python 2.4, 2.5, 2.6, 2.7 and pypy. +# Passes Python2.7's test suite and incorporates all the latest updates. + +# Author: Raymond Hettinger +# License: MIT License +# http://code.activestate.com/recipes/576693/ revision 9, downloaded 2012-03-28 + +try: + from thread import get_ident as _get_ident +except ImportError: + # Hacked by njs -- I don't have dummy_thread and py3 doesn't have thread, + # so the import fails when nosetests3 tries to load this file. + # from dummy_thread import get_ident as _get_ident + def _get_ident(): + return "" + + +try: + from _abcoll import KeysView, ValuesView, ItemsView +except ImportError: + pass + + +class OrderedDict(dict): # pragma: no cover + "Dictionary that remembers insertion order" + + # An inherited dict maps keys to values. + # The inherited dict provides __getitem__, __len__, __contains__, and get. + # The remaining methods are order-aware. + # Big-O running times for all methods are the same as for regular dictionaries. + + # The internal self.__map dictionary maps keys to links in a doubly linked list. + # The circular doubly linked list starts and ends with a sentinel element. + # The sentinel element never gets deleted (this simplifies the algorithm). + # Each link is stored as a list of length three: [PREV, NEXT, KEY]. + + def __init__(self, *args, **kwds): + """Initialize an ordered dictionary. Signature is the same as for + regular dictionaries, but keyword arguments are not recommended + because their insertion order is arbitrary. + + """ + if len(args) > 1: + raise TypeError("expected at most 1 arguments, got %d" % len(args)) + try: + self.__root + except AttributeError: + self.__root = root = [] # sentinel node + root[:] = [root, root, None] + self.__map = {} + self.__update(*args, **kwds) + + def __setitem__(self, key, value, dict_setitem=dict.__setitem__): + "od.__setitem__(i, y) <==> od[i]=y" + # Setting a new item creates a new link which goes at the end of the linked + # list, and the inherited dictionary is updated with the new key/value pair. + if key not in self: + root = self.__root + last = root[0] + last[1] = root[0] = self.__map[key] = [last, root, key] + dict_setitem(self, key, value) + + def __delitem__(self, key, dict_delitem=dict.__delitem__): + "od.__delitem__(y) <==> del od[y]" + # Deleting an existing item uses self.__map to find the link which is + # then removed by updating the links in the predecessor and successor nodes. + dict_delitem(self, key) + link_prev, link_next, key = self.__map.pop(key) + link_prev[1] = link_next + link_next[0] = link_prev + + def __iter__(self): + "od.__iter__() <==> iter(od)" + root = self.__root + curr = root[1] + while curr is not root: + yield curr[2] + curr = curr[1] + + def __reversed__(self): + "od.__reversed__() <==> reversed(od)" + root = self.__root + curr = root[0] + while curr is not root: + yield curr[2] + curr = curr[0] + + def clear(self): + "od.clear() -> None. Remove all items from od." + try: + for node in self.__map.itervalues(): + del node[:] + root = self.__root + root[:] = [root, root, None] + self.__map.clear() + except AttributeError: + pass + dict.clear(self) + + def popitem(self, last=True): + """od.popitem() -> (k, v), return and remove a (key, value) pair. + Pairs are returned in LIFO order if last is true or FIFO order if false. + + """ + if not self: + raise KeyError("dictionary is empty") + root = self.__root + if last: + link = root[0] + link_prev = link[0] + link_prev[1] = root + root[0] = link_prev + else: + link = root[1] + link_next = link[1] + root[1] = link_next + link_next[0] = root + key = link[2] + del self.__map[key] + value = dict.pop(self, key) + return key, value + + # -- the following methods do not depend on the internal structure -- + + def keys(self): + "od.keys() -> list of keys in od" + return list(self) + + def values(self): + "od.values() -> list of values in od" + return [self[key] for key in self] + + def items(self): + "od.items() -> list of (key, value) pairs in od" + return [(key, self[key]) for key in self] + + def iterkeys(self): + "od.iterkeys() -> an iterator over the keys in od" + return iter(self) + + def itervalues(self): + "od.itervalues -> an iterator over the values in od" + for k in self: + yield self[k] + + def iteritems(self): + "od.iteritems -> an iterator over the (key, value) items in od" + for k in self: + yield (k, self[k]) + + def update(*args, **kwds): + """od.update(E, **F) -> None. Update od from dict/iterable E and F. + + If E is a dict instance, does: for k in E: od[k] = E[k] + If E has a .keys() method, does: for k in E.keys(): od[k] = E[k] + Or if E is an iterable of items, does: for k, v in E: od[k] = v + In either case, this is followed by: for k, v in F.items(): od[k] = v + + """ + if len(args) > 2: + raise TypeError( + "update() takes at most 2 positional " + "arguments (%d given)" % (len(args),) + ) + elif not args: + raise TypeError("update() takes at least 1 argument (0 given)") + self = args[0] + # Make progressively weaker assumptions about "other" + other = () + if len(args) == 2: + other = args[1] + if isinstance(other, dict): + for key in other: + self[key] = other[key] + elif hasattr(other, "keys"): + for key in other.keys(): + self[key] = other[key] + else: + for key, value in other: + self[key] = value + for key, value in kwds.items(): + self[key] = value + + __update = update # let subclasses override update without breaking __init__ + + __marker = object() + + def pop(self, key, default=__marker): + """od.pop(k[,d]) -> v, remove specified key and return the corresponding value. + If key is not found, d is returned if given, otherwise KeyError is raised. + + """ + if key in self: + result = self[key] + del self[key] + return result + if default is self.__marker: + raise KeyError(key) + return default + + def setdefault(self, key, default=None): + "od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od" + if key in self: + return self[key] + self[key] = default + return default + + def __repr__(self, _repr_running={}): + "od.__repr__() <==> repr(od)" + call_key = id(self), _get_ident() + if call_key in _repr_running: + return "..." + _repr_running[call_key] = 1 + try: + if not self: + return "%s()" % (self.__class__.__name__,) + return "%s(%r)" % (self.__class__.__name__, self.items()) + finally: + del _repr_running[call_key] + + def __reduce__(self): + "Return state information for pickling" + items = [[k, self[k]] for k in self] + inst_dict = vars(self).copy() + for k in vars(OrderedDict()): + inst_dict.pop(k, None) + if inst_dict: + return (self.__class__, (items,), inst_dict) + return self.__class__, (items,) + + def copy(self): + "od.copy() -> a shallow copy of od" + return self.__class__(self) + + @classmethod + def fromkeys(cls, iterable, value=None): + """OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S + and values equal to v (which defaults to None). + + """ + d = cls() + for key in iterable: + d[key] = value + return d + + def __eq__(self, other): + """od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive + while comparison to a regular mapping is order-insensitive. + + """ + if isinstance(other, OrderedDict): + return len(self) == len(other) and self.items() == other.items() + return dict.__eq__(self, other) + + def __ne__(self, other): + return not self == other + + # -- the following methods are only used in Python 2.7 -- + + def viewkeys(self): + "od.viewkeys() -> a set-like object providing a view on od's keys" + return KeysView(self) + + def viewvalues(self): + "od.viewvalues() -> an object providing a view on od's values" + return ValuesView(self) + + def viewitems(self): + "od.viewitems() -> a set-like object providing a view on od's items" + return ItemsView(self) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/constraint.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/constraint.py new file mode 100644 index 0000000000000000000000000000000000000000..6c04414421d5f8552b3bbcfe93513ad549279eac --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/constraint.py @@ -0,0 +1,561 @@ +# This file is part of Patsy +# Copyright (C) 2011-2012 Nathaniel Smith +# See file LICENSE.txt for license information. + +# Interpreting linear constraints like "2*x1 + x2 = 0" + +# These are made available in the patsy.* namespace +__all__ = ["LinearConstraint"] + +import re + +try: + from collections.abc import Mapping +except ImportError: + from collections import Mapping +import numpy as np +from patsy import PatsyError +from patsy.origin import Origin +from patsy.util import ( + atleast_2d_column_default, + repr_pretty_delegate, + repr_pretty_impl, + no_pickling, + assert_no_pickling, +) +from patsy.infix_parser import Token, Operator, infix_parse +from patsy.parse_formula import _parsing_error_test + + +class LinearConstraint(object): + """A linear constraint in matrix form. + + This object represents a linear constraint of the form `Ax = b`. + + Usually you won't be constructing these by hand, but instead get them as + the return value from :meth:`DesignInfo.linear_constraint`. + + .. attribute:: coefs + + A 2-dimensional ndarray with float dtype, representing `A`. + + .. attribute:: constants + + A 2-dimensional single-column ndarray with float dtype, representing + `b`. + + .. attribute:: variable_names + + A list of strings giving the names of the variables being + constrained. (Used only for consistency checking.) + """ + + def __init__(self, variable_names, coefs, constants=None): + self.variable_names = list(variable_names) + self.coefs = np.atleast_2d(np.asarray(coefs, dtype=float)) + if constants is None: + constants = np.zeros(self.coefs.shape[0], dtype=float) + constants = np.asarray(constants, dtype=float) + self.constants = atleast_2d_column_default(constants) + if self.constants.ndim != 2 or self.constants.shape[1] != 1: + raise ValueError("constants is not (convertible to) a column matrix") + if self.coefs.ndim != 2 or self.coefs.shape[1] != len(variable_names): + raise ValueError("wrong shape for coefs") + if self.coefs.shape[0] == 0: + raise ValueError("must have at least one row in constraint matrix") + if self.coefs.shape[0] != self.constants.shape[0]: + raise ValueError("shape mismatch between coefs and constants") + + __repr__ = repr_pretty_delegate + + def _repr_pretty_(self, p, cycle): + assert not cycle + return repr_pretty_impl( + p, self, [self.variable_names, self.coefs, self.constants] + ) + + __getstate__ = no_pickling + + @classmethod + def combine(cls, constraints): + """Create a new LinearConstraint by ANDing together several existing + LinearConstraints. + + :arg constraints: An iterable of LinearConstraint objects. Their + :attr:`variable_names` attributes must all match. + :returns: A new LinearConstraint object. + """ + if not constraints: + raise ValueError("no constraints specified") + variable_names = constraints[0].variable_names + for constraint in constraints: + if constraint.variable_names != variable_names: + raise ValueError("variable names don't match") + coefs = np.vstack([c.coefs for c in constraints]) + constants = np.vstack([c.constants for c in constraints]) + return cls(variable_names, coefs, constants) + + +def test_LinearConstraint(): + try: + from numpy.testing import assert_equal + except ImportError: + from numpy.testing.utils import assert_equal + lc = LinearConstraint(["foo", "bar"], [1, 1]) + assert lc.variable_names == ["foo", "bar"] + assert_equal(lc.coefs, [[1, 1]]) + assert_equal(lc.constants, [[0]]) + + lc = LinearConstraint(["foo", "bar"], [[1, 1], [2, 3]], [10, 20]) + assert_equal(lc.coefs, [[1, 1], [2, 3]]) + assert_equal(lc.constants, [[10], [20]]) + + assert lc.coefs.dtype == np.dtype(float) + assert lc.constants.dtype == np.dtype(float) + + # statsmodels wants to be able to create degenerate constraints like this, + # see: + # https://github.com/pydata/patsy/issues/89 + # We used to forbid it, but I guess it's harmless, so why not. + lc = LinearConstraint(["a"], [[0]]) + assert_equal(lc.coefs, [[0]]) + + import pytest + + pytest.raises(ValueError, LinearConstraint, ["a"], [[1, 2]]) + pytest.raises(ValueError, LinearConstraint, ["a"], [[[1]]]) + pytest.raises(ValueError, LinearConstraint, ["a"], [[1, 2]], [3, 4]) + pytest.raises(ValueError, LinearConstraint, ["a", "b"], [[1, 2]], [3, 4]) + pytest.raises(ValueError, LinearConstraint, ["a"], [[1]], [[]]) + pytest.raises(ValueError, LinearConstraint, ["a", "b"], []) + pytest.raises(ValueError, LinearConstraint, ["a", "b"], np.zeros((0, 2))) + + assert_no_pickling(lc) + + +def test_LinearConstraint_combine(): + comb = LinearConstraint.combine( + [ + LinearConstraint(["a", "b"], [1, 0]), + LinearConstraint(["a", "b"], [0, 1], [1]), + ] + ) + assert comb.variable_names == ["a", "b"] + try: + from numpy.testing import assert_equal + except ImportError: + from numpy.testing.utils import assert_equal + assert_equal(comb.coefs, [[1, 0], [0, 1]]) + assert_equal(comb.constants, [[0], [1]]) + + import pytest + + pytest.raises(ValueError, LinearConstraint.combine, []) + pytest.raises( + ValueError, + LinearConstraint.combine, + [LinearConstraint(["a"], [1]), LinearConstraint(["b"], [1])], + ) + + +_ops = [ + Operator(",", 2, -100), + Operator("=", 2, 0), + Operator("+", 1, 100), + Operator("-", 1, 100), + Operator("+", 2, 100), + Operator("-", 2, 100), + Operator("*", 2, 200), + Operator("/", 2, 200), +] + +_atomic = ["NUMBER", "VARIABLE"] + + +def _token_maker(type, string): + def make_token(scanner, token_string): + if type == "__OP__": + actual_type = token_string + else: + actual_type = type + return Token(actual_type, Origin(string, *scanner.match.span()), token_string) + + return make_token + + +def _tokenize_constraint(string, variable_names): + lparen_re = r"\(" + rparen_re = r"\)" + op_re = "|".join([re.escape(op.token_type) for op in _ops]) + num_re = r"[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?" + whitespace_re = r"\s+" + + # Prefer long matches: + variable_names = sorted(variable_names, key=len, reverse=True) + variable_re = "|".join([re.escape(n) for n in variable_names]) + + lexicon = [ + (lparen_re, _token_maker(Token.LPAREN, string)), + (rparen_re, _token_maker(Token.RPAREN, string)), + (op_re, _token_maker("__OP__", string)), + (variable_re, _token_maker("VARIABLE", string)), + (num_re, _token_maker("NUMBER", string)), + (whitespace_re, None), + ] + + scanner = re.Scanner(lexicon) + tokens, leftover = scanner.scan(string) + if leftover: + offset = len(string) - len(leftover) + raise PatsyError( + "unrecognized token in constraint", Origin(string, offset, offset + 1) + ) + + return tokens + + +def test__tokenize_constraint(): + code = "2 * (a + b) = q" + tokens = _tokenize_constraint(code, ["a", "b", "q"]) + expecteds = [ + ("NUMBER", 0, 1, "2"), + ("*", 2, 3, "*"), + (Token.LPAREN, 4, 5, "("), + ("VARIABLE", 5, 6, "a"), + ("+", 7, 8, "+"), + ("VARIABLE", 9, 10, "b"), + (Token.RPAREN, 10, 11, ")"), + ("=", 12, 13, "="), + ("VARIABLE", 14, 15, "q"), + ] + for got, expected in zip(tokens, expecteds): + assert isinstance(got, Token) + assert got.type == expected[0] + assert got.origin == Origin(code, expected[1], expected[2]) + assert got.extra == expected[3] + + import pytest + + pytest.raises(PatsyError, _tokenize_constraint, "1 + @b", ["b"]) + # Shouldn't raise an error: + _tokenize_constraint("1 + @b", ["@b"]) + + # Check we aren't confused by names which are proper prefixes of other + # names: + for names in (["a", "aa"], ["aa", "a"]): + tokens = _tokenize_constraint("a aa a", names) + assert len(tokens) == 3 + assert [t.extra for t in tokens] == ["a", "aa", "a"] + + # Check that embedding ops and numbers inside a variable name works + tokens = _tokenize_constraint("2 * a[1,1],", ["a[1,1]"]) + assert len(tokens) == 4 + assert [t.type for t in tokens] == ["NUMBER", "*", "VARIABLE", ","] + assert [t.extra for t in tokens] == ["2", "*", "a[1,1]", ","] + + +def parse_constraint(string, variable_names): + return infix_parse(_tokenize_constraint(string, variable_names), _ops, _atomic) + + +class _EvalConstraint(object): + def __init__(self, variable_names): + self._variable_names = variable_names + self._N = len(variable_names) + + self._dispatch = { + ("VARIABLE", 0): self._eval_variable, + ("NUMBER", 0): self._eval_number, + ("+", 1): self._eval_unary_plus, + ("-", 1): self._eval_unary_minus, + ("+", 2): self._eval_binary_plus, + ("-", 2): self._eval_binary_minus, + ("*", 2): self._eval_binary_multiply, + ("/", 2): self._eval_binary_div, + ("=", 2): self._eval_binary_eq, + (",", 2): self._eval_binary_comma, + } + + # General scheme: there are 2 types we deal with: + # - linear combinations ("lincomb"s) of variables and constants, + # represented as ndarrays with size N+1 + # The last entry is the constant, so [10, 20, 30] means 10x + 20y + + # 30. + # - LinearConstraint objects + + def is_constant(self, coefs): + return np.all(coefs[: self._N] == 0) + + def _eval_variable(self, tree): + var = tree.token.extra + coefs = np.zeros((self._N + 1,), dtype=float) + coefs[self._variable_names.index(var)] = 1 + return coefs + + def _eval_number(self, tree): + coefs = np.zeros((self._N + 1,), dtype=float) + coefs[-1] = float(tree.token.extra) + return coefs + + def _eval_unary_plus(self, tree): + return self.eval(tree.args[0]) + + def _eval_unary_minus(self, tree): + return -1 * self.eval(tree.args[0]) + + def _eval_binary_plus(self, tree): + return self.eval(tree.args[0]) + self.eval(tree.args[1]) + + def _eval_binary_minus(self, tree): + return self.eval(tree.args[0]) - self.eval(tree.args[1]) + + def _eval_binary_div(self, tree): + left = self.eval(tree.args[0]) + right = self.eval(tree.args[1]) + if not self.is_constant(right): + raise PatsyError( + "Can't divide by a variable in a linear constraint", tree.args[1] + ) + return left / right[-1] + + def _eval_binary_multiply(self, tree): + left = self.eval(tree.args[0]) + right = self.eval(tree.args[1]) + if self.is_constant(left): + return left[-1] * right + elif self.is_constant(right): + return left * right[-1] + else: + raise PatsyError( + "Can't multiply one variable by another in a linear constraint", tree + ) + + def _eval_binary_eq(self, tree): + # Handle "a1 = a2 = a3", which is parsed as "(a1 = a2) = a3" + args = list(tree.args) + constraints = [] + for i, arg in enumerate(args): + if arg.type == "=": + constraints.append(self.eval(arg, constraint=True)) + # make our left argument be their right argument, or + # vice-versa + args[i] = arg.args[1 - i] + left = self.eval(args[0]) + right = self.eval(args[1]) + coefs = left[: self._N] - right[: self._N] + if np.all(coefs == 0): + raise PatsyError("no variables appear in constraint", tree) + constant = -left[-1] + right[-1] + constraint = LinearConstraint(self._variable_names, coefs, constant) + constraints.append(constraint) + return LinearConstraint.combine(constraints) + + def _eval_binary_comma(self, tree): + left = self.eval(tree.args[0], constraint=True) + right = self.eval(tree.args[1], constraint=True) + return LinearConstraint.combine([left, right]) + + def eval(self, tree, constraint=False): + key = (tree.type, len(tree.args)) + assert key in self._dispatch + val = self._dispatch[key](tree) + if constraint: + # Force it to be a constraint + if isinstance(val, LinearConstraint): + return val + else: + assert val.size == self._N + 1 + if np.all(val[: self._N] == 0): + raise PatsyError("term is constant, with no variables", tree) + return LinearConstraint(self._variable_names, val[: self._N], -val[-1]) + else: + # Force it to *not* be a constraint + if isinstance(val, LinearConstraint): + raise PatsyError("unexpected constraint object", tree) + return val + + +def linear_constraint(constraint_like, variable_names): + """This is the internal interface implementing + DesignInfo.linear_constraint, see there for docs.""" + if isinstance(constraint_like, LinearConstraint): + if constraint_like.variable_names != variable_names: + raise ValueError( + "LinearConstraint has wrong variable_names " + "(got %r, expected %r)" + % (constraint_like.variable_names, variable_names) + ) + return constraint_like + + if isinstance(constraint_like, Mapping): + # Simple conjunction-of-equality constraints can be specified as + # dicts. {"x": 1, "y": 2} -> tests x = 1 and y = 2. Keys can be + # either variable names, or variable indices. + coefs = np.zeros((len(constraint_like), len(variable_names)), dtype=float) + constants = np.zeros(len(constraint_like)) + used = set() + for i, (name, value) in enumerate(constraint_like.items()): + if name in variable_names: + idx = variable_names.index(name) + elif isinstance(name, int): + idx = name + else: + raise ValueError("unrecognized variable name/index %r" % (name,)) + if idx in used: + raise ValueError("duplicated constraint on %r" % (variable_names[idx],)) + used.add(idx) + coefs[i, idx] = 1 + constants[i] = value + return LinearConstraint(variable_names, coefs, constants) + + if isinstance(constraint_like, str): + constraint_like = [constraint_like] + # fall-through + + if ( + isinstance(constraint_like, list) + and constraint_like + and isinstance(constraint_like[0], str) + ): + constraints = [] + for code in constraint_like: + if not isinstance(code, str): + raise ValueError("expected a string, not %r" % (code,)) + tree = parse_constraint(code, variable_names) + evaluator = _EvalConstraint(variable_names) + constraints.append(evaluator.eval(tree, constraint=True)) + return LinearConstraint.combine(constraints) + + if isinstance(constraint_like, tuple): + if len(constraint_like) != 2: + raise ValueError("constraint tuple must have length 2") + coef, constants = constraint_like + return LinearConstraint(variable_names, coef, constants) + + # assume a raw ndarray + coefs = np.asarray(constraint_like, dtype=float) + return LinearConstraint(variable_names, coefs) + + +def _check_lincon(input, varnames, coefs, constants): + try: + from numpy.testing import assert_equal + except ImportError: + from numpy.testing.utils import assert_equal + got = linear_constraint(input, varnames) + print("got", got) + expected = LinearConstraint(varnames, coefs, constants) + print("expected", expected) + assert_equal(got.variable_names, expected.variable_names) + assert_equal(got.coefs, expected.coefs) + assert_equal(got.constants, expected.constants) + assert_equal(got.coefs.dtype, np.dtype(float)) + assert_equal(got.constants.dtype, np.dtype(float)) + + +def test_linear_constraint(): + import pytest + from patsy.compat import OrderedDict + + t = _check_lincon + + t(LinearConstraint(["a", "b"], [2, 3]), ["a", "b"], [[2, 3]], [[0]]) + pytest.raises( + ValueError, linear_constraint, LinearConstraint(["b", "a"], [2, 3]), ["a", "b"] + ) + + t({"a": 2}, ["a", "b"], [[1, 0]], [[2]]) + t(OrderedDict([("a", 2), ("b", 3)]), ["a", "b"], [[1, 0], [0, 1]], [[2], [3]]) + t(OrderedDict([("a", 2), ("b", 3)]), ["b", "a"], [[0, 1], [1, 0]], [[2], [3]]) + + t({0: 2}, ["a", "b"], [[1, 0]], [[2]]) + t(OrderedDict([(0, 2), (1, 3)]), ["a", "b"], [[1, 0], [0, 1]], [[2], [3]]) + + t(OrderedDict([("a", 2), (1, 3)]), ["a", "b"], [[1, 0], [0, 1]], [[2], [3]]) + + pytest.raises(ValueError, linear_constraint, {"q": 1}, ["a", "b"]) + pytest.raises(ValueError, linear_constraint, {"a": 1, 0: 2}, ["a", "b"]) + + t(np.array([2, 3]), ["a", "b"], [[2, 3]], [[0]]) + t(np.array([[2, 3], [4, 5]]), ["a", "b"], [[2, 3], [4, 5]], [[0], [0]]) + + t("a = 2", ["a", "b"], [[1, 0]], [[2]]) + t("a - 2", ["a", "b"], [[1, 0]], [[2]]) + t("a + 1 = 3", ["a", "b"], [[1, 0]], [[2]]) + t("a + b = 3", ["a", "b"], [[1, 1]], [[3]]) + t("a = 2, b = 3", ["a", "b"], [[1, 0], [0, 1]], [[2], [3]]) + t("b = 3, a = 2", ["a", "b"], [[0, 1], [1, 0]], [[3], [2]]) + + t(["a = 2", "b = 3"], ["a", "b"], [[1, 0], [0, 1]], [[2], [3]]) + + pytest.raises(ValueError, linear_constraint, ["a", {"b": 0}], ["a", "b"]) + + # Actual evaluator tests + t( + "2 * (a + b/3) + b + 2*3/4 = 1 + 2*3", + ["a", "b"], + [[2, 2.0 / 3 + 1]], + [[7 - 6.0 / 4]], + ) + t("+2 * -a", ["a", "b"], [[-2, 0]], [[0]]) + t("a - b, a + b = 2", ["a", "b"], [[1, -1], [1, 1]], [[0], [2]]) + t("a = 1, a = 2, a = 3", ["a", "b"], [[1, 0], [1, 0], [1, 0]], [[1], [2], [3]]) + t("a * 2", ["a", "b"], [[2, 0]], [[0]]) + t("-a = 1", ["a", "b"], [[-1, 0]], [[1]]) + t("(2 + a - a) * b", ["a", "b"], [[0, 2]], [[0]]) + + t("a = 1 = b", ["a", "b"], [[1, 0], [0, -1]], [[1], [-1]]) + t("a = (1 = b)", ["a", "b"], [[0, -1], [1, 0]], [[-1], [1]]) + t( + "a = 1, a = b = c", + ["a", "b", "c"], + [[1, 0, 0], [1, -1, 0], [0, 1, -1]], + [[1], [0], [0]], + ) + + # One should never do this of course, but test that it works anyway... + t("a + 1 = 2", ["a", "a + 1"], [[0, 1]], [[2]]) + + t(([10, 20], [30]), ["a", "b"], [[10, 20]], [[30]]) + t( + ([[10, 20], [20, 40]], [[30], [35]]), + ["a", "b"], + [[10, 20], [20, 40]], + [[30], [35]], + ) + # wrong-length tuple + pytest.raises(ValueError, linear_constraint, ([1, 0], [0], [0]), ["a", "b"]) + pytest.raises(ValueError, linear_constraint, ([1, 0],), ["a", "b"]) + + t([10, 20], ["a", "b"], [[10, 20]], [[0]]) + t([[10, 20], [20, 40]], ["a", "b"], [[10, 20], [20, 40]], [[0], [0]]) + t(np.array([10, 20]), ["a", "b"], [[10, 20]], [[0]]) + t(np.array([[10, 20], [20, 40]]), ["a", "b"], [[10, 20], [20, 40]], [[0], [0]]) + + # unknown object type + pytest.raises(ValueError, linear_constraint, None, ["a", "b"]) + + +_parse_eval_error_tests = [ + # Bad token + "a + oo", + # No pure constant equalities + "a = 1, <1 = 1>, b = 1", + "a = 1, ", + "a = 1, <1>, b = 2", + "a = 1, <2 * b = b + b>, c", + # No non-linearities + "a + + c", + "a + 2 / + c", + # Constraints are not numbers + "a = 1, 2 * <(a = b)>, c", + "a = 1, a + <(a = b)>, c", + "a = 1, <(a, b)> + 2, c", +] + + +def test_eval_errors(): + def doit(bad_code): + return linear_constraint(bad_code, ["a", "b", "c"]) + + _parsing_error_test(doit, _parse_eval_error_tests) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/contrasts.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/contrasts.py new file mode 100644 index 0000000000000000000000000000000000000000..0ac9ac7532569963de42104332182f4627230e9e --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/contrasts.py @@ -0,0 +1,642 @@ +# This file is part of Patsy +# Copyright (C) 2011-2012 Nathaniel Smith +# See file LICENSE.txt for license information. + +# http://www.ats.ucla.edu/stat/r/library/contrast_coding.htm +# http://www.ats.ucla.edu/stat/sas/webbooks/reg/chapter5/sasreg5.htm + +# These are made available in the patsy.* namespace +__all__ = ["ContrastMatrix", "Treatment", "Poly", "Sum", "Helmert", "Diff"] + +import numpy as np +from patsy import PatsyError +from patsy.util import ( + repr_pretty_delegate, + repr_pretty_impl, + safe_issubdtype, + no_pickling, + assert_no_pickling, +) + + +class ContrastMatrix: + """A simple container for a matrix used for coding categorical factors. + + Attributes: + + .. attribute:: matrix + + A 2d ndarray, where each column corresponds to one column of the + resulting design matrix, and each row contains the entries for a single + categorical variable level. Usually n-by-n for a full rank coding or + n-by-(n-1) for a reduced rank coding, though other options are + possible. + + .. attribute:: column_suffixes + + A list of strings to be appended to the factor name, to produce the + final column names. E.g. for treatment coding the entries will look + like ``"[T.level1]"``. + """ + + def __init__(self, matrix, column_suffixes): + self.matrix = np.asarray(matrix) + self.column_suffixes = column_suffixes + if self.matrix.shape[1] != len(column_suffixes): + raise PatsyError("matrix and column_suffixes don't conform") + + __repr__ = repr_pretty_delegate + + def _repr_pretty_(self, p, cycle): + repr_pretty_impl(p, self, [self.matrix, self.column_suffixes]) + + __getstate__ = no_pickling + + +def test_ContrastMatrix(): + cm = ContrastMatrix([[1, 0], [0, 1]], ["a", "b"]) + assert np.array_equal(cm.matrix, np.eye(2)) + assert cm.column_suffixes == ["a", "b"] + # smoke test + repr(cm) + + import pytest + + pytest.raises(PatsyError, ContrastMatrix, [[1], [0]], ["a", "b"]) + + assert_no_pickling(cm) + + +# This always produces an object of the type that Python calls 'str' (whether +# that be a Python 2 string-of-bytes or a Python 3 string-of-unicode). It does +# *not* make any particular guarantees about being reversible or having other +# such useful programmatic properties -- it just produces something that will +# be nice for users to look at. +def _obj_to_readable_str(obj): + if isinstance(obj, str): + return obj + elif isinstance(obj, bytes): + try: + return obj.decode("utf-8") + except UnicodeDecodeError: + return repr(obj) + else: + return repr(obj) + + +def test__obj_to_readable_str(): + def t(obj, expected): + got = _obj_to_readable_str(obj) + assert type(got) is str + assert got == expected + + t(1, "1") + t(1.0, "1.0") + t("asdf", "asdf") + t("asdf", "asdf") + + # we can use "foo".encode here b/c this is python 3! + # a utf-8 encoded euro-sign comes out as a real euro sign. + t("\u20ac".encode("utf-8"), "\u20ac") + # but a iso-8859-15 euro sign can't be decoded, and we fall back on + # repr() + t("\u20ac".encode("iso-8859-15"), "b'\\xa4'") + + +def _name_levels(prefix, levels): + return ["[%s%s]" % (prefix, _obj_to_readable_str(level)) for level in levels] + + +def test__name_levels(): + assert _name_levels("a", ["b", "c"]) == ["[ab]", "[ac]"] + + +def _dummy_code(levels): + return ContrastMatrix(np.eye(len(levels)), _name_levels("", levels)) + + +def _get_level(levels, level_ref): + if level_ref in levels: + return levels.index(level_ref) + if isinstance(level_ref, int): + if level_ref < 0: + level_ref += len(levels) + if not (0 <= level_ref < len(levels)): + raise PatsyError("specified level %r is out of range" % (level_ref,)) + return level_ref + raise PatsyError("specified level %r not found" % (level_ref,)) + + +def test__get_level(): + assert _get_level(["a", "b", "c"], 0) == 0 + assert _get_level(["a", "b", "c"], -1) == 2 + assert _get_level(["a", "b", "c"], "b") == 1 + # For integer levels, we check identity before treating it as an index + assert _get_level([2, 1, 0], 0) == 2 + import pytest + + pytest.raises(PatsyError, _get_level, ["a", "b"], 2) + pytest.raises(PatsyError, _get_level, ["a", "b"], -3) + pytest.raises(PatsyError, _get_level, ["a", "b"], "c") + + +class Treatment: + """Treatment coding (also known as dummy coding). + + This is the default coding. + + For reduced-rank coding, one level is chosen as the "reference", and its + mean behaviour is represented by the intercept. Each column of the + resulting matrix represents the difference between the mean of one level + and this reference level. + + For full-rank coding, classic "dummy" coding is used, and each column of + the resulting matrix represents the mean of the corresponding level. + + The reference level defaults to the first level, or can be specified + explicitly. + + .. ipython:: python + + # reduced rank + dmatrix("C(a, Treatment)", balanced(a=3)) + # full rank + dmatrix("0 + C(a, Treatment)", balanced(a=3)) + # Setting a reference level + dmatrix("C(a, Treatment(1))", balanced(a=3)) + dmatrix("C(a, Treatment('a2'))", balanced(a=3)) + + Equivalent to R ``contr.treatment``. The R documentation suggests that + using ``Treatment(reference=-1)`` will produce contrasts that are + "equivalent to those produced by many (but not all) SAS procedures". + """ + + def __init__(self, reference=None): + self.reference = reference + + def code_with_intercept(self, levels): + return _dummy_code(levels) + + def code_without_intercept(self, levels): + if self.reference is None: + reference = 0 + else: + reference = _get_level(levels, self.reference) + eye = np.eye(len(levels) - 1) + contrasts = np.vstack( + (eye[:reference, :], np.zeros((1, len(levels) - 1)), eye[reference:, :]) + ) + names = _name_levels("T.", levels[:reference] + levels[reference + 1 :]) + return ContrastMatrix(contrasts, names) + + __getstate__ = no_pickling + + +def test_Treatment(): + t1 = Treatment() + matrix = t1.code_with_intercept(["a", "b", "c"]) + assert matrix.column_suffixes == ["[a]", "[b]", "[c]"] + assert np.allclose(matrix.matrix, [[1, 0, 0], [0, 1, 0], [0, 0, 1]]) + matrix = t1.code_without_intercept(["a", "b", "c"]) + assert matrix.column_suffixes == ["[T.b]", "[T.c]"] + assert np.allclose(matrix.matrix, [[0, 0], [1, 0], [0, 1]]) + matrix = Treatment(reference=1).code_without_intercept(["a", "b", "c"]) + assert matrix.column_suffixes == ["[T.a]", "[T.c]"] + assert np.allclose(matrix.matrix, [[1, 0], [0, 0], [0, 1]]) + matrix = Treatment(reference=-2).code_without_intercept(["a", "b", "c"]) + assert matrix.column_suffixes == ["[T.a]", "[T.c]"] + assert np.allclose(matrix.matrix, [[1, 0], [0, 0], [0, 1]]) + matrix = Treatment(reference="b").code_without_intercept(["a", "b", "c"]) + assert matrix.column_suffixes == ["[T.a]", "[T.c]"] + assert np.allclose(matrix.matrix, [[1, 0], [0, 0], [0, 1]]) + # Make sure the default is always the first level, even if there is a + # different level called 0. + matrix = Treatment().code_without_intercept([2, 1, 0]) + assert matrix.column_suffixes == ["[T.1]", "[T.0]"] + assert np.allclose(matrix.matrix, [[0, 0], [1, 0], [0, 1]]) + + +class Poly(object): + """Orthogonal polynomial contrast coding. + + This coding scheme treats the levels as ordered samples from an underlying + continuous scale, whose effect takes an unknown functional form which is + `Taylor-decomposed`__ into the sum of a linear, quadratic, etc. components. + + .. __: https://en.wikipedia.org/wiki/Taylor_series + + For reduced-rank coding, you get a linear column, a quadratic column, + etc., up to the number of levels provided. + + For full-rank coding, the same scheme is used, except that the zero-order + constant polynomial is also included. I.e., you get an intercept column + included as part of your categorical term. + + By default the levels are treated as equally spaced, but you can override + this by providing a value for the `scores` argument. + + Examples: + + .. ipython:: python + + # Reduced rank + dmatrix("C(a, Poly)", balanced(a=4)) + # Full rank + dmatrix("0 + C(a, Poly)", balanced(a=3)) + # Explicit scores + dmatrix("C(a, Poly([1, 2, 10]))", balanced(a=3)) + + This is equivalent to R's ``contr.poly``. (But note that in R, reduced + rank encodings are always dummy-coded, regardless of what contrast you + have set.) + """ + + def __init__(self, scores=None): + self.scores = scores + + def _code_either(self, intercept, levels): + n = len(levels) + scores = self.scores + if scores is None: + scores = np.arange(n) + scores = np.asarray(scores, dtype=float) + if len(scores) != n: + raise PatsyError( + "number of levels (%s) does not match" + " number of scores (%s)" % (n, len(scores)) + ) + # Strategy: just make a matrix whose columns are naive linear, + # quadratic, etc., functions of the raw scores, and then use 'qr' to + # orthogonalize each column against those to its left. + scores -= scores.mean() + raw_poly = scores.reshape((-1, 1)) ** np.arange(n).reshape((1, -1)) + q, r = np.linalg.qr(raw_poly) + q *= np.sign(np.diag(r)) + q /= np.sqrt(np.sum(q**2, axis=1)) + # The constant term is always all 1's -- we don't normalize it. + q[:, 0] = 1 + names = [".Constant", ".Linear", ".Quadratic", ".Cubic"] + names += ["^%s" % (i,) for i in range(4, n)] + names = names[:n] + if intercept: + return ContrastMatrix(q, names) + else: + # We always include the constant/intercept column as something to + # orthogonalize against, but we don't always return it: + return ContrastMatrix(q[:, 1:], names[1:]) + + def code_with_intercept(self, levels): + return self._code_either(True, levels) + + def code_without_intercept(self, levels): + return self._code_either(False, levels) + + __getstate__ = no_pickling + + +def test_Poly(): + t1 = Poly() + matrix = t1.code_with_intercept(["a", "b", "c"]) + assert matrix.column_suffixes == [".Constant", ".Linear", ".Quadratic"] + # Values from R 'options(digits=15); contr.poly(3)' + expected = [ + [1, -7.07106781186548e-01, 0.408248290463863], + [1, 0, -0.816496580927726], + [1, 7.07106781186547e-01, 0.408248290463863], + ] + print(matrix.matrix) + assert np.allclose(matrix.matrix, expected) + matrix = t1.code_without_intercept(["a", "b", "c"]) + assert matrix.column_suffixes == [".Linear", ".Quadratic"] + # Values from R 'options(digits=15); contr.poly(3)' + print(matrix.matrix) + assert np.allclose( + matrix.matrix, + [ + [-7.07106781186548e-01, 0.408248290463863], + [0, -0.816496580927726], + [7.07106781186547e-01, 0.408248290463863], + ], + ) + + matrix = Poly(scores=[0, 10, 11]).code_with_intercept(["a", "b", "c"]) + assert matrix.column_suffixes == [".Constant", ".Linear", ".Quadratic"] + # Values from R 'options(digits=15); contr.poly(3, scores=c(0, 10, 11))' + print(matrix.matrix) + assert np.allclose( + matrix.matrix, + [ + [1, -0.813733471206735, 0.0671156055214024], + [1, 0.348742916231458, -0.7382716607354268], + [1, 0.464990554975277, 0.6711560552140243], + ], + ) + + # we had an integer/float handling bug for score vectors whose mean was + # non-integer, so check one of those: + matrix = Poly(scores=[0, 10, 12]).code_with_intercept(["a", "b", "c"]) + assert matrix.column_suffixes == [".Constant", ".Linear", ".Quadratic"] + # Values from R 'options(digits=15); contr.poly(3, scores=c(0, 10, 12))' + print(matrix.matrix) + assert np.allclose( + matrix.matrix, + [ + [1, -0.806559132617443, 0.127000127000191], + [1, 0.293294230042706, -0.762000762001143], + [1, 0.513264902574736, 0.635000635000952], + ], + ) + + import pytest + + pytest.raises(PatsyError, Poly(scores=[0, 1]).code_with_intercept, ["a", "b", "c"]) + + matrix = t1.code_with_intercept(list(range(6))) + assert matrix.column_suffixes == [ + ".Constant", + ".Linear", + ".Quadratic", + ".Cubic", + "^4", + "^5", + ] + + +class Sum(object): + """Deviation coding (also known as sum-to-zero coding). + + Compares the mean of each level to the mean-of-means. (In a balanced + design, compares the mean of each level to the overall mean.) + + For full-rank coding, a standard intercept term is added. + + One level must be omitted to avoid redundancy; by default this is the last + level, but this can be adjusted via the `omit` argument. + + .. warning:: There are multiple definitions of 'deviation coding' in + use. Make sure this is the one you expect before trying to interpret + your results! + + Examples: + + .. ipython:: python + + # Reduced rank + dmatrix("C(a, Sum)", balanced(a=4)) + # Full rank + dmatrix("0 + C(a, Sum)", balanced(a=4)) + # Omit a different level + dmatrix("C(a, Sum(1))", balanced(a=3)) + dmatrix("C(a, Sum('a1'))", balanced(a=3)) + + This is equivalent to R's `contr.sum`. + """ + + def __init__(self, omit=None): + self.omit = omit + + def _omit_i(self, levels): + if self.omit is None: + # We assume below that this is positive + return len(levels) - 1 + else: + return _get_level(levels, self.omit) + + def _sum_contrast(self, levels): + n = len(levels) + omit_i = self._omit_i(levels) + eye = np.eye(n - 1) + out = np.empty((n, n - 1)) + out[:omit_i, :] = eye[:omit_i, :] + out[omit_i, :] = -1 + out[omit_i + 1 :, :] = eye[omit_i:, :] + return out + + def code_with_intercept(self, levels): + contrast = self.code_without_intercept(levels) + matrix = np.column_stack((np.ones(len(levels)), contrast.matrix)) + column_suffixes = ["[mean]"] + contrast.column_suffixes + return ContrastMatrix(matrix, column_suffixes) + + def code_without_intercept(self, levels): + matrix = self._sum_contrast(levels) + omit_i = self._omit_i(levels) + included_levels = levels[:omit_i] + levels[omit_i + 1 :] + return ContrastMatrix(matrix, _name_levels("S.", included_levels)) + + __getstate__ = no_pickling + + +def test_Sum(): + t1 = Sum() + matrix = t1.code_with_intercept(["a", "b", "c"]) + assert matrix.column_suffixes == ["[mean]", "[S.a]", "[S.b]"] + assert np.allclose(matrix.matrix, [[1, 1, 0], [1, 0, 1], [1, -1, -1]]) + matrix = t1.code_without_intercept(["a", "b", "c"]) + assert matrix.column_suffixes == ["[S.a]", "[S.b]"] + assert np.allclose(matrix.matrix, [[1, 0], [0, 1], [-1, -1]]) + # Check that it's not thrown off by negative integer term names + matrix = t1.code_without_intercept([-1, -2, -3]) + assert matrix.column_suffixes == ["[S.-1]", "[S.-2]"] + assert np.allclose(matrix.matrix, [[1, 0], [0, 1], [-1, -1]]) + t2 = Sum(omit=1) + matrix = t2.code_with_intercept(["a", "b", "c"]) + assert matrix.column_suffixes == ["[mean]", "[S.a]", "[S.c]"] + assert np.allclose(matrix.matrix, [[1, 1, 0], [1, -1, -1], [1, 0, 1]]) + matrix = t2.code_without_intercept(["a", "b", "c"]) + assert matrix.column_suffixes == ["[S.a]", "[S.c]"] + assert np.allclose(matrix.matrix, [[1, 0], [-1, -1], [0, 1]]) + matrix = t2.code_without_intercept([1, 0, 2]) + assert matrix.column_suffixes == ["[S.0]", "[S.2]"] + assert np.allclose(matrix.matrix, [[-1, -1], [1, 0], [0, 1]]) + t3 = Sum(omit=-3) + matrix = t3.code_with_intercept(["a", "b", "c"]) + assert matrix.column_suffixes == ["[mean]", "[S.b]", "[S.c]"] + assert np.allclose(matrix.matrix, [[1, -1, -1], [1, 1, 0], [1, 0, 1]]) + matrix = t3.code_without_intercept(["a", "b", "c"]) + assert matrix.column_suffixes == ["[S.b]", "[S.c]"] + assert np.allclose(matrix.matrix, [[-1, -1], [1, 0], [0, 1]]) + t4 = Sum(omit="a") + matrix = t3.code_with_intercept(["a", "b", "c"]) + assert matrix.column_suffixes == ["[mean]", "[S.b]", "[S.c]"] + assert np.allclose(matrix.matrix, [[1, -1, -1], [1, 1, 0], [1, 0, 1]]) + matrix = t3.code_without_intercept(["a", "b", "c"]) + assert matrix.column_suffixes == ["[S.b]", "[S.c]"] + assert np.allclose(matrix.matrix, [[-1, -1], [1, 0], [0, 1]]) + + +class Helmert(object): + """Helmert contrasts. + + Compares the second level with the first, the third with the average of + the first two, and so on. + + For full-rank coding, a standard intercept term is added. + + .. warning:: There are multiple definitions of 'Helmert coding' in + use. Make sure this is the one you expect before trying to interpret + your results! + + Examples: + + .. ipython:: python + + # Reduced rank + dmatrix("C(a, Helmert)", balanced(a=4)) + # Full rank + dmatrix("0 + C(a, Helmert)", balanced(a=4)) + + This is equivalent to R's `contr.helmert`. + """ + + def _helmert_contrast(self, levels): + n = len(levels) + # http://www.ats.ucla.edu/stat/sas/webbooks/reg/chapter5/sasreg5.htm#HELMERT + # contr = np.eye(n - 1) + # int_range = np.arange(n - 1., 1, -1) + # denom = np.repeat(int_range, np.arange(n - 2, 0, -1)) + # contr[np.tril_indices(n - 1, -1)] = -1. / denom + + # http://www.ats.ucla.edu/stat/r/library/contrast_coding.htm#HELMERT + # contr = np.zeros((n - 1., n - 1)) + # int_range = np.arange(n, 1, -1) + # denom = np.repeat(int_range[:-1], np.arange(n - 2, 0, -1)) + # contr[np.diag_indices(n - 1)] = (int_range - 1.) / int_range + # contr[np.tril_indices(n - 1, -1)] = -1. / denom + # contr = np.vstack((contr, -1./int_range)) + + # r-like + contr = np.zeros((n, n - 1)) + contr[1:][np.diag_indices(n - 1)] = np.arange(1, n) + contr[np.triu_indices(n - 1)] = -1 + return contr + + def code_with_intercept(self, levels): + contrast = np.column_stack( + (np.ones(len(levels)), self._helmert_contrast(levels)) + ) + column_suffixes = _name_levels("H.", ["intercept"] + list(levels[1:])) + return ContrastMatrix(contrast, column_suffixes) + + def code_without_intercept(self, levels): + contrast = self._helmert_contrast(levels) + return ContrastMatrix(contrast, _name_levels("H.", levels[1:])) + + __getstate__ = no_pickling + + +def test_Helmert(): + t1 = Helmert() + for levels in (["a", "b", "c", "d"], ("a", "b", "c", "d")): + matrix = t1.code_with_intercept(levels) + assert matrix.column_suffixes == ["[H.intercept]", "[H.b]", "[H.c]", "[H.d]"] + assert np.allclose( + matrix.matrix, + [[1, -1, -1, -1], [1, 1, -1, -1], [1, 0, 2, -1], [1, 0, 0, 3]], + ) + matrix = t1.code_without_intercept(levels) + assert matrix.column_suffixes == ["[H.b]", "[H.c]", "[H.d]"] + assert np.allclose( + matrix.matrix, [[-1, -1, -1], [1, -1, -1], [0, 2, -1], [0, 0, 3]] + ) + + +class Diff(object): + """Backward difference coding. + + This coding scheme is useful for ordered factors, and compares the mean of + each level with the preceding level. So you get the second level minus the + first, the third level minus the second, etc. + + For full-rank coding, a standard intercept term is added (which gives the + mean value for the first level). + + Examples: + + .. ipython:: python + + # Reduced rank + dmatrix("C(a, Diff)", balanced(a=3)) + # Full rank + dmatrix("0 + C(a, Diff)", balanced(a=3)) + """ + + def _diff_contrast(self, levels): + nlevels = len(levels) + contr = np.zeros((nlevels, nlevels - 1)) + int_range = np.arange(1, nlevels) + upper_int = np.repeat(int_range, int_range) + row_i, col_i = np.triu_indices(nlevels - 1) + # we want to iterate down the columns not across the rows + # it would be nice if the index functions had a row/col order arg + col_order = np.argsort(col_i) + contr[row_i[col_order], col_i[col_order]] = (upper_int - nlevels) / float( + nlevels + ) + lower_int = np.repeat(int_range, int_range[::-1]) + row_i, col_i = np.tril_indices(nlevels - 1) + # we want to iterate down the columns not across the rows + col_order = np.argsort(col_i) + contr[row_i[col_order] + 1, col_i[col_order]] = lower_int / float(nlevels) + return contr + + def code_with_intercept(self, levels): + contrast = np.column_stack((np.ones(len(levels)), self._diff_contrast(levels))) + return ContrastMatrix(contrast, _name_levels("D.", levels)) + + def code_without_intercept(self, levels): + contrast = self._diff_contrast(levels) + return ContrastMatrix(contrast, _name_levels("D.", levels[:-1])) + + __getstate__ = no_pickling + + +def test_diff(): + t1 = Diff() + matrix = t1.code_with_intercept(["a", "b", "c", "d"]) + assert matrix.column_suffixes == ["[D.a]", "[D.b]", "[D.c]", "[D.d]"] + assert np.allclose( + matrix.matrix, + [ + [1, -3 / 4.0, -1 / 2.0, -1 / 4.0], + [1, 1 / 4.0, -1 / 2.0, -1 / 4.0], + [1, 1 / 4.0, 1.0 / 2, -1 / 4.0], + [1, 1 / 4.0, 1 / 2.0, 3 / 4.0], + ], + ) + matrix = t1.code_without_intercept(["a", "b", "c", "d"]) + assert matrix.column_suffixes == ["[D.a]", "[D.b]", "[D.c]"] + assert np.allclose( + matrix.matrix, + [ + [-3 / 4.0, -1 / 2.0, -1 / 4.0], + [1 / 4.0, -1 / 2.0, -1 / 4.0], + [1 / 4.0, 2.0 / 4, -1 / 4.0], + [1 / 4.0, 1 / 2.0, 3 / 4.0], + ], + ) + + +# contrast can be: +# -- a ContrastMatrix +# -- a simple np.ndarray +# -- an object with code_with_intercept and code_without_intercept methods +# -- a function returning one of the above +# -- None, in which case the above rules are applied to 'default' +# This function always returns a ContrastMatrix. +def code_contrast_matrix(intercept, levels, contrast, default=None): + if contrast is None: + contrast = default + if callable(contrast): + contrast = contrast() + if isinstance(contrast, ContrastMatrix): + return contrast + as_array = np.asarray(contrast) + if safe_issubdtype(as_array.dtype, np.number): + return ContrastMatrix( + as_array, _name_levels("custom", range(as_array.shape[1])) + ) + if intercept: + return contrast.code_with_intercept(levels) + else: + return contrast.code_without_intercept(levels) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/desc.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/desc.py new file mode 100644 index 0000000000000000000000000000000000000000..210350df2c9b772b06824e2ab99613ed1ec5b32b --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/desc.py @@ -0,0 +1,668 @@ +# This file is part of Patsy +# Copyright (C) 2011-2012 Nathaniel Smith +# See file LICENSE.txt for license information. + +# This file defines the ModelDesc class, which describes a model at a high +# level, as a list of interactions of factors. It also has the code to convert +# a formula parse tree (from patsy.parse_formula) into a ModelDesc. + +from patsy import PatsyError +from patsy.parse_formula import ParseNode, Token, parse_formula +from patsy.eval import EvalEnvironment, EvalFactor +from patsy.util import uniqueify_list +from patsy.util import repr_pretty_delegate, repr_pretty_impl +from patsy.util import no_pickling, assert_no_pickling + +# These are made available in the patsy.* namespace +__all__ = ["Term", "ModelDesc", "INTERCEPT"] + + +# One might think it would make more sense for 'factors' to be a set, rather +# than a tuple-with-guaranteed-unique-entries-that-compares-like-a-set. The +# reason we do it this way is that it preserves the order that the user typed +# and is expecting, which then ends up producing nicer names in our final +# output, nicer column ordering, etc. (A similar comment applies to the +# ordering of terms in ModelDesc objects as a whole.) +class Term(object): + """The interaction between a collection of factor objects. + + This is one of the basic types used in representing formulas, and + corresponds to an expression like ``"a:b:c"`` in a formula string. + For details, see :ref:`formulas` and :ref:`expert-model-specification`. + + Terms are hashable and compare by value. + + Attributes: + + .. attribute:: factors + + A tuple of factor objects. + """ + + def __init__(self, factors): + self.factors = tuple(uniqueify_list(factors)) + + def __eq__(self, other): + return isinstance(other, Term) and frozenset(other.factors) == frozenset( + self.factors + ) + + def __ne__(self, other): + return not self == other + + def __hash__(self): + return hash((Term, frozenset(self.factors))) + + __repr__ = repr_pretty_delegate + + def _repr_pretty_(self, p, cycle): + assert not cycle + repr_pretty_impl(p, self, [list(self.factors)]) + + def name(self): + """Return a human-readable name for this term.""" + if self.factors: + return ":".join([f.name() for f in self.factors]) + else: + return "Intercept" + + __getstate__ = no_pickling + + +INTERCEPT = Term([]) + + +class _MockFactor(object): + def __init__(self, name): + self._name = name + + def name(self): + return self._name + + +def test_Term(): + assert Term([1, 2, 1]).factors == (1, 2) + assert Term([1, 2]) == Term([2, 1]) + assert hash(Term([1, 2])) == hash(Term([2, 1])) + f1 = _MockFactor("a") + f2 = _MockFactor("b") + assert Term([f1, f2]).name() == "a:b" + assert Term([f2, f1]).name() == "b:a" + assert Term([]).name() == "Intercept" + + assert_no_pickling(Term([])) + + +class ModelDesc(object): + """A simple container representing the termlists parsed from a formula. + + This is a simple container object which has exactly the same + representational power as a formula string, but is a Python object + instead. You can construct one by hand, and pass it to functions like + :func:`dmatrix` or :func:`incr_dbuilder` that are expecting a formula + string, but without having to do any messy string manipulation. For + details see :ref:`expert-model-specification`. + + Attributes: + + .. attribute:: lhs_termlist + rhs_termlist + + Two termlists representing the left- and right-hand sides of a + formula, suitable for passing to :func:`design_matrix_builders`. + """ + + def __init__(self, lhs_termlist, rhs_termlist): + self.lhs_termlist = uniqueify_list(lhs_termlist) + self.rhs_termlist = uniqueify_list(rhs_termlist) + + __repr__ = repr_pretty_delegate + + def _repr_pretty_(self, p, cycle): + assert not cycle + return repr_pretty_impl( + p, + self, + [], + [("lhs_termlist", self.lhs_termlist), ("rhs_termlist", self.rhs_termlist)], + ) + + def describe(self): + """Returns a human-readable representation of this :class:`ModelDesc` + in pseudo-formula notation. + + .. warning:: There is no guarantee that the strings returned by this + function can be parsed as formulas. They are best-effort + descriptions intended for human users. However, if this ModelDesc + was created by parsing a formula, then it should work in + practice. If you *really* have to. + """ + + def term_code(term): + if term == INTERCEPT: + return "1" + else: + return term.name() + + result = " + ".join([term_code(term) for term in self.lhs_termlist]) + if result: + result += " ~ " + else: + result += "~ " + if self.rhs_termlist == [INTERCEPT]: + result += term_code(INTERCEPT) + else: + term_names = [] + if INTERCEPT not in self.rhs_termlist: + term_names.append("0") + term_names += [ + term_code(term) for term in self.rhs_termlist if term != INTERCEPT + ] + result += " + ".join(term_names) + return result + + @classmethod + def from_formula(cls, tree_or_string): + """Construct a :class:`ModelDesc` from a formula string. + + :arg tree_or_string: A formula string. (Or an unevaluated formula + parse tree, but the API for generating those isn't public yet. Shh, + it can be our secret.) + :returns: A new :class:`ModelDesc`. + """ + if isinstance(tree_or_string, ParseNode): + tree = tree_or_string + else: + tree = parse_formula(tree_or_string) + value = Evaluator().eval(tree, require_evalexpr=False) + assert isinstance(value, cls) + return value + + __getstate__ = no_pickling + + +def test_ModelDesc(): + f1 = _MockFactor("a") + f2 = _MockFactor("b") + m = ModelDesc([INTERCEPT, Term([f1])], [Term([f1]), Term([f1, f2])]) + assert m.lhs_termlist == [INTERCEPT, Term([f1])] + assert m.rhs_termlist == [Term([f1]), Term([f1, f2])] + print(m.describe()) + assert m.describe() == "1 + a ~ 0 + a + a:b" + + assert_no_pickling(m) + + assert ModelDesc([], []).describe() == "~ 0" + assert ModelDesc([INTERCEPT], []).describe() == "1 ~ 0" + assert ModelDesc([INTERCEPT], [INTERCEPT]).describe() == "1 ~ 1" + assert ModelDesc([INTERCEPT], [INTERCEPT, Term([f2])]).describe() == "1 ~ b" + + +def test_ModelDesc_from_formula(): + for input in ("y ~ x", parse_formula("y ~ x")): + md = ModelDesc.from_formula(input) + assert md.lhs_termlist == [ + Term([EvalFactor("y")]), + ] + assert md.rhs_termlist == [INTERCEPT, Term([EvalFactor("x")])] + + +class IntermediateExpr(object): + "This class holds an intermediate result while we're evaluating a tree." + + def __init__(self, intercept, intercept_origin, intercept_removed, terms): + self.intercept = intercept + self.intercept_origin = intercept_origin + self.intercept_removed = intercept_removed + self.terms = tuple(uniqueify_list(terms)) + if self.intercept: + assert self.intercept_origin + assert not (self.intercept and self.intercept_removed) + + __repr__ = repr_pretty_delegate + + def _pretty_repr_(self, p, cycle): # pragma: no cover + assert not cycle + return repr_pretty_impl( + p, + self, + [self.intercept, self.intercept_origin, self.intercept_removed, self.terms], + ) + + __getstate__ = no_pickling + + +def _maybe_add_intercept(doit, terms): + if doit: + return (INTERCEPT,) + terms + else: + return terms + + +def _eval_any_tilde(evaluator, tree): + exprs = [evaluator.eval(arg) for arg in tree.args] + if len(exprs) == 1: + # Formula was like: "~ foo" + # We pretend that instead it was like: "0 ~ foo" + exprs.insert(0, IntermediateExpr(False, None, True, [])) + assert len(exprs) == 2 + # Note that only the RHS gets an implicit intercept: + return ModelDesc( + _maybe_add_intercept(exprs[0].intercept, exprs[0].terms), + _maybe_add_intercept(not exprs[1].intercept_removed, exprs[1].terms), + ) + + +def _eval_binary_plus(evaluator, tree): + left_expr = evaluator.eval(tree.args[0]) + if tree.args[1].type == "ZERO": + return IntermediateExpr(False, None, True, left_expr.terms) + else: + right_expr = evaluator.eval(tree.args[1]) + if right_expr.intercept: + return IntermediateExpr( + True, + right_expr.intercept_origin, + False, + left_expr.terms + right_expr.terms, + ) + else: + return IntermediateExpr( + left_expr.intercept, + left_expr.intercept_origin, + left_expr.intercept_removed, + left_expr.terms + right_expr.terms, + ) + + +def _eval_binary_minus(evaluator, tree): + left_expr = evaluator.eval(tree.args[0]) + if tree.args[1].type == "ZERO": + return IntermediateExpr(True, tree.args[1], False, left_expr.terms) + elif tree.args[1].type == "ONE": + return IntermediateExpr(False, None, True, left_expr.terms) + else: + right_expr = evaluator.eval(tree.args[1]) + terms = [term for term in left_expr.terms if term not in right_expr.terms] + if right_expr.intercept: + return IntermediateExpr(False, None, True, terms) + else: + return IntermediateExpr( + left_expr.intercept, + left_expr.intercept_origin, + left_expr.intercept_removed, + terms, + ) + + +def _check_interactable(expr): + if expr.intercept: + raise PatsyError( + "intercept term cannot interact with anything else", + expr.intercept_origin, + ) + + +def _interaction(left_expr, right_expr): + for expr in (left_expr, right_expr): + _check_interactable(expr) + terms = [] + for l_term in left_expr.terms: + for r_term in right_expr.terms: + terms.append(Term(l_term.factors + r_term.factors)) + return IntermediateExpr(False, None, False, terms) + + +def _eval_binary_prod(evaluator, tree): + exprs = [evaluator.eval(arg) for arg in tree.args] + return IntermediateExpr( + False, None, False, exprs[0].terms + exprs[1].terms + _interaction(*exprs).terms + ) + + +# Division (nesting) is right-ward distributive: +# a / (b + c) -> a/b + a/c -> a + a:b + a:c +# But left-ward, in S/R it has a quirky behavior: +# (a + b)/c -> a + b + a:b:c +# This is because it's meaningless for a factor to be "nested" under two +# different factors. (This is documented in Chambers and Hastie (page 30) as a +# "Slightly more subtle..." rule, with no further elaboration. Hopefully we +# will do better.) +def _eval_binary_div(evaluator, tree): + left_expr = evaluator.eval(tree.args[0]) + right_expr = evaluator.eval(tree.args[1]) + terms = list(left_expr.terms) + _check_interactable(left_expr) + # Build a single giant combined term for everything on the left: + left_factors = [] + for term in left_expr.terms: + left_factors += list(term.factors) + left_combined_expr = IntermediateExpr(False, None, False, [Term(left_factors)]) + # Then interact it with everything on the right: + terms += list(_interaction(left_combined_expr, right_expr).terms) + return IntermediateExpr(False, None, False, terms) + + +def _eval_binary_interact(evaluator, tree): + exprs = [evaluator.eval(arg) for arg in tree.args] + return _interaction(*exprs) + + +def _eval_binary_power(evaluator, tree): + left_expr = evaluator.eval(tree.args[0]) + _check_interactable(left_expr) + power = -1 + if tree.args[1].type in ("ONE", "NUMBER"): + expr = tree.args[1].token.extra + try: + power = int(expr) + except ValueError: + pass + if power < 1: + raise PatsyError("'**' requires a positive integer", tree.args[1]) + all_terms = left_expr.terms + big_expr = left_expr + # Small optimization: (a + b)**100 is just the same as (a + b)**2. + power = min(len(left_expr.terms), power) + for i in range(1, power): + big_expr = _interaction(left_expr, big_expr) + all_terms = all_terms + big_expr.terms + return IntermediateExpr(False, None, False, all_terms) + + +def _eval_unary_plus(evaluator, tree): + return evaluator.eval(tree.args[0]) + + +def _eval_unary_minus(evaluator, tree): + if tree.args[0].type == "ZERO": + return IntermediateExpr(True, tree.origin, False, []) + elif tree.args[0].type == "ONE": + return IntermediateExpr(False, None, True, []) + else: + raise PatsyError("Unary minus can only be applied to 1 or 0", tree) + + +def _eval_zero(evaluator, tree): + return IntermediateExpr(False, None, True, []) + + +def _eval_one(evaluator, tree): + return IntermediateExpr(True, tree.origin, False, []) + + +def _eval_number(evaluator, tree): + raise PatsyError("numbers besides '0' and '1' are only allowed with **", tree) + + +def _eval_python_expr(evaluator, tree): + factor = EvalFactor(tree.token.extra, origin=tree.origin) + return IntermediateExpr(False, None, False, [Term([factor])]) + + +class Evaluator(object): + def __init__(self): + self._evaluators = {} + self.add_op("~", 2, _eval_any_tilde) + self.add_op("~", 1, _eval_any_tilde) + + self.add_op("+", 2, _eval_binary_plus) + self.add_op("-", 2, _eval_binary_minus) + self.add_op("*", 2, _eval_binary_prod) + self.add_op("/", 2, _eval_binary_div) + self.add_op(":", 2, _eval_binary_interact) + self.add_op("**", 2, _eval_binary_power) + + self.add_op("+", 1, _eval_unary_plus) + self.add_op("-", 1, _eval_unary_minus) + + self.add_op("ZERO", 0, _eval_zero) + self.add_op("ONE", 0, _eval_one) + self.add_op("NUMBER", 0, _eval_number) + self.add_op("PYTHON_EXPR", 0, _eval_python_expr) + + # Not used by Patsy -- provided for the convenience of eventual + # user-defined operators. + self.stash = {} + + # This should not be considered a public API yet (to use for actually + # adding new operator semantics) because I wrote in some of the relevant + # code sort of speculatively, but it isn't actually tested. + def add_op(self, op, arity, evaluator): + self._evaluators[op, arity] = evaluator + + def eval(self, tree, require_evalexpr=True): + result = None + assert isinstance(tree, ParseNode) + key = (tree.type, len(tree.args)) + if key not in self._evaluators: + raise PatsyError( + "I don't know how to evaluate this '%s' operator" % (tree.type,), + tree.token, + ) + result = self._evaluators[key](self, tree) + if require_evalexpr and not isinstance(result, IntermediateExpr): + if isinstance(result, ModelDesc): + raise PatsyError( + "~ can only be used once, and only at the top level", tree + ) + else: + raise PatsyError( + "custom operator returned an " + "object that I don't know how to " + "handle", + tree, + ) + return result + + +############# + +_eval_tests = { + "": (True, []), + " ": (True, []), + " \n ": (True, []), + "a": (True, ["a"]), + "1": (True, []), + "0": (False, []), + "- 1": (False, []), + "- 0": (True, []), + "+ 1": (True, []), + "+ 0": (False, []), + "0 + 1": (True, []), + "1 + 0": (False, []), + "1 - 0": (True, []), + "0 - 1": (False, []), + "1 + a": (True, ["a"]), + "0 + a": (False, ["a"]), + "a - 1": (False, ["a"]), + "a - 0": (True, ["a"]), + "1 - a": (True, []), + "a + b": (True, ["a", "b"]), + "(a + b)": (True, ["a", "b"]), + "a + ((((b))))": (True, ["a", "b"]), + "a + ((((+b))))": (True, ["a", "b"]), + "a + ((((b - a))))": (True, ["a", "b"]), + "a + a + a": (True, ["a"]), + "a + (b - a)": (True, ["a", "b"]), + "a + np.log(a, base=10)": (True, ["a", "np.log(a, base=10)"]), + # Note different spacing: + "a + np.log(a, base=10) - np . log(a , base = 10)": (True, ["a"]), + "a + (I(b) + c)": (True, ["a", "I(b)", "c"]), + "a + I(b + c)": (True, ["a", "I(b + c)"]), + "a:b": (True, [("a", "b")]), + "a:b:a": (True, [("a", "b")]), + "a:(b + c)": (True, [("a", "b"), ("a", "c")]), + "(a + b):c": (True, [("a", "c"), ("b", "c")]), + "a:(b - c)": (True, [("a", "b")]), + "c + a:c + a:(b - c)": (True, ["c", ("a", "c"), ("a", "b")]), + "(a - b):c": (True, [("a", "c")]), + "b + b:c + (a - b):c": (True, ["b", ("b", "c"), ("a", "c")]), + "a:b - a:b": (True, []), + "a:b - b:a": (True, []), + "1 - (a + b)": (True, []), + "a + b - (a + b)": (True, []), + "a * b": (True, ["a", "b", ("a", "b")]), + "a * b * a": (True, ["a", "b", ("a", "b")]), + "a * (b + c)": (True, ["a", "b", "c", ("a", "b"), ("a", "c")]), + "(a + b) * c": (True, ["a", "b", "c", ("a", "c"), ("b", "c")]), + "a * (b - c)": (True, ["a", "b", ("a", "b")]), + "c + a:c + a * (b - c)": (True, ["c", ("a", "c"), "a", "b", ("a", "b")]), + "(a - b) * c": (True, ["a", "c", ("a", "c")]), + "b + b:c + (a - b) * c": (True, ["b", ("b", "c"), "a", "c", ("a", "c")]), + "a/b": (True, ["a", ("a", "b")]), + "(a + b)/c": (True, ["a", "b", ("a", "b", "c")]), + "b + b:c + (a - b)/c": (True, ["b", ("b", "c"), "a", ("a", "c")]), + "a/(b + c)": (True, ["a", ("a", "b"), ("a", "c")]), + "a ** 2": (True, ["a"]), + "(a + b + c + d) ** 2": ( + True, + [ + "a", + "b", + "c", + "d", + ("a", "b"), + ("a", "c"), + ("a", "d"), + ("b", "c"), + ("b", "d"), + ("c", "d"), + ], + ), + "(a + b + c + d) ** 3": ( + True, + [ + "a", + "b", + "c", + "d", + ("a", "b"), + ("a", "c"), + ("a", "d"), + ("b", "c"), + ("b", "d"), + ("c", "d"), + ("a", "b", "c"), + ("a", "b", "d"), + ("a", "c", "d"), + ("b", "c", "d"), + ], + ), + "a + +a": (True, ["a"]), + "~ a + b": (True, ["a", "b"]), + "~ a*b": (True, ["a", "b", ("a", "b")]), + "~ a*b + 0": (False, ["a", "b", ("a", "b")]), + "~ -1": (False, []), + "0 ~ a + b": (True, ["a", "b"]), + "1 ~ a + b": (True, [], True, ["a", "b"]), + "y ~ a + b": (False, ["y"], True, ["a", "b"]), + "0 + y ~ a + b": (False, ["y"], True, ["a", "b"]), + "0 + y * z ~ a + b": (False, ["y", "z", ("y", "z")], True, ["a", "b"]), + "-1 ~ 1": (False, [], True, []), + "1 + y ~ a + b": (True, ["y"], True, ["a", "b"]), + # Check precedence: + "a + b * c": (True, ["a", "b", "c", ("b", "c")]), + "a * b + c": (True, ["a", "b", ("a", "b"), "c"]), + "a * b - a": (True, ["b", ("a", "b")]), + "a + b / c": (True, ["a", "b", ("b", "c")]), + "a / b + c": (True, ["a", ("a", "b"), "c"]), + "a*b:c": (True, ["a", ("b", "c"), ("a", "b", "c")]), + "a:b*c": (True, [("a", "b"), "c", ("a", "b", "c")]), + # Intercept handling: + "~ 1 + 1 + 0 + 1": (True, []), + "~ 0 + 1 + 0": (False, []), + "~ 0 - 1 - 1 + 0 + 1": (True, []), + "~ 1 - 1": (False, []), + "~ 0 + a + 1": (True, ["a"]), + "~ 1 + (a + 0)": (True, ["a"]), # This is correct, but perhaps surprising! + "~ 0 + (a + 1)": (True, ["a"]), # Also correct! + "~ 1 - (a + 1)": (False, []), +} + +# <> mark off where the error should be reported: +_eval_error_tests = [ + "a <+>", + "a + <(>", + "b + <(-a)>", + "a:<1>", + "(a + <1>)*b", + "a + <2>", + "a + <1.0>", + # eh, catching this is a hassle, we'll just leave the user some rope if + # they really want it: + # "a + <0x1>", + "a ** ", + "a ** <(1 + 1)>", + "a ** <1.5>", + "a + b <# asdf>", + "<)>", + "a + <)>", + "<*> a", + "a + <*>", + "a + ", + "a + ", + "a + ", + "a + <[bar>", + "a + <{bar>", + "a + <{bar[]>", + "a + foo<]>bar", + "a + foo[]<]>bar", + "a + foo{}<}>bar", + "a + foo<)>bar", + "a + b<)>", + "(a) <.>", + "<(>a + b", + " ~ b", + "y ~ <(a ~ b)>", + "<~ a> ~ b", + "~ <(a ~ b)>", + "1 + <-(a + b)>", + "<- a>", + "a + <-a**2>", +] + + +def _assert_terms_match(terms, expected_intercept, expecteds): # pragma: no cover + if expected_intercept: + expecteds = [()] + expecteds + assert len(terms) == len(expecteds) + for term, expected in zip(terms, expecteds): + if isinstance(term, Term): + if isinstance(expected, str): + expected = (expected,) + assert term.factors == tuple([EvalFactor(s) for s in expected]) + else: + assert term == expected + + +def _do_eval_formula_tests(tests): # pragma: no cover + for code, result in tests.items(): + if len(result) == 2: + result = (False, []) + result + model_desc = ModelDesc.from_formula(code) + print(repr(code)) + print(result) + print(model_desc) + lhs_intercept, lhs_termlist, rhs_intercept, rhs_termlist = result + _assert_terms_match(model_desc.lhs_termlist, lhs_intercept, lhs_termlist) + _assert_terms_match(model_desc.rhs_termlist, rhs_intercept, rhs_termlist) + + +def test_eval_formula(): + _do_eval_formula_tests(_eval_tests) + + +def test_eval_formula_error_reporting(): + from patsy.parse_formula import _parsing_error_test + + parse_fn = lambda formula: ModelDesc.from_formula(formula) + _parsing_error_test(parse_fn, _eval_error_tests) + + +def test_formula_factor_origin(): + from patsy.origin import Origin + + desc = ModelDesc.from_formula("a + b") + assert desc.rhs_termlist[1].factors[0].origin == Origin("a + b", 0, 1) + assert desc.rhs_termlist[2].factors[0].origin == Origin("a + b", 4, 5) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/design_info.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/design_info.py new file mode 100644 index 0000000000000000000000000000000000000000..d94b97a8b790a4d7daa36c508a2c2139aecf11c2 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/design_info.py @@ -0,0 +1,1318 @@ +# This file is part of Patsy +# Copyright (C) 2011-2015 Nathaniel Smith +# See file LICENSE.txt for license information. + +# This file defines the main class for storing metadata about a model +# design. It also defines a 'value-added' design matrix type -- a subclass of +# ndarray that represents a design matrix and holds metadata about its +# columns. The intent is that these are useful and usable data structures +# even if you're not using *any* of the rest of patsy to actually build +# your matrices. + + +# XX TMP TODO: +# +# - update design_matrix_builders and build_design_matrices docs +# - add tests and docs for new design info stuff +# - consider renaming design_matrix_builders (and I guess +# build_design_matrices too). Ditto for highlevel dbuilder functions. + +# These are made available in the patsy.* namespace +__all__ = ["DesignInfo", "FactorInfo", "SubtermInfo", "DesignMatrix"] + +import warnings + +import numpy as np + +from patsy import PatsyError +from patsy.util import atleast_2d_column_default +from patsy.compat import OrderedDict +from patsy.util import ( + repr_pretty_delegate, + repr_pretty_impl, + safe_issubdtype, + no_pickling, + assert_no_pickling, +) +from patsy.constraint import linear_constraint +from patsy.contrasts import ContrastMatrix +from patsy.desc import ModelDesc, Term + + +class FactorInfo: + """A FactorInfo object is a simple class that provides some metadata about + the role of a factor within a model. :attr:`DesignInfo.factor_infos` is + a dictionary which maps factor objects to FactorInfo objects for each + factor in the model. + + .. versionadded:: 0.4.0 + + Attributes: + + .. attribute:: factor + + The factor object being described. + + .. attribute:: type + + The type of the factor -- either the string ``"numerical"`` or the + string ``"categorical"``. + + .. attribute:: state + + An opaque object which holds the state needed to evaluate this + factor on new data (e.g., for prediction). See + :meth:`factor_protocol.eval`. + + .. attribute:: num_columns + + For numerical factors, the number of columns this factor produces. For + categorical factors, this attribute will always be ``None``. + + .. attribute:: categories + + For categorical factors, a tuple of the possible categories this factor + takes on, in order. For numerical factors, this attribute will always be + ``None``. + """ + + def __init__(self, factor, type, state, num_columns=None, categories=None): + self.factor = factor + self.type = type + if self.type not in ["numerical", "categorical"]: + raise ValueError( + "FactorInfo.type must be " + "'numerical' or 'categorical', not %r" % (self.type,) + ) + self.state = state + if self.type == "numerical": + if not isinstance(num_columns, int): + raise ValueError( + "For numerical factors, num_columns must be an integer" + ) + if categories is not None: + raise ValueError("For numerical factors, categories must be None") + else: + assert self.type == "categorical" + if num_columns is not None: + raise ValueError("For categorical factors, num_columns must be None") + categories = tuple(categories) + self.num_columns = num_columns + self.categories = categories + + __repr__ = repr_pretty_delegate + + def _repr_pretty_(self, p, cycle): + assert not cycle + + class FactorState(object): + def __repr__(self): + return "" + + kwlist = [ + ("factor", self.factor), + ("type", self.type), + # Don't put the state in people's faces, it will + # just encourage them to pay attention to the + # contents :-). Plus it's a bunch of gobbledygook + # they don't care about. They can always look at + # self.state if they want to know... + ("state", FactorState()), + ] + if self.type == "numerical": + kwlist.append(("num_columns", self.num_columns)) + else: + kwlist.append(("categories", self.categories)) + repr_pretty_impl(p, self, [], kwlist) + + __getstate__ = no_pickling + + +def test_FactorInfo(): + fi1 = FactorInfo("asdf", "numerical", {"a": 1}, num_columns=10) + assert fi1.factor == "asdf" + assert fi1.state == {"a": 1} + assert fi1.type == "numerical" + assert fi1.num_columns == 10 + assert fi1.categories is None + + # smoke test + repr(fi1) + + fi2 = FactorInfo("asdf", "categorical", {"a": 2}, categories=["z", "j"]) + assert fi2.factor == "asdf" + assert fi2.state == {"a": 2} + assert fi2.type == "categorical" + assert fi2.num_columns is None + assert fi2.categories == ("z", "j") + + # smoke test + repr(fi2) + + import pytest + + pytest.raises(ValueError, FactorInfo, "asdf", "non-numerical", {}) + pytest.raises(ValueError, FactorInfo, "asdf", "numerical", {}) + + pytest.raises(ValueError, FactorInfo, "asdf", "numerical", {}, num_columns="asdf") + pytest.raises( + ValueError, FactorInfo, "asdf", "numerical", {}, num_columns=1, categories=1 + ) + + pytest.raises(TypeError, FactorInfo, "asdf", "categorical", {}) + pytest.raises(ValueError, FactorInfo, "asdf", "categorical", {}, num_columns=1) + pytest.raises(TypeError, FactorInfo, "asdf", "categorical", {}, categories=1) + + +class SubtermInfo: + """A SubtermInfo object is a simple metadata container describing a single + primitive interaction and how it is coded in our design matrix. Our final + design matrix is produced by coding each primitive interaction in order + from left to right, and then stacking the resulting columns. For each + :class:`Term`, we have one or more of these objects which describe how + that term is encoded. :attr:`DesignInfo.term_codings` is a dictionary + which maps term objects to lists of SubtermInfo objects. + + To code a primitive interaction, the following steps are performed: + + * Evaluate each factor on the provided data. + * Encode each factor into one or more proto-columns. For numerical + factors, these proto-columns are identical to whatever the factor + evaluates to; for categorical factors, they are encoded using a + specified contrast matrix. + * Form all pairwise, elementwise products between proto-columns generated + by different factors. (For example, if factor 1 generated proto-columns + A and B, and factor 2 generated proto-columns C and D, then our final + columns are ``A * C``, ``B * C``, ``A * D``, ``B * D``.) + * The resulting columns are stored directly into the final design matrix. + + Sometimes multiple primitive interactions are needed to encode a single + term; this occurs, for example, in the formula ``"1 + a:b"`` when ``a`` + and ``b`` are categorical. See :ref:`formulas-building` for full details. + + .. versionadded:: 0.4.0 + + Attributes: + + .. attribute:: factors + + The factors which appear in this subterm's interaction. + + .. attribute:: contrast_matrices + + A dict mapping factor objects to :class:`ContrastMatrix` objects, + describing how each categorical factor in this interaction is coded. + + .. attribute:: num_columns + + The number of design matrix columns which this interaction generates. + + """ + + def __init__(self, factors, contrast_matrices, num_columns): + self.factors = tuple(factors) + factor_set = frozenset(factors) + if not isinstance(contrast_matrices, dict): + raise ValueError("contrast_matrices must be dict") + for factor, contrast_matrix in contrast_matrices.items(): + if factor not in factor_set: + raise ValueError("Unexpected factor in contrast_matrices dict") + if not isinstance(contrast_matrix, ContrastMatrix): + raise ValueError( + "Expected a ContrastMatrix, not %r" % (contrast_matrix,) + ) + self.contrast_matrices = contrast_matrices + if not isinstance(num_columns, int): + raise ValueError("num_columns must be an integer") + self.num_columns = num_columns + + __repr__ = repr_pretty_delegate + + def _repr_pretty_(self, p, cycle): + assert not cycle + repr_pretty_impl( + p, + self, + [], + [ + ("factors", self.factors), + ("contrast_matrices", self.contrast_matrices), + ("num_columns", self.num_columns), + ], + ) + + __getstate__ = no_pickling + + +def test_SubtermInfo(): + cm = ContrastMatrix(np.ones((2, 2)), ["[1]", "[2]"]) + s = SubtermInfo(["a", "x"], {"a": cm}, 4) + assert s.factors == ("a", "x") + assert s.contrast_matrices == {"a": cm} + assert s.num_columns == 4 + + # smoke test + repr(s) + + import pytest + + pytest.raises(TypeError, SubtermInfo, 1, {}, 1) + pytest.raises(ValueError, SubtermInfo, ["a", "x"], 1, 1) + pytest.raises(ValueError, SubtermInfo, ["a", "x"], {"z": cm}, 1) + pytest.raises(ValueError, SubtermInfo, ["a", "x"], {"a": 1}, 1) + pytest.raises(ValueError, SubtermInfo, ["a", "x"], {}, 1.5) + + +class DesignInfo(object): + """A DesignInfo object holds metadata about a design matrix. + + This is the main object that Patsy uses to pass metadata about a design + matrix to statistical libraries, in order to allow further downstream + processing like intelligent tests, prediction on new data, etc. Usually + encountered as the `.design_info` attribute on design matrices. + + """ + + def __init__(self, column_names, factor_infos=None, term_codings=None): + self.column_name_indexes = OrderedDict( + zip(column_names, range(len(column_names))) + ) + + if (factor_infos is None) != (term_codings is None): + raise ValueError( + "Must specify either both or neither of factor_infos= and term_codings=" + ) + + self.factor_infos = factor_infos + self.term_codings = term_codings + + # factor_infos is a dict containing one entry for every factor + # mentioned in our terms + # and mapping each to FactorInfo object + if self.factor_infos is not None: + if not isinstance(self.factor_infos, dict): + raise ValueError("factor_infos should be a dict") + + if not isinstance(self.term_codings, OrderedDict): + raise ValueError("term_codings must be an OrderedDict") + for term, subterms in self.term_codings.items(): + if not isinstance(term, Term): + raise ValueError("expected a Term, not %r" % (term,)) + if not isinstance(subterms, list): + raise ValueError("term_codings must contain lists") + term_factors = set(term.factors) + for subterm in subterms: + if not isinstance(subterm, SubtermInfo): + raise ValueError("expected SubtermInfo, not %r" % (subterm,)) + if not term_factors.issuperset(subterm.factors): + raise ValueError("unexpected factors in subterm") + + all_factors = set() + for term in self.term_codings: + all_factors.update(term.factors) + if all_factors != set(self.factor_infos): + raise ValueError("Provided Term objects and factor_infos do not match") + for factor, factor_info in self.factor_infos.items(): + if not isinstance(factor_info, FactorInfo): + raise ValueError( + "expected FactorInfo object, not %r" % (factor_info,) + ) + if factor != factor_info.factor: + raise ValueError("mismatched factor_info.factor") + + for term, subterms in self.term_codings.items(): + for subterm in subterms: + exp_cols = 1 + cat_factors = set() + for factor in subterm.factors: + fi = self.factor_infos[factor] + if fi.type == "numerical": + exp_cols *= fi.num_columns + else: + assert fi.type == "categorical" + cm = subterm.contrast_matrices[factor].matrix + if cm.shape[0] != len(fi.categories): + raise ValueError( + "Mismatched contrast matrix " + "for factor %r" % (factor,) + ) + cat_factors.add(factor) + exp_cols *= cm.shape[1] + if cat_factors != set(subterm.contrast_matrices): + raise ValueError( + "Mismatch between contrast_matrices and categorical factors" + ) + if exp_cols != subterm.num_columns: + raise ValueError("Unexpected num_columns") + + if term_codings is None: + # Need to invent term information + self.term_slices = None + # We invent one term per column, with the same name as the column + term_names = column_names + slices = [slice(i, i + 1) for i in range(len(column_names))] + self.term_name_slices = OrderedDict(zip(term_names, slices)) + else: + # Need to derive term information from term_codings + self.term_slices = OrderedDict() + idx = 0 + for term, subterm_infos in self.term_codings.items(): + term_columns = 0 + for subterm_info in subterm_infos: + term_columns += subterm_info.num_columns + self.term_slices[term] = slice(idx, idx + term_columns) + idx += term_columns + if idx != len(self.column_names): + raise ValueError( + "mismatch between column_names and columns coded by given terms" + ) + self.term_name_slices = OrderedDict( + [(term.name(), slice_) for (term, slice_) in self.term_slices.items()] + ) + + # Guarantees: + # term_name_slices is never None + # The slices in term_name_slices are in order and exactly cover the + # whole range of columns. + # term_slices may be None + # If term_slices is not None, then its slices match the ones in + # term_name_slices. + assert self.term_name_slices is not None + if self.term_slices is not None: + assert list(self.term_slices.values()) == list( + self.term_name_slices.values() + ) + # These checks probably aren't necessary anymore now that we always + # generate the slices ourselves, but we'll leave them in just to be + # safe. + covered = 0 + for slice_ in self.term_name_slices.values(): + start, stop, step = slice_.indices(len(column_names)) + assert start == covered + assert step == 1 + covered = stop + assert covered == len(column_names) + # If there is any name overlap between terms and columns, they refer + # to the same columns. + for column_name, index in self.column_name_indexes.items(): + if column_name in self.term_name_slices: + slice_ = self.term_name_slices[column_name] + if slice_ != slice(index, index + 1): + raise ValueError("term/column name collision") + + __repr__ = repr_pretty_delegate + + def _repr_pretty_(self, p, cycle): + assert not cycle + repr_pretty_impl( + p, + self, + [self.column_names], + [("factor_infos", self.factor_infos), ("term_codings", self.term_codings)], + ) + + @property + def column_names(self): + "A list of the column names, in order." + return list(self.column_name_indexes) + + @property + def terms(self): + "A list of :class:`Terms`, in order, or else None." + if self.term_slices is None: + return None + return list(self.term_slices) + + @property + def term_names(self): + "A list of terms, in order." + return list(self.term_name_slices) + + @property + def builder(self): + ".. deprecated:: 0.4.0" + warnings.warn( + DeprecationWarning( + "The DesignInfo.builder attribute is deprecated starting in " + "patsy v0.4.0; distinct builder objects have been eliminated " + "and design_info.builder is now just a long-winded way of " + "writing 'design_info' (i.e. the .builder attribute just " + "returns self)" + ), + stacklevel=2, + ) + return self + + @property + def design_info(self): + ".. deprecated:: 0.4.0" + warnings.warn( + DeprecationWarning( + "Starting in patsy v0.4.0, the DesignMatrixBuilder class has " + "been merged into the DesignInfo class. So there's no need to " + "use builder.design_info to access the DesignInfo; 'builder' " + "already *is* a DesignInfo." + ), + stacklevel=2, + ) + return self + + def slice(self, columns_specifier): + """Locate a subset of design matrix columns, specified symbolically. + + A patsy design matrix has two levels of structure: the individual + columns (which are named), and the :ref:`terms ` in + the formula that generated those columns. This is a one-to-many + relationship: a single term may span several columns. This method + provides a user-friendly API for locating those columns. + + (While we talk about columns here, this is probably most useful for + indexing into other arrays that are derived from the design matrix, + such as regression coefficients or covariance matrices.) + + The `columns_specifier` argument can take a number of forms: + + * A term name + * A column name + * A :class:`Term` object + * An integer giving a raw index + * A raw slice object + + In all cases, a Python :func:`slice` object is returned, which can be + used directly for indexing. + + Example:: + + y, X = dmatrices("y ~ a", demo_data("y", "a", nlevels=3)) + betas = np.linalg.lstsq(X, y)[0] + a_betas = betas[X.design_info.slice("a")] + + (If you want to look up a single individual column by name, use + ``design_info.column_name_indexes[name]``.) + """ + if isinstance(columns_specifier, slice): + return columns_specifier + if np.issubdtype(type(columns_specifier), np.integer): + return slice(columns_specifier, columns_specifier + 1) + if self.term_slices is not None and columns_specifier in self.term_slices: + return self.term_slices[columns_specifier] + if columns_specifier in self.term_name_slices: + return self.term_name_slices[columns_specifier] + if columns_specifier in self.column_name_indexes: + idx = self.column_name_indexes[columns_specifier] + return slice(idx, idx + 1) + raise PatsyError("unknown column specified '%s'" % (columns_specifier,)) + + def linear_constraint(self, constraint_likes): + """Construct a linear constraint in matrix form from a (possibly + symbolic) description. + + Possible inputs: + + * A dictionary which is taken as a set of equality constraint. Keys + can be either string column names, or integer column indexes. + * A string giving a arithmetic expression referring to the matrix + columns by name. + * A list of such strings which are ANDed together. + * A tuple (A, b) where A and b are array_likes, and the constraint is + Ax = b. If necessary, these will be coerced to the proper + dimensionality by appending dimensions with size 1. + + The string-based language has the standard arithmetic operators, / * + + - and parentheses, plus "=" is used for equality and "," is used to + AND together multiple constraint equations within a string. You can + If no = appears in some expression, then that expression is assumed to + be equal to zero. Division is always float-based, even if + ``__future__.true_division`` isn't in effect. + + Returns a :class:`LinearConstraint` object. + + Examples:: + + di = DesignInfo(["x1", "x2", "x3"]) + + # Equivalent ways to write x1 == 0: + di.linear_constraint({"x1": 0}) # by name + di.linear_constraint({0: 0}) # by index + di.linear_constraint("x1 = 0") # string based + di.linear_constraint("x1") # can leave out "= 0" + di.linear_constraint("2 * x1 = (x1 + 2 * x1) / 3") + di.linear_constraint(([1, 0, 0], 0)) # constraint matrices + + # Equivalent ways to write x1 == 0 and x3 == 10 + di.linear_constraint({"x1": 0, "x3": 10}) + di.linear_constraint({0: 0, 2: 10}) + di.linear_constraint({0: 0, "x3": 10}) + di.linear_constraint("x1 = 0, x3 = 10") + di.linear_constraint("x1, x3 = 10") + di.linear_constraint(["x1", "x3 = 0"]) # list of strings + di.linear_constraint("x1 = 0, x3 - 10 = x1") + di.linear_constraint([[1, 0, 0], [0, 0, 1]], [0, 10]) + + # You can also chain together equalities, just like Python: + di.linear_constraint("x1 = x2 = 3") + """ + return linear_constraint(constraint_likes, self.column_names) + + def describe(self): + """Returns a human-readable string describing this design info. + + Example: + + .. ipython:: + + In [1]: y, X = dmatrices("y ~ x1 + x2", demo_data("y", "x1", "x2")) + + In [2]: y.design_info.describe() + Out[2]: 'y' + + In [3]: X.design_info.describe() + Out[3]: '1 + x1 + x2' + + .. warning:: + + There is no guarantee that the strings returned by this function + can be parsed as formulas, or that if they can be parsed as a + formula that they will produce a model equivalent to the one you + started with. This function produces a best-effort description + intended for humans to read. + + """ + + names = [] + for name in self.term_names: + if name == "Intercept": + names.append("1") + else: + names.append(name) + return " + ".join(names) + + def subset(self, which_terms): + """Create a new :class:`DesignInfo` for design matrices that contain a + subset of the terms that the current :class:`DesignInfo` does. + + For example, if ``design_info`` has terms ``x``, ``y``, and ``z``, + then:: + + design_info2 = design_info.subset(["x", "z"]) + + will return a new DesignInfo that can be used to construct design + matrices with only the columns corresponding to the terms ``x`` and + ``z``. After we do this, then in general these two expressions will + return the same thing (here we assume that ``x``, ``y``, and ``z`` + each generate a single column of the output):: + + build_design_matrix([design_info], data)[0][:, [0, 2]] + build_design_matrix([design_info2], data)[0] + + However, a critical difference is that in the second case, ``data`` + need not contain any values for ``y``. This is very useful when doing + prediction using a subset of a model, in which situation R usually + forces you to specify dummy values for ``y``. + + If using a formula to specify the terms to include, remember that like + any formula, the intercept term will be included by default, so use + ``0`` or ``-1`` in your formula if you want to avoid this. + + This method can also be used to reorder the terms in your design + matrix, in case you want to do that for some reason. I can't think of + any. + + Note that this method will generally *not* produce the same result as + creating a new model directly. Consider these DesignInfo objects:: + + design1 = dmatrix("1 + C(a)", data) + design2 = design1.subset("0 + C(a)") + design3 = dmatrix("0 + C(a)", data) + + Here ``design2`` and ``design3`` will both produce design matrices + that contain an encoding of ``C(a)`` without any intercept term. But + ``design3`` uses a full-rank encoding for the categorical term + ``C(a)``, while ``design2`` uses the same reduced-rank encoding as + ``design1``. + + :arg which_terms: The terms which should be kept in the new + :class:`DesignMatrixBuilder`. If this is a string, then it is parsed + as a formula, and then the names of the resulting terms are taken as + the terms to keep. If it is a list, then it can contain a mixture of + term names (as strings) and :class:`Term` objects. + + .. versionadded: 0.2.0 + New method on the class DesignMatrixBuilder. + + .. versionchanged: 0.4.0 + Moved from DesignMatrixBuilder to DesignInfo, as part of the + removal of DesignMatrixBuilder. + + """ + if isinstance(which_terms, str): + desc = ModelDesc.from_formula(which_terms) + if desc.lhs_termlist: + raise PatsyError("right-hand-side-only formula required") + which_terms = [term.name() for term in desc.rhs_termlist] + + if self.term_codings is None: + # This is a minimal DesignInfo + # If the name is unknown we just let the KeyError escape + new_names = [] + for t in which_terms: + new_names += self.column_names[self.term_name_slices[t]] + return DesignInfo(new_names) + else: + term_name_to_term = {} + for term in self.term_codings: + term_name_to_term[term.name()] = term + + new_column_names = [] + new_factor_infos = {} + new_term_codings = OrderedDict() + for name_or_term in which_terms: + term = term_name_to_term.get(name_or_term, name_or_term) + # If the name is unknown we just let the KeyError escape + s = self.term_slices[term] + new_column_names += self.column_names[s] + for f in term.factors: + new_factor_infos[f] = self.factor_infos[f] + new_term_codings[term] = self.term_codings[term] + return DesignInfo( + new_column_names, + factor_infos=new_factor_infos, + term_codings=new_term_codings, + ) + + @classmethod + def from_array(cls, array_like, default_column_prefix="column"): + """Find or construct a DesignInfo appropriate for a given array_like. + + If the input `array_like` already has a ``.design_info`` + attribute, then it will be returned. Otherwise, a new DesignInfo + object will be constructed, using names either taken from the + `array_like` (e.g., for a pandas DataFrame with named columns), or + constructed using `default_column_prefix`. + + This is how :func:`dmatrix` (for example) creates a DesignInfo object + if an arbitrary matrix is passed in. + + :arg array_like: An ndarray or pandas container. + :arg default_column_prefix: If it's necessary to invent column names, + then this will be used to construct them. + :returns: a DesignInfo object + """ + if hasattr(array_like, "design_info") and isinstance( + array_like.design_info, cls + ): + return array_like.design_info + arr = atleast_2d_column_default(array_like, preserve_pandas=True) + if arr.ndim > 2: + raise ValueError("design matrix can't have >2 dimensions") + columns = getattr(arr, "columns", range(arr.shape[1])) + if hasattr(columns, "dtype") and not safe_issubdtype(columns.dtype, np.integer): + column_names = [str(obj) for obj in columns] + else: + column_names = ["%s%s" % (default_column_prefix, i) for i in columns] + return DesignInfo(column_names) + + __getstate__ = no_pickling + + +def test_DesignInfo(): + import pytest + + class _MockFactor(object): + def __init__(self, name): + self._name = name + + def name(self): + return self._name + + f_x = _MockFactor("x") + f_y = _MockFactor("y") + t_x = Term([f_x]) + t_y = Term([f_y]) + factor_infos = { + f_x: FactorInfo(f_x, "numerical", {}, num_columns=3), + f_y: FactorInfo(f_y, "numerical", {}, num_columns=1), + } + term_codings = OrderedDict( + [(t_x, [SubtermInfo([f_x], {}, 3)]), (t_y, [SubtermInfo([f_y], {}, 1)])] + ) + di = DesignInfo(["x1", "x2", "x3", "y"], factor_infos, term_codings) + assert di.column_names == ["x1", "x2", "x3", "y"] + assert di.term_names == ["x", "y"] + assert di.terms == [t_x, t_y] + assert di.column_name_indexes == {"x1": 0, "x2": 1, "x3": 2, "y": 3} + assert di.term_name_slices == {"x": slice(0, 3), "y": slice(3, 4)} + assert di.term_slices == {t_x: slice(0, 3), t_y: slice(3, 4)} + assert di.describe() == "x + y" + + assert di.slice(1) == slice(1, 2) + assert di.slice("x1") == slice(0, 1) + assert di.slice("x2") == slice(1, 2) + assert di.slice("x3") == slice(2, 3) + assert di.slice("x") == slice(0, 3) + assert di.slice(t_x) == slice(0, 3) + assert di.slice("y") == slice(3, 4) + assert di.slice(t_y) == slice(3, 4) + assert di.slice(slice(2, 4)) == slice(2, 4) + pytest.raises(PatsyError, di.slice, "asdf") + + # smoke test + repr(di) + + assert_no_pickling(di) + + # One without term objects + di = DesignInfo(["a1", "a2", "a3", "b"]) + assert di.column_names == ["a1", "a2", "a3", "b"] + assert di.term_names == ["a1", "a2", "a3", "b"] + assert di.terms is None + assert di.column_name_indexes == {"a1": 0, "a2": 1, "a3": 2, "b": 3} + assert di.term_name_slices == { + "a1": slice(0, 1), + "a2": slice(1, 2), + "a3": slice(2, 3), + "b": slice(3, 4), + } + assert di.term_slices is None + assert di.describe() == "a1 + a2 + a3 + b" + + assert di.slice(1) == slice(1, 2) + assert di.slice("a1") == slice(0, 1) + assert di.slice("a2") == slice(1, 2) + assert di.slice("a3") == slice(2, 3) + assert di.slice("b") == slice(3, 4) + + # Check intercept handling in describe() + assert DesignInfo(["Intercept", "a", "b"]).describe() == "1 + a + b" + + # Failure modes + # must specify either both or neither of factor_infos and term_codings: + pytest.raises( + ValueError, DesignInfo, ["x1", "x2", "x3", "y"], factor_infos=factor_infos + ) + pytest.raises( + ValueError, DesignInfo, ["x1", "x2", "x3", "y"], term_codings=term_codings + ) + # factor_infos must be a dict + pytest.raises( + ValueError, + DesignInfo, + ["x1", "x2", "x3", "y"], + list(factor_infos), + term_codings, + ) + # wrong number of column names: + pytest.raises( + ValueError, + DesignInfo, + ["x1", "x2", "x3", "y1", "y2"], + factor_infos, + term_codings, + ) + pytest.raises( + ValueError, DesignInfo, ["x1", "x2", "x3"], factor_infos, term_codings + ) + # name overlap problems + pytest.raises( + ValueError, DesignInfo, ["x1", "x2", "y", "y2"], factor_infos, term_codings + ) + # duplicate name + pytest.raises( + ValueError, DesignInfo, ["x1", "x1", "x1", "y"], factor_infos, term_codings + ) + + # f_y is in factor_infos, but not mentioned in any term + term_codings_x_only = OrderedDict(term_codings) + del term_codings_x_only[t_y] + pytest.raises( + ValueError, DesignInfo, ["x1", "x2", "x3"], factor_infos, term_codings_x_only + ) + + # f_a is in a term, but not in factor_infos + f_a = _MockFactor("a") + t_a = Term([f_a]) + term_codings_with_a = OrderedDict(term_codings) + term_codings_with_a[t_a] = [SubtermInfo([f_a], {}, 1)] + pytest.raises( + ValueError, + DesignInfo, + ["x1", "x2", "x3", "y", "a"], + factor_infos, + term_codings_with_a, + ) + + # bad factor_infos + not_factor_infos = dict(factor_infos) + not_factor_infos[f_x] = "what is this I don't even" + pytest.raises( + ValueError, DesignInfo, ["x1", "x2", "x3", "y"], not_factor_infos, term_codings + ) + + mismatch_factor_infos = dict(factor_infos) + mismatch_factor_infos[f_x] = FactorInfo(f_a, "numerical", {}, num_columns=3) + pytest.raises( + ValueError, + DesignInfo, + ["x1", "x2", "x3", "y"], + mismatch_factor_infos, + term_codings, + ) + + # bad term_codings + pytest.raises( + ValueError, + DesignInfo, + ["x1", "x2", "x3", "y"], + factor_infos, + dict(term_codings), + ) + + not_term_codings = OrderedDict(term_codings) + not_term_codings["this is a string"] = term_codings[t_x] + pytest.raises( + ValueError, DesignInfo, ["x1", "x2", "x3", "y"], factor_infos, not_term_codings + ) + + non_list_term_codings = OrderedDict(term_codings) + non_list_term_codings[t_y] = tuple(term_codings[t_y]) + pytest.raises( + ValueError, + DesignInfo, + ["x1", "x2", "x3", "y"], + factor_infos, + non_list_term_codings, + ) + + non_subterm_term_codings = OrderedDict(term_codings) + non_subterm_term_codings[t_y][0] = "not a SubtermInfo" + pytest.raises( + ValueError, + DesignInfo, + ["x1", "x2", "x3", "y"], + factor_infos, + non_subterm_term_codings, + ) + + bad_subterm = OrderedDict(term_codings) + # f_x is a factor in this model, but it is not a factor in t_y + term_codings[t_y][0] = SubtermInfo([f_x], {}, 1) + pytest.raises( + ValueError, DesignInfo, ["x1", "x2", "x3", "y"], factor_infos, bad_subterm + ) + + # contrast matrix has wrong number of rows + factor_codings_a = { + f_a: FactorInfo(f_a, "categorical", {}, categories=["a1", "a2"]) + } + term_codings_a_bad_rows = OrderedDict( + [ + ( + t_a, + [ + SubtermInfo( + [f_a], {f_a: ContrastMatrix(np.ones((3, 2)), ["[1]", "[2]"])}, 2 + ) + ], + ) + ] + ) + pytest.raises( + ValueError, + DesignInfo, + ["a[1]", "a[2]"], + factor_codings_a, + term_codings_a_bad_rows, + ) + + # have a contrast matrix for a non-categorical factor + t_ax = Term([f_a, f_x]) + factor_codings_ax = { + f_a: FactorInfo(f_a, "categorical", {}, categories=["a1", "a2"]), + f_x: FactorInfo(f_x, "numerical", {}, num_columns=2), + } + term_codings_ax_extra_cm = OrderedDict( + [ + ( + t_ax, + [ + SubtermInfo( + [f_a, f_x], + { + f_a: ContrastMatrix(np.ones((2, 2)), ["[1]", "[2]"]), + f_x: ContrastMatrix(np.ones((2, 2)), ["[1]", "[2]"]), + }, + 4, + ) + ], + ) + ] + ) + pytest.raises( + ValueError, + DesignInfo, + ["a[1]:x[1]", "a[2]:x[1]", "a[1]:x[2]", "a[2]:x[2]"], + factor_codings_ax, + term_codings_ax_extra_cm, + ) + + # no contrast matrix for a categorical factor + term_codings_ax_missing_cm = OrderedDict([(t_ax, [SubtermInfo([f_a, f_x], {}, 4)])]) + # This actually fails before it hits the relevant check with a KeyError, + # but that's okay... the previous test still exercises the check. + pytest.raises( + (ValueError, KeyError), + DesignInfo, + ["a[1]:x[1]", "a[2]:x[1]", "a[1]:x[2]", "a[2]:x[2]"], + factor_codings_ax, + term_codings_ax_missing_cm, + ) + + # subterm num_columns doesn't match the value computed from the individual + # factors + term_codings_ax_wrong_subterm_columns = OrderedDict( + [ + ( + t_ax, + [ + SubtermInfo( + [f_a, f_x], + {f_a: ContrastMatrix(np.ones((2, 3)), ["[1]", "[2]", "[3]"])}, + # should be 2 * 3 = 6 + 5, + ) + ], + ) + ] + ) + pytest.raises( + ValueError, + DesignInfo, + ["a[1]:x[1]", "a[2]:x[1]", "a[3]:x[1]", "a[1]:x[2]", "a[2]:x[2]", "a[3]:x[2]"], + factor_codings_ax, + term_codings_ax_wrong_subterm_columns, + ) + + +def test_DesignInfo_from_array(): + di = DesignInfo.from_array([1, 2, 3]) + assert di.column_names == ["column0"] + di2 = DesignInfo.from_array([[1, 2], [2, 3], [3, 4]]) + assert di2.column_names == ["column0", "column1"] + di3 = DesignInfo.from_array([1, 2, 3], default_column_prefix="x") + assert di3.column_names == ["x0"] + di4 = DesignInfo.from_array([[1, 2], [2, 3], [3, 4]], default_column_prefix="x") + assert di4.column_names == ["x0", "x1"] + m = DesignMatrix([1, 2, 3], di3) + assert DesignInfo.from_array(m) is di3 + # But weird objects are ignored + m.design_info = "asdf" + di_weird = DesignInfo.from_array(m) + assert di_weird.column_names == ["column0"] + + import pytest + + pytest.raises(ValueError, DesignInfo.from_array, np.ones((2, 2, 2))) + + from patsy.util import have_pandas + + if have_pandas: + import pandas + + # with named columns + di5 = DesignInfo.from_array(pandas.DataFrame([[1, 2]], columns=["a", "b"])) + assert di5.column_names == ["a", "b"] + # with irregularly numbered columns + di6 = DesignInfo.from_array(pandas.DataFrame([[1, 2]], columns=[0, 10])) + assert di6.column_names == ["column0", "column10"] + # with .design_info attr + df = pandas.DataFrame([[1, 2]]) + df.design_info = di6 + assert DesignInfo.from_array(df) is di6 + + +def test_DesignInfo_linear_constraint(): + di = DesignInfo(["a1", "a2", "a3", "b"]) + con = di.linear_constraint(["2 * a1 = b + 1", "a3"]) + assert con.variable_names == ["a1", "a2", "a3", "b"] + assert np.all(con.coefs == [[2, 0, 0, -1], [0, 0, 1, 0]]) + assert np.all(con.constants == [[1], [0]]) + + +def test_DesignInfo_deprecated_attributes(): + d = DesignInfo(["a1", "a2"]) + + def check(attr): + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + assert getattr(d, attr) is d + assert len(w) == 1 + assert w[0].category is DeprecationWarning + + check("builder") + check("design_info") + + +# Idea: format with a reasonable amount of precision, then if that turns out +# to be higher than necessary, remove as many zeros as we can. But only do +# this while we can do it to *all* the ordinarily-formatted numbers, to keep +# decimal points aligned. +def _format_float_column(precision, col): + format_str = "%." + str(precision) + "f" + assert col.ndim == 1 + # We don't want to look at numbers like "1e-5" or "nan" when stripping. + simple_float_chars = set("+-0123456789.") + col_strs = np.array([format_str % (x,) for x in col], dtype=object) + # Really every item should have a decimal, but just in case, we don't want + # to strip zeros off the end of "10" or something like that. + mask = np.array( + [ + simple_float_chars.issuperset(col_str) and "." in col_str + for col_str in col_strs + ] + ) + mask_idxes = np.nonzero(mask)[0] + strip_char = "0" + if np.any(mask): + while True: + if np.all([s.endswith(strip_char) for s in col_strs[mask]]): + for idx in mask_idxes: + col_strs[idx] = col_strs[idx][:-1] + else: + if strip_char == "0": + strip_char = "." + else: + break + return col_strs + + +def test__format_float_column(): + def t(precision, numbers, expected): + got = _format_float_column(precision, np.asarray(numbers)) + print(got, expected) + assert np.array_equal(got, expected) + + # This acts weird on old python versions (e.g. it can be "-nan"), so don't + # hardcode it: + nan_string = "%.3f" % (np.nan,) + t(3, [1, 2.1234, 2.1239, np.nan], ["1.000", "2.123", "2.124", nan_string]) + t(3, [1, 2, 3, np.nan], ["1", "2", "3", nan_string]) + t(3, [1.0001, 2, 3, np.nan], ["1", "2", "3", nan_string]) + t(4, [1.0001, 2, 3, np.nan], ["1.0001", "2.0000", "3.0000", nan_string]) + + +# http://docs.scipy.org/doc/numpy/user/basics.subclassing.html#slightly-more-realistic-example-attribute-added-to-existing-array +class DesignMatrix(np.ndarray): + """A simple numpy array subclass that carries design matrix metadata. + + .. attribute:: design_info + + A :class:`DesignInfo` object containing metadata about this design + matrix. + + This class also defines a fancy __repr__ method with labeled + columns. Otherwise it is identical to a regular numpy ndarray. + + .. warning:: + + You should never check for this class using + :func:`isinstance`. Limitations of the numpy API mean that it is + impossible to prevent the creation of numpy arrays that have type + DesignMatrix, but that are not actually design matrices (and such + objects will behave like regular ndarrays in every way). Instead, check + for the presence of a ``.design_info`` attribute -- this will be + present only on "real" DesignMatrix objects. + """ + + def __new__(cls, input_array, design_info=None, default_column_prefix="column"): + """Create a DesignMatrix, or cast an existing matrix to a DesignMatrix. + + A call like:: + + DesignMatrix(my_array) + + will convert an arbitrary array_like object into a DesignMatrix. + + The return from this function is guaranteed to be a two-dimensional + ndarray with a real-valued floating point dtype, and a + ``.design_info`` attribute which matches its shape. If the + `design_info` argument is not given, then one is created via + :meth:`DesignInfo.from_array` using the given + `default_column_prefix`. + + Depending on the input array, it is possible this will pass through + its input unchanged, or create a view. + """ + # Pass through existing DesignMatrixes. The design_info check is + # necessary because numpy is sort of annoying and cannot be stopped + # from turning non-design-matrix arrays into DesignMatrix + # instances. (E.g., my_dm.diagonal() will return a DesignMatrix + # object, but one without a design_info attribute.) + if isinstance(input_array, DesignMatrix) and hasattr( + input_array, "design_info" + ): + return input_array + self = atleast_2d_column_default(input_array).view(cls) + # Upcast integer to floating point + if safe_issubdtype(self.dtype, np.integer): + self = np.asarray(self, dtype=float).view(cls) + if self.ndim > 2: + raise ValueError("DesignMatrix must be 2d") + assert self.ndim == 2 + if design_info is None: + design_info = DesignInfo.from_array(self, default_column_prefix) + if len(design_info.column_names) != self.shape[1]: + raise ValueError( + "wrong number of column names for design matrix " + "(got %s, wanted %s)" % (len(design_info.column_names), self.shape[1]) + ) + self.design_info = design_info + if not safe_issubdtype(self.dtype, np.floating): + raise ValueError("design matrix must be real-valued floating point") + return self + + __repr__ = repr_pretty_delegate + + def _repr_pretty_(self, p, cycle): + if not hasattr(self, "design_info"): + # Not a real DesignMatrix + p.pretty(np.asarray(self)) + return + assert not cycle + + # XX: could try calculating width of the current terminal window: + # http://stackoverflow.com/questions/566746/how-to-get-console-window-width-in-python + # sadly it looks like ipython does not actually pass this information + # in, even if we use _repr_pretty_ -- the pretty-printer object has a + # fixed width it always uses. (As of IPython 0.12.) + MAX_TOTAL_WIDTH = 78 + SEP = 2 + INDENT = 2 + MAX_ROWS = 30 + PRECISION = 5 + + names = self.design_info.column_names + column_name_widths = [len(name) for name in names] + min_total_width = ( + INDENT + SEP * (self.shape[1] - 1) + np.sum(column_name_widths) + ) + if min_total_width <= MAX_TOTAL_WIDTH: + printable_part = np.asarray(self)[:MAX_ROWS, :] + formatted_cols = [ + _format_float_column(PRECISION, printable_part[:, i]) + for i in range(self.shape[1]) + ] + + def max_width(col): + assert col.ndim == 1 + if not col.shape[0]: + return 0 + else: + return max([len(s) for s in col]) + + column_num_widths = [max_width(col) for col in formatted_cols] + column_widths = [ + max(name_width, num_width) + for (name_width, num_width) in zip( + column_name_widths, column_num_widths + ) + ] + total_width = INDENT + SEP * (self.shape[1] - 1) + np.sum(column_widths) + print_numbers = total_width < MAX_TOTAL_WIDTH + else: + print_numbers = False + + p.begin_group(INDENT, "DesignMatrix with shape %s" % (self.shape,)) + p.breakable("\n" + " " * p.indentation) + if print_numbers: + # We can fit the numbers on the screen + sep = " " * SEP + # list() is for Py3 compatibility + for row in [names] + list(zip(*formatted_cols)): + cells = [cell.rjust(width) for (width, cell) in zip(column_widths, row)] + p.text(sep.join(cells)) + p.text("\n" + " " * p.indentation) + if MAX_ROWS < self.shape[0]: + p.text("[%s rows omitted]" % (self.shape[0] - MAX_ROWS,)) + p.text("\n" + " " * p.indentation) + else: + p.begin_group(2, "Columns:") + p.breakable("\n" + " " * p.indentation) + p.pretty(names) + p.end_group(2, "") + p.breakable("\n" + " " * p.indentation) + + p.begin_group(2, "Terms:") + p.breakable("\n" + " " * p.indentation) + for term_name, span in self.design_info.term_name_slices.items(): + if span.start != 0: + p.breakable(", ") + p.pretty(term_name) + if span.stop - span.start == 1: + coltext = "column %s" % (span.start,) + else: + coltext = "columns %s:%s" % (span.start, span.stop) + p.text(" (%s)" % (coltext,)) + p.end_group(2, "") + + if not print_numbers or self.shape[0] > MAX_ROWS: + # some data was not shown + p.breakable("\n" + " " * p.indentation) + p.text("(to view full data, use np.asarray(this_obj))") + + p.end_group(INDENT, "") + + # No __array_finalize__ method, because we don't want slices of this + # object to keep the design_info (they may have different columns!), or + # anything fancy like that. + + __reduce__ = no_pickling + + +def test_design_matrix(): + import pytest + + di = DesignInfo(["a1", "a2", "a3", "b"]) + mm = DesignMatrix([[12, 14, 16, 18]], di) + assert mm.design_info.column_names == ["a1", "a2", "a3", "b"] + + bad_di = DesignInfo(["a1"]) + pytest.raises(ValueError, DesignMatrix, [[12, 14, 16, 18]], bad_di) + + mm2 = DesignMatrix([[12, 14, 16, 18]]) + assert mm2.design_info.column_names == ["column0", "column1", "column2", "column3"] + + mm3 = DesignMatrix([12, 14, 16, 18]) + assert mm3.shape == (4, 1) + + # DesignMatrix always has exactly 2 dimensions + pytest.raises(ValueError, DesignMatrix, [[[1]]]) + + # DesignMatrix constructor passes through existing DesignMatrixes + mm4 = DesignMatrix(mm) + assert mm4 is mm + # But not if they are really slices: + mm5 = DesignMatrix(mm.diagonal()) + assert mm5 is not mm + + mm6 = DesignMatrix([[12, 14, 16, 18]], default_column_prefix="x") + assert mm6.design_info.column_names == ["x0", "x1", "x2", "x3"] + + assert_no_pickling(mm6) + + # Only real-valued matrices can be DesignMatrixs + pytest.raises(ValueError, DesignMatrix, [1, 2, 3j]) + pytest.raises(ValueError, DesignMatrix, ["a", "b", "c"]) + pytest.raises(ValueError, DesignMatrix, [1, 2, object()]) + + # Just smoke tests + repr(mm) + repr(DesignMatrix(np.arange(100))) + repr(DesignMatrix(np.arange(100) * 2.0)) + repr(mm[1:, :]) + repr(DesignMatrix(np.arange(100).reshape((1, 100)))) + repr(DesignMatrix([np.nan, np.inf])) + repr(DesignMatrix([np.nan, 0, 1e20, 20.5])) + # handling of zero-size matrices + repr(DesignMatrix(np.zeros((1, 0)))) + repr(DesignMatrix(np.zeros((0, 1)))) + repr(DesignMatrix(np.zeros((0, 0)))) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/eval.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/eval.py new file mode 100644 index 0000000000000000000000000000000000000000..9d1fba021dc175175a766fcae5a936cfd694cf54 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/eval.py @@ -0,0 +1,853 @@ +# This file is part of Patsy +# Copyright (C) 2011 Nathaniel Smith +# See file LICENSE.txt for license information. + +# Utilities that require an over-intimate knowledge of Python's execution +# environment. + +# NB: if you add any __future__ imports to this file then you'll have to +# adjust the tests that deal with checking the caller's execution environment +# for __future__ flags! + +# These are made available in the patsy.* namespace +__all__ = ["EvalEnvironment", "EvalFactor"] + +import __future__ +import sys +import inspect +import tokenize +import ast +import numbers +from patsy import PatsyError +from patsy.util import PushbackAdapter, no_pickling, assert_no_pickling +from patsy.tokens import pretty_untokenize, normalize_token_spacing, python_tokenize +from patsy.compat import call_and_wrap_exc + + +def _all_future_flags(): + flags = 0 + for feature_name in __future__.all_feature_names: + feature = getattr(__future__, feature_name) + mr = feature.getMandatoryRelease() + # None means a planned feature was dropped, or at least postponed + # without a final decision; see, for example, + # https://docs.python.org/3.11/library/__future__.html#id2. + if mr is None or mr > sys.version_info: + flags |= feature.compiler_flag + return flags + + +_ALL_FUTURE_FLAGS = _all_future_flags() + + +# This is just a minimal dict-like object that does lookup in a 'stack' of +# dicts -- first it checks the first, then the second, etc. Assignments go +# into an internal, zeroth dict. +class VarLookupDict(object): + def __init__(self, dicts): + self._dicts = [{}] + list(dicts) + + def __getitem__(self, key): + for d in self._dicts: + try: + return d[key] + except KeyError: + pass + raise KeyError(key) + + def __setitem__(self, key, value): + self._dicts[0][key] = value + + def __contains__(self, key): + try: + self[key] + except KeyError: + return False + else: + return True + + def get(self, key, default=None): + try: + return self[key] + except KeyError: + return default + + def __repr__(self): + return "%s(%r)" % (self.__class__.__name__, self._dicts) + + __getstate__ = no_pickling + + +def test_VarLookupDict(): + d1 = {"a": 1} + d2 = {"a": 2, "b": 3} + ds = VarLookupDict([d1, d2]) + assert ds["a"] == 1 + assert ds["b"] == 3 + assert "a" in ds + assert "c" not in ds + import pytest + + pytest.raises(KeyError, ds.__getitem__, "c") + ds["a"] = 10 + assert ds["a"] == 10 + assert d1["a"] == 1 + assert ds.get("c") is None + assert isinstance(repr(ds), str) + + assert_no_pickling(ds) + + +def ast_names(code): + """Iterator that yields all the (ast) names in a Python expression. + + :arg code: A string containing a Python expression. + """ + # Syntax that allows new name bindings to be introduced is tricky to + # handle here, so we just refuse to do so. + disallowed_ast_nodes = (ast.Lambda, ast.ListComp, ast.GeneratorExp) + disallowed_ast_nodes += (ast.DictComp, ast.SetComp) + + for node in ast.walk(ast.parse(code)): + if isinstance(node, disallowed_ast_nodes): + raise PatsyError( + "Lambda, list/dict/set comprehension, generator " + "expression in patsy formula not currently supported." + ) + if isinstance(node, ast.Name): + yield node.id + + +def test_ast_names(): + test_data = [ + ("np.log(x)", ["np", "x"]), + ("x", ["x"]), + ("center(x + 1)", ["center", "x"]), + ("dt.date.dt.month", ["dt"]), + ] + for code, expected in test_data: + assert set(ast_names(code)) == set(expected) + + +def test_ast_names_disallowed_nodes(): + import pytest + + def list_ast_names(code): + return list(ast_names(code)) + + pytest.raises(PatsyError, list_ast_names, "lambda x: x + y") + pytest.raises(PatsyError, list_ast_names, "[x + 1 for x in range(10)]") + pytest.raises(PatsyError, list_ast_names, "(x + 1 for x in range(10))") + pytest.raises(PatsyError, list_ast_names, "{x: True for x in range(10)}") + pytest.raises(PatsyError, list_ast_names, "{x + 1 for x in range(10)}") + + +class EvalEnvironment(object): + """Represents a Python execution environment. + + Encapsulates a namespace for variable lookup and set of __future__ + flags.""" + + def __init__(self, namespaces, flags=0): + assert not flags & ~_ALL_FUTURE_FLAGS + self._namespaces = list(namespaces) + self.flags = flags + + @property + def namespace(self): + """A dict-like object that can be used to look up variables accessible + from the encapsulated environment.""" + return VarLookupDict(self._namespaces) + + def with_outer_namespace(self, outer_namespace): + """Return a new EvalEnvironment with an extra namespace added. + + This namespace will be used only for variables that are not found in + any existing namespace, i.e., it is "outside" them all.""" + return self.__class__(self._namespaces + [outer_namespace], self.flags) + + def eval(self, expr, source_name="", inner_namespace={}): + """Evaluate some Python code in the encapsulated environment. + + :arg expr: A string containing a Python expression. + :arg source_name: A name for this string, for use in tracebacks. + :arg inner_namespace: A dict-like object that will be checked first + when `expr` attempts to access any variables. + :returns: The value of `expr`. + """ + code = compile(expr, source_name, "eval", self.flags, False) + return eval(code, {}, VarLookupDict([inner_namespace] + self._namespaces)) + + @classmethod + def capture(cls, eval_env=0, reference=0): + """Capture an execution environment from the stack. + + If `eval_env` is already an :class:`EvalEnvironment`, it is returned + unchanged. Otherwise, we walk up the stack by ``eval_env + reference`` + steps and capture that function's evaluation environment. + + For ``eval_env=0`` and ``reference=0``, the default, this captures the + stack frame of the function that calls :meth:`capture`. If ``eval_env + + reference`` is 1, then we capture that function's caller, etc. + + This somewhat complicated calling convention is designed to be + convenient for functions which want to capture their caller's + environment by default, but also allow explicit environments to be + specified. See the second example. + + Example:: + + x = 1 + this_env = EvalEnvironment.capture() + assert this_env.namespace["x"] == 1 + def child_func(): + return EvalEnvironment.capture(1) + this_env_from_child = child_func() + assert this_env_from_child.namespace["x"] == 1 + + Example:: + + # This function can be used like: + # my_model(formula_like, data) + # -> evaluates formula_like in caller's environment + # my_model(formula_like, data, eval_env=1) + # -> evaluates formula_like in caller's caller's environment + # my_model(formula_like, data, eval_env=my_env) + # -> evaluates formula_like in environment 'my_env' + def my_model(formula_like, data, eval_env=0): + eval_env = EvalEnvironment.capture(eval_env, reference=1) + return model_setup_helper(formula_like, data, eval_env) + + This is how :func:`dmatrix` works. + + .. versionadded: 0.2.0 + The ``reference`` argument. + """ + if isinstance(eval_env, cls): + return eval_env + elif isinstance(eval_env, numbers.Integral): + depth = eval_env + reference + else: + raise TypeError( + "Parameter 'eval_env' must be either an integer " + "or an instance of patsy.EvalEnvironment." + ) + frame = inspect.currentframe() + try: + for i in range(depth + 1): + if frame is None: + raise ValueError("call-stack is not that deep!") + frame = frame.f_back + return cls( + [frame.f_locals, frame.f_globals], + frame.f_code.co_flags & _ALL_FUTURE_FLAGS, + ) + # The try/finally is important to avoid a potential reference cycle -- + # any exception traceback will carry a reference to *our* frame, which + # contains a reference to our local variables, which would otherwise + # carry a reference to some parent frame, where the exception was + # caught...: + finally: + del frame + + def subset(self, names): + """Creates a new, flat EvalEnvironment that contains only + the variables specified.""" + vld = VarLookupDict(self._namespaces) + new_ns = dict((name, vld[name]) for name in names) + return EvalEnvironment([new_ns], self.flags) + + def _namespace_ids(self): + return [id(n) for n in self._namespaces] + + def __eq__(self, other): + return ( + isinstance(other, EvalEnvironment) + and self.flags == other.flags + and self._namespace_ids() == other._namespace_ids() + ) + + def __ne__(self, other): + return not self == other + + def __hash__(self): + return hash((EvalEnvironment, self.flags, tuple(self._namespace_ids()))) + + __getstate__ = no_pickling + + +def _a(): # pragma: no cover + _a = 1 + return _b() + + +def _b(): # pragma: no cover + _b = 1 + return _c() + + +def _c(): # pragma: no cover + _c = 1 + return [ + EvalEnvironment.capture(), + EvalEnvironment.capture(0), + EvalEnvironment.capture(1), + EvalEnvironment.capture(0, reference=1), + EvalEnvironment.capture(2), + EvalEnvironment.capture(0, 2), + ] + + +def test_EvalEnvironment_capture_namespace(): + c0, c, b1, b2, a1, a2 = _a() + assert "test_EvalEnvironment_capture_namespace" in c0.namespace + assert "test_EvalEnvironment_capture_namespace" in c.namespace + assert "test_EvalEnvironment_capture_namespace" in b1.namespace + assert "test_EvalEnvironment_capture_namespace" in b2.namespace + assert "test_EvalEnvironment_capture_namespace" in a1.namespace + assert "test_EvalEnvironment_capture_namespace" in a2.namespace + assert c0.namespace["_c"] == 1 + assert c.namespace["_c"] == 1 + assert b1.namespace["_b"] == 1 + assert b2.namespace["_b"] == 1 + assert a1.namespace["_a"] == 1 + assert a2.namespace["_a"] == 1 + assert b1.namespace["_c"] is _c + assert b2.namespace["_c"] is _c + import pytest + + pytest.raises(ValueError, EvalEnvironment.capture, 10**6) + + assert EvalEnvironment.capture(b1) is b1 + + pytest.raises(TypeError, EvalEnvironment.capture, 1.2) + + assert_no_pickling(EvalEnvironment.capture()) + + +def test_EvalEnvironment_capture_flags(): + # This is the only __future__ feature currently usable in Python + # 3... fortunately it is probably not going anywhere. + TEST_FEATURE = "barry_as_FLUFL" + test_flag = getattr(__future__, TEST_FEATURE).compiler_flag + assert test_flag & _ALL_FUTURE_FLAGS + source = ( + "def f():\n" + " in_f = 'hi from f'\n" + " global RETURN_INNER, RETURN_OUTER, RETURN_INNER_FROM_OUTER\n" + " RETURN_INNER = EvalEnvironment.capture(0)\n" + " RETURN_OUTER = call_capture_0()\n" + " RETURN_INNER_FROM_OUTER = call_capture_1()\n" + "f()\n" + ) + code = compile(source, "", "exec", 0, 1) + env = { + "EvalEnvironment": EvalEnvironment, + "call_capture_0": lambda: EvalEnvironment.capture(0), + "call_capture_1": lambda: EvalEnvironment.capture(1), + } + env2 = dict(env) + exec(code, env) + assert env["RETURN_INNER"].namespace["in_f"] == "hi from f" + assert env["RETURN_INNER_FROM_OUTER"].namespace["in_f"] == "hi from f" + assert "in_f" not in env["RETURN_OUTER"].namespace + assert env["RETURN_INNER"].flags & _ALL_FUTURE_FLAGS == 0 + assert env["RETURN_OUTER"].flags & _ALL_FUTURE_FLAGS == 0 + assert env["RETURN_INNER_FROM_OUTER"].flags & _ALL_FUTURE_FLAGS == 0 + + code2 = compile( + ("from __future__ import %s\n" % (TEST_FEATURE,)) + source, + "", + "exec", + 0, + 1, + ) + exec(code2, env2) + assert env2["RETURN_INNER"].namespace["in_f"] == "hi from f" + assert env2["RETURN_INNER_FROM_OUTER"].namespace["in_f"] == "hi from f" + assert "in_f" not in env2["RETURN_OUTER"].namespace + assert env2["RETURN_INNER"].flags & _ALL_FUTURE_FLAGS == test_flag + assert env2["RETURN_OUTER"].flags & _ALL_FUTURE_FLAGS == 0 + assert env2["RETURN_INNER_FROM_OUTER"].flags & _ALL_FUTURE_FLAGS == test_flag + + +def test_EvalEnvironment_eval_namespace(): + env = EvalEnvironment([{"a": 1}]) + assert env.eval("2 * a") == 2 + assert env.eval("2 * a", inner_namespace={"a": 2}) == 4 + import pytest + + pytest.raises(NameError, env.eval, "2 * b") + a = 3 + env2 = EvalEnvironment.capture(0) + assert env2.eval("2 * a") == 6 + + env3 = env.with_outer_namespace({"a": 10, "b": 3}) + assert env3.eval("2 * a") == 2 + assert env3.eval("2 * b") == 6 + + +def test_EvalEnvironment_eval_flags(): + import pytest + + # This joke __future__ statement replaces "!=" with "<>": + # http://www.python.org/dev/peps/pep-0401/ + test_flag = __future__.barry_as_FLUFL.compiler_flag + assert test_flag & _ALL_FUTURE_FLAGS + + env = EvalEnvironment([{"a": 11}], flags=0) + assert env.eval("a != 0") == True + pytest.raises(SyntaxError, env.eval, "a <> 0") + assert env.subset(["a"]).flags == 0 + assert env.with_outer_namespace({"b": 10}).flags == 0 + + env2 = EvalEnvironment([{"a": 11}], flags=test_flag) + assert env2.eval("a <> 0") == True + pytest.raises(SyntaxError, env2.eval, "a != 0") + assert env2.subset(["a"]).flags == test_flag + assert env2.with_outer_namespace({"b": 10}).flags == test_flag + + +def test_EvalEnvironment_subset(): + env = EvalEnvironment([{"a": 1}, {"b": 2}, {"c": 3}]) + + subset_a = env.subset(["a"]) + assert subset_a.eval("a") == 1 + import pytest + + pytest.raises(NameError, subset_a.eval, "b") + pytest.raises(NameError, subset_a.eval, "c") + + subset_bc = env.subset(["b", "c"]) + assert subset_bc.eval("b * c") == 6 + pytest.raises(NameError, subset_bc.eval, "a") + + +def test_EvalEnvironment_eq(): + import pytest + + if sys.version_info >= (3, 13): + pytest.skip( + "`frame.f_locals` may return write-through proxies in Python 3.13+, " + "breaking direct comparison by ids." + ) + + # Two environments are eq only if they refer to exactly the same + # global/local dicts + env1 = EvalEnvironment.capture(0) + env2 = EvalEnvironment.capture(0) + assert env1 == env2 + assert hash(env1) == hash(env2) + capture_local_env = lambda: EvalEnvironment.capture(0) + env3 = capture_local_env() + env4 = capture_local_env() + assert env3 != env4 + + +_builtins_dict = {} +exec("from patsy.builtins import *", {}, _builtins_dict) +# This is purely to make the existence of patsy.builtins visible to systems +# like py2app and py2exe. It's basically free, since the above line guarantees +# that patsy.builtins will be present in sys.modules in any case. +import patsy.builtins + + +class EvalFactor(object): + def __init__(self, code, origin=None): + """A factor class that executes arbitrary Python code and supports + stateful transforms. + + :arg code: A string containing a Python expression, that will be + evaluated to produce this factor's value. + + This is the standard factor class that is used when parsing formula + strings and implements the standard stateful transform processing. See + :ref:`stateful-transforms` and :ref:`expert-model-specification`. + + Two EvalFactor's are considered equal (e.g., for purposes of + redundancy detection) if they contain the same token stream. Basically + this means that the source code must be identical except for + whitespace:: + + assert EvalFactor("a + b") == EvalFactor("a+b") + assert EvalFactor("a + b") != EvalFactor("b + a") + """ + + # For parsed formulas, the code will already have been normalized by + # the parser. But let's normalize anyway, so we can be sure of having + # consistent semantics for __eq__ and __hash__. + self.code = normalize_token_spacing(code) + self.origin = origin + + def name(self): + return self.code + + def __repr__(self): + return "%s(%r)" % (self.__class__.__name__, self.code) + + def __eq__(self, other): + return isinstance(other, EvalFactor) and self.code == other.code + + def __ne__(self, other): + return not self == other + + def __hash__(self): + return hash((EvalFactor, self.code)) + + def memorize_passes_needed(self, state, eval_env): + # 'state' is just an empty dict which we can do whatever we want with, + # and that will be passed back to later memorize functions + state["transforms"] = {} + + eval_env = eval_env.with_outer_namespace(_builtins_dict) + env_namespace = eval_env.namespace + subset_names = [name for name in ast_names(self.code) if name in env_namespace] + eval_env = eval_env.subset(subset_names) + state["eval_env"] = eval_env + + # example code: == "2 * center(x)" + i = [0] + + def new_name_maker(token): + value = eval_env.namespace.get(token) + if hasattr(value, "__patsy_stateful_transform__"): + obj_name = "_patsy_stobj%s__%s__" % (i[0], token) + i[0] += 1 + obj = value.__patsy_stateful_transform__() + state["transforms"][obj_name] = obj + return obj_name + ".transform" + else: + return token + + # example eval_code: == "2 * _patsy_stobj0__center__.transform(x)" + eval_code = replace_bare_funcalls(self.code, new_name_maker) + state["eval_code"] = eval_code + # paranoia: verify that none of our new names appeared anywhere in the + # original code + if has_bare_variable_reference(state["transforms"], self.code): + raise PatsyError( + "names of this form are reserved for internal use (%s)" % (token,), + token.origin, + ) + # Pull out all the '_patsy_stobj0__center__.transform(x)' pieces + # to make '_patsy_stobj0__center__.memorize_chunk(x)' pieces + state["memorize_code"] = {} + for obj_name in state["transforms"]: + transform_calls = capture_obj_method_calls(obj_name, eval_code) + assert len(transform_calls) == 1 + transform_call = transform_calls[0] + transform_call_name, transform_call_code = transform_call + assert transform_call_name == obj_name + ".transform" + assert transform_call_code.startswith(transform_call_name + "(") + memorize_code = ( + obj_name + + ".memorize_chunk" + + transform_call_code[len(transform_call_name) :] + ) + state["memorize_code"][obj_name] = memorize_code + # Then sort the codes into bins, so that every item in bin number i + # depends only on items in bin (i-1) or less. (By 'depends', we mean + # that in something like: + # spline(center(x)) + # we have to first run: + # center.memorize_chunk(x) + # then + # center.memorize_finish(x) + # and only then can we run: + # spline.memorize_chunk(center.transform(x)) + # Since all of our objects have unique names, figuring out who + # depends on who is pretty easy -- we just check whether the + # memorization code for spline: + # spline.memorize_chunk(center.transform(x)) + # mentions the variable 'center' (which in the example, of course, it + # does). + pass_bins = [] + unsorted = set(state["transforms"]) + while unsorted: + pass_bin = set() + for obj_name in unsorted: + other_objs = unsorted.difference([obj_name]) + memorize_code = state["memorize_code"][obj_name] + if not has_bare_variable_reference(other_objs, memorize_code): + pass_bin.add(obj_name) + assert pass_bin + unsorted.difference_update(pass_bin) + pass_bins.append(pass_bin) + state["pass_bins"] = pass_bins + + return len(pass_bins) + + def _eval(self, code, memorize_state, data): + inner_namespace = VarLookupDict([data, memorize_state["transforms"]]) + return call_and_wrap_exc( + "Error evaluating factor", + self, + memorize_state["eval_env"].eval, + code, + inner_namespace=inner_namespace, + ) + + def memorize_chunk(self, state, which_pass, data): + for obj_name in state["pass_bins"][which_pass]: + self._eval(state["memorize_code"][obj_name], state, data) + + def memorize_finish(self, state, which_pass): + for obj_name in state["pass_bins"][which_pass]: + state["transforms"][obj_name].memorize_finish() + + def eval(self, memorize_state, data): + return self._eval(memorize_state["eval_code"], memorize_state, data) + + __getstate__ = no_pickling + + +def test_EvalFactor_basics(): + e = EvalFactor("a+b") + assert e.code == "a + b" + assert e.name() == "a + b" + e2 = EvalFactor("a +b", origin="asdf") + assert e == e2 + assert hash(e) == hash(e2) + assert e.origin is None + assert e2.origin == "asdf" + + assert_no_pickling(e) + + +def test_EvalFactor_memorize_passes_needed(): + from patsy.state import stateful_transform + + foo = stateful_transform(lambda: "FOO-OBJ") + bar = stateful_transform(lambda: "BAR-OBJ") + quux = stateful_transform(lambda: "QUUX-OBJ") + e = EvalFactor("foo(x) + bar(foo(y)) + quux(z, w)") + + state = {} + eval_env = EvalEnvironment.capture(0) + passes = e.memorize_passes_needed(state, eval_env) + print(passes) + print(state) + assert passes == 2 + for name in ["foo", "bar", "quux"]: + assert state["eval_env"].namespace[name] is locals()[name] + for name in ["w", "x", "y", "z", "e", "state"]: + assert name not in state["eval_env"].namespace + assert state["transforms"] == { + "_patsy_stobj0__foo__": "FOO-OBJ", + "_patsy_stobj1__bar__": "BAR-OBJ", + "_patsy_stobj2__foo__": "FOO-OBJ", + "_patsy_stobj3__quux__": "QUUX-OBJ", + } + assert ( + state["eval_code"] == "_patsy_stobj0__foo__.transform(x)" + " + _patsy_stobj1__bar__.transform(" + "_patsy_stobj2__foo__.transform(y))" + " + _patsy_stobj3__quux__.transform(z, w)" + ) + + assert state["memorize_code"] == { + "_patsy_stobj0__foo__": "_patsy_stobj0__foo__.memorize_chunk(x)", + "_patsy_stobj1__bar__": "_patsy_stobj1__bar__.memorize_chunk(_patsy_stobj2__foo__.transform(y))", + "_patsy_stobj2__foo__": "_patsy_stobj2__foo__.memorize_chunk(y)", + "_patsy_stobj3__quux__": "_patsy_stobj3__quux__.memorize_chunk(z, w)", + } + assert state["pass_bins"] == [ + set(["_patsy_stobj0__foo__", "_patsy_stobj2__foo__", "_patsy_stobj3__quux__"]), + set(["_patsy_stobj1__bar__"]), + ] + + +class _MockTransform(object): + # Adds up all memorized data, then subtracts that sum from each datum + def __init__(self): + self._sum = 0 + self._memorize_chunk_called = 0 + self._memorize_finish_called = 0 + + def memorize_chunk(self, data): + self._memorize_chunk_called += 1 + import numpy as np + + self._sum += np.sum(data) + + def memorize_finish(self): + self._memorize_finish_called += 1 + + def transform(self, data): + return data - self._sum + + +def test_EvalFactor_end_to_end(): + from patsy.state import stateful_transform + + foo = stateful_transform(_MockTransform) + e = EvalFactor("foo(x) + foo(foo(y))") + state = {} + eval_env = EvalEnvironment.capture(0) + passes = e.memorize_passes_needed(state, eval_env) + print(passes) + print(state) + assert passes == 2 + assert state["eval_env"].namespace["foo"] is foo + for name in ["x", "y", "e", "state"]: + assert name not in state["eval_env"].namespace + import numpy as np + + e.memorize_chunk(state, 0, {"x": np.array([1, 2]), "y": np.array([10, 11])}) + assert state["transforms"]["_patsy_stobj0__foo__"]._memorize_chunk_called == 1 + assert state["transforms"]["_patsy_stobj2__foo__"]._memorize_chunk_called == 1 + e.memorize_chunk(state, 0, {"x": np.array([12, -10]), "y": np.array([100, 3])}) + assert state["transforms"]["_patsy_stobj0__foo__"]._memorize_chunk_called == 2 + assert state["transforms"]["_patsy_stobj2__foo__"]._memorize_chunk_called == 2 + assert state["transforms"]["_patsy_stobj0__foo__"]._memorize_finish_called == 0 + assert state["transforms"]["_patsy_stobj2__foo__"]._memorize_finish_called == 0 + e.memorize_finish(state, 0) + assert state["transforms"]["_patsy_stobj0__foo__"]._memorize_finish_called == 1 + assert state["transforms"]["_patsy_stobj2__foo__"]._memorize_finish_called == 1 + assert state["transforms"]["_patsy_stobj1__foo__"]._memorize_chunk_called == 0 + assert state["transforms"]["_patsy_stobj1__foo__"]._memorize_finish_called == 0 + e.memorize_chunk(state, 1, {"x": np.array([1, 2]), "y": np.array([10, 11])}) + e.memorize_chunk(state, 1, {"x": np.array([12, -10]), "y": np.array([100, 3])}) + e.memorize_finish(state, 1) + for transform in state["transforms"].values(): + assert transform._memorize_chunk_called == 2 + assert transform._memorize_finish_called == 1 + # sums: + # 0: 1 + 2 + 12 + -10 == 5 + # 2: 10 + 11 + 100 + 3 == 124 + # 1: (10 - 124) + (11 - 124) + (100 - 124) + (3 - 124) == -372 + # results: + # 0: -4, -3, 7, -15 + # 2: -114, -113, -24, -121 + # 1: 258, 259, 348, 251 + # 0 + 1: 254, 256, 355, 236 + assert np.all( + e.eval(state, {"x": np.array([1, 2, 12, -10]), "y": np.array([10, 11, 100, 3])}) + == [254, 256, 355, 236] + ) + + +def annotated_tokens(code): + prev_was_dot = False + it = PushbackAdapter(python_tokenize(code)) + for token_type, token, origin in it: + props = {} + props["bare_ref"] = not prev_was_dot and token_type == tokenize.NAME + props["bare_funcall"] = ( + props["bare_ref"] and it.has_more() and it.peek()[1] == "(" + ) + yield (token_type, token, origin, props) + prev_was_dot = token == "." + + +def test_annotated_tokens(): + tokens_without_origins = [ + (token_type, token, props) + for (token_type, token, origin, props) in (annotated_tokens("a(b) + c.d")) + ] + assert tokens_without_origins == [ + (tokenize.NAME, "a", {"bare_ref": True, "bare_funcall": True}), + (tokenize.OP, "(", {"bare_ref": False, "bare_funcall": False}), + (tokenize.NAME, "b", {"bare_ref": True, "bare_funcall": False}), + (tokenize.OP, ")", {"bare_ref": False, "bare_funcall": False}), + (tokenize.OP, "+", {"bare_ref": False, "bare_funcall": False}), + (tokenize.NAME, "c", {"bare_ref": True, "bare_funcall": False}), + (tokenize.OP, ".", {"bare_ref": False, "bare_funcall": False}), + (tokenize.NAME, "d", {"bare_ref": False, "bare_funcall": False}), + ] + + # This was a bug: + assert len(list(annotated_tokens("x"))) == 1 + + +def has_bare_variable_reference(names, code): + for _, token, _, props in annotated_tokens(code): + if props["bare_ref"] and token in names: + return True + return False + + +def replace_bare_funcalls(code, replacer): + tokens = [] + for token_type, token, origin, props in annotated_tokens(code): + if props["bare_ref"] and props["bare_funcall"]: + token = replacer(token) + tokens.append((token_type, token)) + return pretty_untokenize(tokens) + + +def test_replace_bare_funcalls(): + def replacer1(token): + return {"a": "b", "foo": "_internal.foo.process"}.get(token, token) + + def t1(code, expected): + replaced = replace_bare_funcalls(code, replacer1) + print("%r -> %r" % (code, replaced)) + print("(wanted %r)" % (expected,)) + assert replaced == expected + + t1("foobar()", "foobar()") + t1("a()", "b()") + t1("foobar.a()", "foobar.a()") + t1("foo()", "_internal.foo.process()") + t1("a + 1", "a + 1") + t1("b() + a() * x[foo(2 ** 3)]", "b() + b() * x[_internal.foo.process(2 ** 3)]") + + +class _FuncallCapturer(object): + # captures the next funcall + def __init__(self, start_token_type, start_token): + self.func = [start_token] + self.tokens = [(start_token_type, start_token)] + self.paren_depth = 0 + self.started = False + self.done = False + + def add_token(self, token_type, token): + if self.done: + return + self.tokens.append((token_type, token)) + if token in ["(", "{", "["]: + self.paren_depth += 1 + if token in [")", "}", "]"]: + self.paren_depth -= 1 + assert self.paren_depth >= 0 + if not self.started: + if token == "(": + self.started = True + else: + assert token_type == tokenize.NAME or token == "." + self.func.append(token) + if self.started and self.paren_depth == 0: + self.done = True + + +# This is not a very general function -- it assumes that all references to the +# given object are of the form '.something(method call)'. +def capture_obj_method_calls(obj_name, code): + capturers = [] + for token_type, token, origin, props in annotated_tokens(code): + for capturer in capturers: + capturer.add_token(token_type, token) + if props["bare_ref"] and token == obj_name: + capturers.append(_FuncallCapturer(token_type, token)) + return [ + ("".join(capturer.func), pretty_untokenize(capturer.tokens)) + for capturer in capturers + ] + + +def test_capture_obj_method_calls(): + assert capture_obj_method_calls("foo", "a + foo.baz(bar) + b.c(d)") == [ + ("foo.baz", "foo.baz(bar)") + ] + assert capture_obj_method_calls("b", "a + foo.baz(bar) + b.c(d)") == [ + ("b.c", "b.c(d)") + ] + assert capture_obj_method_calls("foo", "foo.bar(foo.baz(quux))") == [ + ("foo.bar", "foo.bar(foo.baz(quux))"), + ("foo.baz", "foo.baz(quux)"), + ] + assert capture_obj_method_calls("bar", "foo[bar.baz(x(z[asdf])) ** 2]") == [ + ("bar.baz", "bar.baz(x(z[asdf]))") + ] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/highlevel.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/highlevel.py new file mode 100644 index 0000000000000000000000000000000000000000..1af6ce8cbfeab87e0dbd501bb9e44f012acc1a65 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/highlevel.py @@ -0,0 +1,322 @@ +# This file is part of Patsy +# Copyright (C) 2011-2013 Nathaniel Smith +# See file LICENSE.txt for license information. + +# These are made available in the patsy.* namespace: +__all__ = ["dmatrix", "dmatrices", "incr_dbuilder", "incr_dbuilders"] + +# problems: +# statsmodels reluctant to pass around separate eval environment, suggesting +# that design_and_matrices-equivalent should return a formula_like +# is ModelDesc really the high-level thing? +# ModelDesign doesn't work -- need to work with the builder set +# want to be able to return either a matrix or a pandas dataframe + +import numpy as np + +from patsy import PatsyError +from patsy.design_info import DesignMatrix, DesignInfo +from patsy.eval import EvalEnvironment +from patsy.desc import ModelDesc +from patsy.build import design_matrix_builders, build_design_matrices +from patsy.util import have_pandas, asarray_or_pandas, atleast_2d_column_default + +if have_pandas: + import pandas + + +# Tries to build a (lhs, rhs) design given a formula_like and an incremental +# data source. If formula_like is not capable of doing this, then returns +# None. +def _try_incr_builders(formula_like, data_iter_maker, eval_env, NA_action): + if isinstance(formula_like, DesignInfo): + return ( + design_matrix_builders([[]], data_iter_maker, eval_env, NA_action)[0], + formula_like, + ) + if ( + isinstance(formula_like, tuple) + and len(formula_like) == 2 + and isinstance(formula_like[0], DesignInfo) + and isinstance(formula_like[1], DesignInfo) + ): + return formula_like + if hasattr(formula_like, "__patsy_get_model_desc__"): + formula_like = formula_like.__patsy_get_model_desc__(eval_env) + if not isinstance(formula_like, ModelDesc): + raise PatsyError( + "bad value from %r.__patsy_get_model_desc__" % (formula_like,) + ) + # fallthrough + if isinstance(formula_like, str): + formula_like = ModelDesc.from_formula(formula_like) + # fallthrough + if isinstance(formula_like, ModelDesc): + assert isinstance(eval_env, EvalEnvironment) + return design_matrix_builders( + [formula_like.lhs_termlist, formula_like.rhs_termlist], + data_iter_maker, + eval_env, + NA_action, + ) + else: + return None + + +def incr_dbuilder(formula_like, data_iter_maker, eval_env=0, NA_action="drop"): + """Construct a design matrix builder incrementally from a large data set. + + :arg formula_like: Similar to :func:`dmatrix`, except that explicit + matrices are not allowed. Must be a formula string, a + :class:`ModelDesc`, a :class:`DesignInfo`, or an object with a + ``__patsy_get_model_desc__`` method. + :arg data_iter_maker: A zero-argument callable which returns an iterator + over dict-like data objects. This must be a callable rather than a + simple iterator because sufficiently complex formulas may require + multiple passes over the data (e.g. if there are nested stateful + transforms). + :arg eval_env: Either a :class:`EvalEnvironment` which will be used to + look up any variables referenced in `formula_like` that cannot be + found in `data`, or else a depth represented as an + integer which will be passed to :meth:`EvalEnvironment.capture`. + ``eval_env=0`` means to use the context of the function calling + :func:`incr_dbuilder` for lookups. If calling this function from a + library, you probably want ``eval_env=1``, which means that variables + should be resolved in *your* caller's namespace. + :arg NA_action: An :class:`NAAction` object or string, used to determine + what values count as 'missing' for purposes of determining the levels of + categorical factors. + :returns: A :class:`DesignInfo` + + Tip: for `data_iter_maker`, write a generator like:: + + def iter_maker(): + for data_chunk in my_data_store: + yield data_chunk + + and pass `iter_maker` (*not* `iter_maker()`). + + .. versionadded:: 0.2.0 + The ``NA_action`` argument. + """ + eval_env = EvalEnvironment.capture(eval_env, reference=1) + design_infos = _try_incr_builders( + formula_like, data_iter_maker, eval_env, NA_action + ) + if design_infos is None: + raise PatsyError("bad formula-like object") + if len(design_infos[0].column_names) > 0: + raise PatsyError( + "encountered outcome variables for a model that does not expect them" + ) + return design_infos[1] + + +def incr_dbuilders(formula_like, data_iter_maker, eval_env=0, NA_action="drop"): + """Construct two design matrix builders incrementally from a large data + set. + + :func:`incr_dbuilders` is to :func:`incr_dbuilder` as :func:`dmatrices` is + to :func:`dmatrix`. See :func:`incr_dbuilder` for details. + """ + eval_env = EvalEnvironment.capture(eval_env, reference=1) + design_infos = _try_incr_builders( + formula_like, data_iter_maker, eval_env, NA_action + ) + if design_infos is None: + raise PatsyError("bad formula-like object") + if len(design_infos[0].column_names) == 0: + raise PatsyError("model is missing required outcome variables") + return design_infos + + +# This always returns a length-two tuple, +# response, predictors +# where +# response is a DesignMatrix (possibly with 0 columns) +# predictors is a DesignMatrix +# The input 'formula_like' could be like: +# (np.ndarray, np.ndarray) +# (DesignMatrix, DesignMatrix) +# (None, DesignMatrix) +# np.ndarray # for predictor-only models +# DesignMatrix +# (None, np.ndarray) +# "y ~ x" +# ModelDesc(...) +# DesignInfo +# (DesignInfo, DesignInfo) +# any object with a special method __patsy_get_model_desc__ +def _do_highlevel_design(formula_like, data, eval_env, NA_action, return_type): + if return_type == "dataframe" and not have_pandas: + raise PatsyError("pandas.DataFrame was requested, but pandas is not installed") + if return_type not in ("matrix", "dataframe"): + raise PatsyError( + "unrecognized output type %r, should be " + "'matrix' or 'dataframe'" % (return_type,) + ) + + def data_iter_maker(): + return iter([data]) + + design_infos = _try_incr_builders( + formula_like, data_iter_maker, eval_env, NA_action + ) + if design_infos is not None: + return build_design_matrices( + design_infos, data, NA_action=NA_action, return_type=return_type + ) + else: + # No builders, but maybe we can still get matrices + if isinstance(formula_like, tuple): + if len(formula_like) != 2: + raise PatsyError( + "don't know what to do with a length %s " + "matrices tuple" % (len(formula_like),) + ) + (lhs, rhs) = formula_like + else: + # subok=True is necessary here to allow DesignMatrixes to pass + # through + (lhs, rhs) = (None, asarray_or_pandas(formula_like, subok=True)) + + # some sort of explicit matrix or matrices were given. Currently we + # have them in one of these forms: + # -- an ndarray or subclass + # -- a DesignMatrix + # -- a pandas.Series + # -- a pandas.DataFrame + # and we have to produce a standard output format. + def _regularize_matrix(m, default_column_prefix): + di = DesignInfo.from_array(m, default_column_prefix) + if have_pandas and isinstance(m, (pandas.Series, pandas.DataFrame)): + orig_index = m.index + else: + orig_index = None + if return_type == "dataframe": + m = atleast_2d_column_default(m, preserve_pandas=True) + m = pandas.DataFrame(m) + m.columns = di.column_names + m.design_info = di + return (m, orig_index) + else: + return (DesignMatrix(m, di), orig_index) + + rhs, rhs_orig_index = _regularize_matrix(rhs, "x") + if lhs is None: + lhs = np.zeros((rhs.shape[0], 0), dtype=float) + lhs, lhs_orig_index = _regularize_matrix(lhs, "y") + + assert isinstance(getattr(lhs, "design_info", None), DesignInfo) + assert isinstance(getattr(rhs, "design_info", None), DesignInfo) + if lhs.shape[0] != rhs.shape[0]: + raise PatsyError( + "shape mismatch: outcome matrix has %s rows, " + "predictor matrix has %s rows" % (lhs.shape[0], rhs.shape[0]) + ) + if rhs_orig_index is not None and lhs_orig_index is not None: + if not rhs_orig_index.equals(lhs_orig_index): + raise PatsyError( + "index mismatch: outcome and predictor have incompatible indexes" + ) + if return_type == "dataframe": + if rhs_orig_index is not None and lhs_orig_index is None: + lhs.index = rhs.index + if rhs_orig_index is None and lhs_orig_index is not None: + rhs.index = lhs.index + return (lhs, rhs) + + +def dmatrix(formula_like, data={}, eval_env=0, NA_action="drop", return_type="matrix"): + """Construct a single design matrix given a formula_like and data. + + :arg formula_like: An object that can be used to construct a design + matrix. See below. + :arg data: A dict-like object that can be used to look up variables + referenced in `formula_like`. + :arg eval_env: Either a :class:`EvalEnvironment` which will be used to + look up any variables referenced in `formula_like` that cannot be + found in `data`, or else a depth represented as an + integer which will be passed to :meth:`EvalEnvironment.capture`. + ``eval_env=0`` means to use the context of the function calling + :func:`dmatrix` for lookups. If calling this function from a library, + you probably want ``eval_env=1``, which means that variables should be + resolved in *your* caller's namespace. + :arg NA_action: What to do with rows that contain missing values. You can + ``"drop"`` them, ``"raise"`` an error, or for customization, pass an + :class:`NAAction` object. See :class:`NAAction` for details on what + values count as 'missing' (and how to alter this). + :arg return_type: Either ``"matrix"`` or ``"dataframe"``. See below. + + The `formula_like` can take a variety of forms. You can use any of the + following: + + * (The most common option) A formula string like ``"x1 + x2"`` (for + :func:`dmatrix`) or ``"y ~ x1 + x2"`` (for :func:`dmatrices`). For + details see :ref:`formulas`. + * A :class:`ModelDesc`, which is a Python object representation of a + formula. See :ref:`formulas` and :ref:`expert-model-specification` for + details. + * A :class:`DesignInfo`. + * An object that has a method called :meth:`__patsy_get_model_desc__`. + For details see :ref:`expert-model-specification`. + * A numpy array_like (for :func:`dmatrix`) or a tuple + (array_like, array_like) (for :func:`dmatrices`). These will have + metadata added, representation normalized, and then be returned + directly. In this case `data` and `eval_env` are + ignored. There is special handling for two cases: + + * :class:`DesignMatrix` objects will have their :class:`DesignInfo` + preserved. This allows you to set up custom column names and term + information even if you aren't using the rest of the patsy + machinery. + * :class:`pandas.DataFrame` or :class:`pandas.Series` objects will have + their (row) indexes checked. If two are passed in, their indexes must + be aligned. If ``return_type="dataframe"``, then their indexes will be + preserved on the output. + + Regardless of the input, the return type is always either: + + * A :class:`DesignMatrix`, if ``return_type="matrix"`` (the default) + * A :class:`pandas.DataFrame`, if ``return_type="dataframe"``. + + The actual contents of the design matrix is identical in both cases, and + in both cases a :class:`DesignInfo` object will be available in a + ``.design_info`` attribute on the return value. However, for + ``return_type="dataframe"``, any pandas indexes on the input (either in + `data` or directly passed through `formula_like`) will be preserved, which + may be useful for e.g. time-series models. + + .. versionadded:: 0.2.0 + The ``NA_action`` argument. + """ + eval_env = EvalEnvironment.capture(eval_env, reference=1) + (lhs, rhs) = _do_highlevel_design( + formula_like, data, eval_env, NA_action, return_type + ) + if lhs.shape[1] != 0: + raise PatsyError( + "encountered outcome variables for a model that does not expect them" + ) + return rhs + + +def dmatrices( + formula_like, data={}, eval_env=0, NA_action="drop", return_type="matrix" +): + """Construct two design matrices given a formula_like and data. + + This function is identical to :func:`dmatrix`, except that it requires + (and returns) two matrices instead of one. By convention, the first matrix + is the "outcome" or "y" data, and the second is the "predictor" or "x" + data. + + See :func:`dmatrix` for details. + """ + eval_env = EvalEnvironment.capture(eval_env, reference=1) + (lhs, rhs) = _do_highlevel_design( + formula_like, data, eval_env, NA_action, return_type + ) + if lhs.shape[1] == 0: + raise PatsyError("model is missing required outcome variables") + return (lhs, rhs) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/infix_parser.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/infix_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..6c127b534fff08951ada0097df5af6ea24fc33e0 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/infix_parser.py @@ -0,0 +1,296 @@ +# This file is part of Patsy +# Copyright (C) 2011 Nathaniel Smith +# See file LICENSE.txt for license information. + +# This file implements a simple "shunting yard algorithm" parser for infix +# languages with parentheses. It is used as the core of our parser for +# formulas, but is generic enough to be used for other purposes as well +# (e.g. parsing linear constraints). It just builds a parse tree; semantics +# are somebody else's problem. +# +# Plus it spends energy on tracking where each item in the parse tree comes +# from, to allow high-quality error reporting. +# +# You are expected to provide an collection of Operators, a collection of +# atomic types, and an iterator that provides Tokens. Each Operator should +# have a unique token_type (which is an arbitrary Python object), and each +# Token should have a matching token_type, or one of the special types +# Token.LPAREN, Token.RPAREN. Each Token is required to have a valid Origin +# attached, for error reporting. + +# XX: still seriously consider putting the magic intercept handling into the +# tokenizer. we'd still need separate term-sets that get pasted together by ~ +# to create the modeldesc, though... heck maybe we should just have a +# modeldesc be 1-or-more termsets, with the convention that if it's 1, then +# it's a rhs, and if it's 2, it's (lhs, rhs), and otherwise you're on your +# own. Test: would this be useful for multiple-group log-linear models, +# maybe? Answer: Perhaps. outcome ~ x1 + x2 ~ group. But lots of other +# plausible, maybe better ways to write this -- (outcome | group) ~ x1 + x2? +# "outcome ~ x1 + x2", group="group"? etc. + +__all__ = ["Token", "ParseNode", "Operator", "parse"] + +from patsy import PatsyError +from patsy.origin import Origin +from patsy.util import ( + repr_pretty_delegate, + repr_pretty_impl, + no_pickling, + assert_no_pickling, +) + + +class _UniqueValue: + def __init__(self, print_as): + self._print_as = print_as + + def __repr__(self): + return "%s(%r)" % (self.__class__.__name__, self._print_as) + + __getstate__ = no_pickling + + +class Token: + """A token with possible payload. + + .. attribute:: type + + An arbitrary object indicating the type of this token. Should be + :term:`hashable`, but otherwise it can be whatever you like. + """ + + LPAREN = _UniqueValue("LPAREN") + RPAREN = _UniqueValue("RPAREN") + + def __init__(self, type, origin, extra=None): + self.type = type + self.origin = origin + self.extra = extra + + __repr__ = repr_pretty_delegate + + def _repr_pretty_(self, p, cycle): + assert not cycle + kwargs = [] + if self.extra is not None: + kwargs = [("extra", self.extra)] + return repr_pretty_impl(p, self, [self.type, self.origin], kwargs) + + __getstate__ = no_pickling + + +class ParseNode(object): + def __init__(self, type, token, args, origin): + self.type = type + self.token = token + self.args = args + self.origin = origin + + __repr__ = repr_pretty_delegate + + def _repr_pretty_(self, p, cycle): + return repr_pretty_impl(p, self, [self.type, self.token, self.args]) + + __getstate__ = no_pickling + + +class Operator(object): + def __init__(self, token_type, arity, precedence): + self.token_type = token_type + self.arity = arity + self.precedence = precedence + + def __repr__(self): + return "%s(%r, %r, %r)" % ( + self.__class__.__name__, + self.token_type, + self.arity, + self.precedence, + ) + + __getstate__ = no_pickling + + +class _StackOperator(object): + def __init__(self, op, token): + self.op = op + self.token = token + + __getstate__ = no_pickling + + +_open_paren = Operator(Token.LPAREN, -1, -9999999) + + +class _ParseContext(object): + def __init__(self, unary_ops, binary_ops, atomic_types, trace): + self.op_stack = [] + self.noun_stack = [] + self.unary_ops = unary_ops + self.binary_ops = binary_ops + self.atomic_types = atomic_types + self.trace = trace + + __getstate__ = no_pickling + + +def _read_noun_context(token, c): + if token.type == Token.LPAREN: + if c.trace: + print("Pushing open-paren") + c.op_stack.append(_StackOperator(_open_paren, token)) + return True + elif token.type in c.unary_ops: + if c.trace: + print("Pushing unary op %r" % (token.type,)) + c.op_stack.append(_StackOperator(c.unary_ops[token.type], token)) + return True + elif token.type in c.atomic_types: + if c.trace: + print("Pushing noun %r (%r)" % (token.type, token.extra)) + c.noun_stack.append(ParseNode(token.type, token, [], token.origin)) + return False + else: + raise PatsyError( + "expected a noun, not '%s'" % (token.origin.relevant_code(),), token + ) + + +def _run_op(c): + assert c.op_stack + stackop = c.op_stack.pop() + args = [] + for i in range(stackop.op.arity): + args.append(c.noun_stack.pop()) + args.reverse() + if c.trace: + print("Reducing %r (%r)" % (stackop.op.token_type, args)) + node = ParseNode( + stackop.op.token_type, + stackop.token, + args, + Origin.combine([stackop.token] + args), + ) + c.noun_stack.append(node) + + +def _read_op_context(token, c): + if token.type == Token.RPAREN: + if c.trace: + print("Found close-paren") + while c.op_stack and c.op_stack[-1].op.token_type != Token.LPAREN: + _run_op(c) + if not c.op_stack: + raise PatsyError("missing '(' or extra ')'", token) + assert c.op_stack[-1].op.token_type == Token.LPAREN + # Expand the origin of the item on top of the noun stack to include + # the open and close parens: + combined = Origin.combine([c.op_stack[-1].token, c.noun_stack[-1].token, token]) + c.noun_stack[-1].origin = combined + # Pop the open-paren + c.op_stack.pop() + return False + elif token.type in c.binary_ops: + if c.trace: + print("Found binary operator %r" % (token.type)) + stackop = _StackOperator(c.binary_ops[token.type], token) + while c.op_stack and stackop.op.precedence <= c.op_stack[-1].op.precedence: + _run_op(c) + if c.trace: + print("Pushing binary operator %r" % (token.type)) + c.op_stack.append(stackop) + return True + else: + raise PatsyError( + "expected an operator, not '%s'" % (token.origin.relevant_code(),), token + ) + + +def infix_parse(tokens, operators, atomic_types, trace=False): + token_source = iter(tokens) + + unary_ops = {} + binary_ops = {} + for op in operators: + assert op.precedence > _open_paren.precedence + if op.arity == 1: + unary_ops[op.token_type] = op + elif op.arity == 2: + binary_ops[op.token_type] = op + else: + raise ValueError("operators must be unary or binary") + + c = _ParseContext(unary_ops, binary_ops, atomic_types, trace) + + # This is an implementation of Dijkstra's shunting yard algorithm: + # http://en.wikipedia.org/wiki/Shunting_yard_algorithm + # http://www.engr.mun.ca/~theo/Misc/exp_parsing.htm + + want_noun = True + for token in token_source: + if c.trace: + print("Reading next token (want_noun=%r)" % (want_noun,)) + if want_noun: + want_noun = _read_noun_context(token, c) + else: + want_noun = _read_op_context(token, c) + if c.trace: + print("End of token stream") + + if want_noun: + raise PatsyError( + "expected a noun, but instead the expression ended", + c.op_stack[-1].token.origin, + ) + + while c.op_stack: + if c.op_stack[-1].op.token_type == Token.LPAREN: + raise PatsyError("Unmatched '('", c.op_stack[-1].token) + _run_op(c) + + assert len(c.noun_stack) == 1 + return c.noun_stack.pop() + + +# Much more thorough tests in parse_formula.py, this is just a smoke test: +def test_infix_parse(): + ops = [Operator("+", 2, 10), Operator("*", 2, 20), Operator("-", 1, 30)] + atomic = ["ATOM1", "ATOM2"] + # a + -b * (c + d) + mock_origin = Origin("asdf", 2, 3) + tokens = [ + Token("ATOM1", mock_origin, "a"), + Token("+", mock_origin, "+"), + Token("-", mock_origin, "-"), + Token("ATOM2", mock_origin, "b"), + Token("*", mock_origin, "*"), + Token(Token.LPAREN, mock_origin, "("), + Token("ATOM1", mock_origin, "c"), + Token("+", mock_origin, "+"), + Token("ATOM2", mock_origin, "d"), + Token(Token.RPAREN, mock_origin, ")"), + ] + tree = infix_parse(tokens, ops, atomic) + + def te(tree, type, extra): + assert tree.type == type + assert tree.token.extra == extra + + te(tree, "+", "+") + te(tree.args[0], "ATOM1", "a") + assert tree.args[0].args == [] + te(tree.args[1], "*", "*") + te(tree.args[1].args[0], "-", "-") + assert len(tree.args[1].args[0].args) == 1 + te(tree.args[1].args[0].args[0], "ATOM2", "b") + te(tree.args[1].args[1], "+", "+") + te(tree.args[1].args[1].args[0], "ATOM1", "c") + te(tree.args[1].args[1].args[1], "ATOM2", "d") + + import pytest + + # No ternary ops + pytest.raises(ValueError, infix_parse, [], [Operator("+", 3, 10)], ["ATOMIC"]) + + # smoke test just to make sure there are no egregious bugs in 'trace' + infix_parse(tokens, ops, atomic, trace=True) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/mgcv_cubic_splines.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/mgcv_cubic_splines.py new file mode 100644 index 0000000000000000000000000000000000000000..5f9368096b34e210f2b7f27d7f862dc79f82345f --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/mgcv_cubic_splines.py @@ -0,0 +1,1253 @@ +# This file is part of Patsy +# Copyright (C) 2014 GDF Suez, http://www.gdfsuez.com/ +# See file LICENSE.txt for license information. + +# R package 'mgcv' compatible cubic spline basis functions + +# These are made available in the patsy.* namespace +__all__ = ["cr", "cc", "te"] + +import numpy as np + +from patsy.util import ( + have_pandas, + atleast_2d_column_default, + no_pickling, + assert_no_pickling, + safe_string_eq, +) +from patsy.state import stateful_transform + +if have_pandas: + import pandas + + +def _get_natural_f(knots): + """Returns mapping of natural cubic spline values to 2nd derivatives. + + .. note:: See 'Generalized Additive Models', Simon N. Wood, 2006, pp 145-146 + + :param knots: The 1-d array knots used for cubic spline parametrization, + must be sorted in ascending order. + :return: A 2-d array mapping natural cubic spline values at + knots to second derivatives. + + :raise ImportError: if scipy is not found, required for + ``linalg.solve_banded()`` + """ + try: + from scipy import linalg + except ImportError: # pragma: no cover + raise ImportError("Cubic spline functionality requires scipy.") + + h = knots[1:] - knots[:-1] + diag = (h[:-1] + h[1:]) / 3.0 + ul_diag = h[1:-1] / 6.0 + banded_b = np.array([np.r_[0.0, ul_diag], diag, np.r_[ul_diag, 0.0]]) + d = np.zeros((knots.size - 2, knots.size)) + for i in range(knots.size - 2): + d[i, i] = 1.0 / h[i] + d[i, i + 2] = 1.0 / h[i + 1] + d[i, i + 1] = -d[i, i] - d[i, i + 2] + + fm = linalg.solve_banded((1, 1), banded_b, d) + + return np.vstack([np.zeros(knots.size), fm, np.zeros(knots.size)]) + + +# Cyclic Cubic Regression Splines + + +def _map_cyclic(x, lbound, ubound): + """Maps values into the interval [lbound, ubound] in a cyclic fashion. + + :param x: The 1-d array values to be mapped. + :param lbound: The lower bound of the interval. + :param ubound: The upper bound of the interval. + :return: A new 1-d array containing mapped x values. + + :raise ValueError: if lbound >= ubound. + """ + if lbound >= ubound: + raise ValueError( + "Invalid argument: lbound (%r) should be " + "less than ubound (%r)." % (lbound, ubound) + ) + + x = np.copy(x) + x[x > ubound] = lbound + (x[x > ubound] - ubound) % (ubound - lbound) + x[x < lbound] = ubound - (lbound - x[x < lbound]) % (ubound - lbound) + + return x + + +def test__map_cyclic(): + x = np.array([1.5, 2.6, 0.1, 4.4, 10.7]) + x_orig = np.copy(x) + expected_mapped_x = np.array([3.0, 2.6, 3.1, 2.9, 3.2]) + mapped_x = _map_cyclic(x, 2.1, 3.6) + assert np.allclose(x, x_orig) + assert np.allclose(mapped_x, expected_mapped_x) + + +def test__map_cyclic_errors(): + import pytest + + x = np.linspace(0.2, 5.7, 10) + pytest.raises(ValueError, _map_cyclic, x, 4.5, 3.6) + pytest.raises(ValueError, _map_cyclic, x, 4.5, 4.5) + + +def _get_cyclic_f(knots): + """Returns mapping of cyclic cubic spline values to 2nd derivatives. + + .. note:: See 'Generalized Additive Models', Simon N. Wood, 2006, pp 146-147 + + :param knots: The 1-d array knots used for cubic spline parametrization, + must be sorted in ascending order. + :return: A 2-d array mapping cyclic cubic spline values at + knots to second derivatives. + """ + h = knots[1:] - knots[:-1] + n = knots.size - 1 + b = np.zeros((n, n)) + d = np.zeros((n, n)) + + b[0, 0] = (h[n - 1] + h[0]) / 3.0 + b[0, n - 1] = h[n - 1] / 6.0 + b[n - 1, 0] = h[n - 1] / 6.0 + + d[0, 0] = -1.0 / h[0] - 1.0 / h[n - 1] + d[0, n - 1] = 1.0 / h[n - 1] + d[n - 1, 0] = 1.0 / h[n - 1] + + for i in range(1, n): + b[i, i] = (h[i - 1] + h[i]) / 3.0 + b[i, i - 1] = h[i - 1] / 6.0 + b[i - 1, i] = h[i - 1] / 6.0 + + d[i, i] = -1.0 / h[i - 1] - 1.0 / h[i] + d[i, i - 1] = 1.0 / h[i - 1] + d[i - 1, i] = 1.0 / h[i - 1] + + return np.linalg.solve(b, d) + + +# Tensor Product + + +def _row_tensor_product(dms): + """Computes row-wise tensor product of given arguments. + + .. note:: Custom algorithm to precisely match what is done in 'mgcv', + in particular look out for order of result columns! + For reference implementation see 'mgcv' source code, + file 'mat.c', mgcv_tensor_mm(), l.62 + + :param dms: A sequence of 2-d arrays (marginal design matrices). + :return: The 2-d array row-wise tensor product of given arguments. + + :raise ValueError: if argument sequence is empty, does not contain only + 2-d arrays or if the arrays number of rows does not match. + """ + if len(dms) == 0: + raise ValueError("Tensor product arrays sequence should not be empty.") + for dm in dms: + if dm.ndim != 2: + raise ValueError("Tensor product arguments should be 2-d arrays.") + + tp_nrows = dms[0].shape[0] + tp_ncols = 1 + for dm in dms: + if dm.shape[0] != tp_nrows: + raise ValueError( + "Tensor product arguments should have same number of rows." + ) + tp_ncols *= dm.shape[1] + tp = np.zeros((tp_nrows, tp_ncols)) + tp[:, -dms[-1].shape[1] :] = dms[-1] + filled_tp_ncols = dms[-1].shape[1] + for dm in dms[-2::-1]: + p = -filled_tp_ncols * dm.shape[1] + for j in range(dm.shape[1]): + xj = dm[:, j] + for t in range(-filled_tp_ncols, 0): + tp[:, p] = tp[:, t] * xj + p += 1 + filled_tp_ncols *= dm.shape[1] + + return tp + + +def test__row_tensor_product_errors(): + import pytest + + pytest.raises(ValueError, _row_tensor_product, []) + pytest.raises(ValueError, _row_tensor_product, [np.arange(1, 5)]) + pytest.raises(ValueError, _row_tensor_product, [np.arange(1, 5), np.arange(1, 5)]) + pytest.raises( + ValueError, + _row_tensor_product, + [np.arange(1, 13).reshape((3, 4)), np.arange(1, 13).reshape((4, 3))], + ) + + +def test__row_tensor_product(): + # Testing cases where main input array should not be modified + dm1 = np.arange(1, 17).reshape((4, 4)) + assert np.array_equal(_row_tensor_product([dm1]), dm1) + ones = np.ones(4).reshape((4, 1)) + tp1 = _row_tensor_product([ones, dm1]) + assert np.array_equal(tp1, dm1) + tp2 = _row_tensor_product([dm1, ones]) + assert np.array_equal(tp2, dm1) + + # Testing cases where main input array should be scaled + twos = 2 * ones + tp3 = _row_tensor_product([twos, dm1]) + assert np.array_equal(tp3, 2 * dm1) + tp4 = _row_tensor_product([dm1, twos]) + assert np.array_equal(tp4, 2 * dm1) + + # Testing main cases + dm2 = np.array([[1, 2], [1, 2]]) + dm3 = np.arange(1, 7).reshape((2, 3)) + expected_tp5 = np.array([[1, 2, 3, 2, 4, 6], [4, 5, 6, 8, 10, 12]]) + tp5 = _row_tensor_product([dm2, dm3]) + assert np.array_equal(tp5, expected_tp5) + expected_tp6 = np.array([[1, 2, 2, 4, 3, 6], [4, 8, 5, 10, 6, 12]]) + tp6 = _row_tensor_product([dm3, dm2]) + assert np.array_equal(tp6, expected_tp6) + + +# Common code + + +def _find_knots_lower_bounds(x, knots): + """Finds knots lower bounds for given values. + + Returns an array of indices ``I`` such that + ``0 <= I[i] <= knots.size - 2`` for all ``i`` + and + ``knots[I[i]] < x[i] <= knots[I[i] + 1]`` if + ``np.min(knots) < x[i] <= np.max(knots)``, + ``I[i] = 0`` if ``x[i] <= np.min(knots)`` + ``I[i] = knots.size - 2`` if ``np.max(knots) < x[i]`` + + :param x: The 1-d array values whose knots lower bounds are to be found. + :param knots: The 1-d array knots used for cubic spline parametrization, + must be sorted in ascending order. + :return: An array of knots lower bounds indices. + """ + lb = np.searchsorted(knots, x) - 1 + + # I[i] = 0 for x[i] <= np.min(knots) + lb[lb == -1] = 0 + + # I[i] = knots.size - 2 for x[i] > np.max(knots) + lb[lb == knots.size - 1] = knots.size - 2 + + return lb + + +def _compute_base_functions(x, knots): + """Computes base functions used for building cubic splines basis. + + .. note:: See 'Generalized Additive Models', Simon N. Wood, 2006, p. 146 + and for the special treatment of ``x`` values outside ``knots`` range + see 'mgcv' source code, file 'mgcv.c', function 'crspl()', l.249 + + :param x: The 1-d array values for which base functions should be computed. + :param knots: The 1-d array knots used for cubic spline parametrization, + must be sorted in ascending order. + :return: 4 arrays corresponding to the 4 base functions ajm, ajp, cjm, cjp + + the 1-d array of knots lower bounds indices corresponding to + the given ``x`` values. + """ + j = _find_knots_lower_bounds(x, knots) + + h = knots[1:] - knots[:-1] + hj = h[j] + xj1_x = knots[j + 1] - x + x_xj = x - knots[j] + + ajm = xj1_x / hj + ajp = x_xj / hj + + cjm_3 = xj1_x * xj1_x * xj1_x / (6.0 * hj) + cjm_3[x > np.max(knots)] = 0.0 + cjm_1 = hj * xj1_x / 6.0 + cjm = cjm_3 - cjm_1 + + cjp_3 = x_xj * x_xj * x_xj / (6.0 * hj) + cjp_3[x < np.min(knots)] = 0.0 + cjp_1 = hj * x_xj / 6.0 + cjp = cjp_3 - cjp_1 + + return ajm, ajp, cjm, cjp, j + + +def _absorb_constraints(design_matrix, constraints): + """Absorb model parameters constraints into the design matrix. + + :param design_matrix: The (2-d array) initial design matrix. + :param constraints: The 2-d array defining initial model parameters + (``betas``) constraints (``np.dot(constraints, betas) = 0``). + :return: The new design matrix with absorbed parameters constraints. + + :raise ImportError: if scipy is not found, used for ``scipy.linalg.qr()`` + which is cleaner than numpy's version requiring a call like + ``qr(..., mode='complete')`` to get a full QR decomposition. + """ + try: + from scipy import linalg + except ImportError: # pragma: no cover + raise ImportError("Cubic spline functionality requires scipy.") + + m = constraints.shape[0] + q, r = linalg.qr(np.transpose(constraints)) + + return np.dot(design_matrix, q[:, m:]) + + +def _get_free_crs_dmatrix(x, knots, cyclic=False): + """Builds an unconstrained cubic regression spline design matrix. + + Returns design matrix with dimensions ``len(x) x n`` + for a cubic regression spline smoother + where + - ``n = len(knots)`` for natural CRS + - ``n = len(knots) - 1`` for cyclic CRS + + .. note:: See 'Generalized Additive Models', Simon N. Wood, 2006, p. 145 + + :param x: The 1-d array values. + :param knots: The 1-d array knots used for cubic spline parametrization, + must be sorted in ascending order. + :param cyclic: Indicates whether used cubic regression splines should + be cyclic or not. Default is ``False``. + :return: The (2-d array) design matrix. + """ + n = knots.size + if cyclic: + x = _map_cyclic(x, min(knots), max(knots)) + n -= 1 + + ajm, ajp, cjm, cjp, j = _compute_base_functions(x, knots) + + j1 = j + 1 + if cyclic: + j1[j1 == n] = 0 + + i = np.identity(n) + + if cyclic: + f = _get_cyclic_f(knots) + else: + f = _get_natural_f(knots) + + dmt = ajm * i[j, :].T + ajp * i[j1, :].T + cjm * f[j, :].T + cjp * f[j1, :].T + + return dmt.T + + +def _get_crs_dmatrix(x, knots, constraints=None, cyclic=False): + """Builds a cubic regression spline design matrix. + + Returns design matrix with dimensions len(x) x n + where: + - ``n = len(knots) - nrows(constraints)`` for natural CRS + - ``n = len(knots) - nrows(constraints) - 1`` for cyclic CRS + for a cubic regression spline smoother + + :param x: The 1-d array values. + :param knots: The 1-d array knots used for cubic spline parametrization, + must be sorted in ascending order. + :param constraints: The 2-d array defining model parameters (``betas``) + constraints (``np.dot(constraints, betas) = 0``). + :param cyclic: Indicates whether used cubic regression splines should + be cyclic or not. Default is ``False``. + :return: The (2-d array) design matrix. + """ + dm = _get_free_crs_dmatrix(x, knots, cyclic) + if constraints is not None: + dm = _absorb_constraints(dm, constraints) + + return dm + + +def _get_te_dmatrix(design_matrices, constraints=None): + """Builds tensor product design matrix, given the marginal design matrices. + + :param design_matrices: A sequence of 2-d arrays (marginal design matrices). + :param constraints: The 2-d array defining model parameters (``betas``) + constraints (``np.dot(constraints, betas) = 0``). + :return: The (2-d array) design matrix. + """ + dm = _row_tensor_product(design_matrices) + if constraints is not None: + dm = _absorb_constraints(dm, constraints) + + return dm + + +# Stateful Transforms + + +def _get_all_sorted_knots( + x, n_inner_knots=None, inner_knots=None, lower_bound=None, upper_bound=None +): + """Gets all knots locations with lower and upper exterior knots included. + + If needed, inner knots are computed as equally spaced quantiles of the + input data falling between given lower and upper bounds. + + :param x: The 1-d array data values. + :param n_inner_knots: Number of inner knots to compute. + :param inner_knots: Provided inner knots if any. + :param lower_bound: The lower exterior knot location. If unspecified, the + minimum of ``x`` values is used. + :param upper_bound: The upper exterior knot location. If unspecified, the + maximum of ``x`` values is used. + :return: The array of ``n_inner_knots + 2`` distinct knots. + + :raise ValueError: for various invalid parameters sets or if unable to + compute ``n_inner_knots + 2`` distinct knots. + """ + if lower_bound is None and x.size == 0: + raise ValueError( + "Cannot set lower exterior knot location: empty " + "input data and lower_bound not specified." + ) + elif lower_bound is None and x.size != 0: + lower_bound = np.min(x) + + if upper_bound is None and x.size == 0: + raise ValueError( + "Cannot set upper exterior knot location: empty " + "input data and upper_bound not specified." + ) + elif upper_bound is None and x.size != 0: + upper_bound = np.max(x) + + if upper_bound < lower_bound: + raise ValueError( + "lower_bound > upper_bound (%r > %r)" % (lower_bound, upper_bound) + ) + + if inner_knots is None and n_inner_knots is not None: + if n_inner_knots < 0: + raise ValueError( + "Invalid requested number of inner knots: %r" % (n_inner_knots,) + ) + + x = x[(lower_bound <= x) & (x <= upper_bound)] + x = np.unique(x) + + if x.size != 0: + inner_knots_q = np.linspace(0, 100, n_inner_knots + 2)[1:-1] + # .tolist() is necessary to work around a bug in numpy 1.8 + inner_knots = np.asarray(np.percentile(x, inner_knots_q.tolist())) + elif n_inner_knots == 0: + inner_knots = np.array([]) + else: + raise ValueError( + "No data values between lower_bound(=%r) and " + "upper_bound(=%r): cannot compute requested " + "%r inner knot(s)." % (lower_bound, upper_bound, n_inner_knots) + ) + elif inner_knots is not None: + inner_knots = np.unique(inner_knots) + if n_inner_knots is not None and n_inner_knots != inner_knots.size: + raise ValueError( + "Needed number of inner knots=%r does not match " + "provided number of inner knots=%r." % (n_inner_knots, inner_knots.size) + ) + n_inner_knots = inner_knots.size + if np.any(inner_knots < lower_bound): + raise ValueError( + "Some knot values (%s) fall below lower bound " + "(%r)." % (inner_knots[inner_knots < lower_bound], lower_bound) + ) + if np.any(inner_knots > upper_bound): + raise ValueError( + "Some knot values (%s) fall above upper bound " + "(%r)." % (inner_knots[inner_knots > upper_bound], upper_bound) + ) + else: + raise ValueError("Must specify either 'n_inner_knots' or 'inner_knots'.") + + all_knots = np.concatenate(([lower_bound, upper_bound], inner_knots)) + all_knots = np.unique(all_knots) + if all_knots.size != n_inner_knots + 2: + raise ValueError( + "Unable to compute n_inner_knots(=%r) + 2 distinct " + "knots: %r data value(s) found between " + "lower_bound(=%r) and upper_bound(=%r)." + % (n_inner_knots, x.size, lower_bound, upper_bound) + ) + + return all_knots + + +def test__get_all_sorted_knots(): + import pytest + + pytest.raises(ValueError, _get_all_sorted_knots, np.array([]), -1) + pytest.raises(ValueError, _get_all_sorted_knots, np.array([]), 0) + pytest.raises(ValueError, _get_all_sorted_knots, np.array([]), 0, lower_bound=1) + pytest.raises(ValueError, _get_all_sorted_knots, np.array([]), 0, upper_bound=5) + pytest.raises( + ValueError, _get_all_sorted_knots, np.array([]), 0, lower_bound=3, upper_bound=1 + ) + assert np.array_equal( + _get_all_sorted_knots(np.array([]), 0, lower_bound=1, upper_bound=5), [1, 5] + ) + pytest.raises( + ValueError, _get_all_sorted_knots, np.array([]), 0, lower_bound=1, upper_bound=1 + ) + x = np.arange(6) * 2 + pytest.raises(ValueError, _get_all_sorted_knots, x, -2) + assert np.array_equal(_get_all_sorted_knots(x, 0), [0, 10]) + assert np.array_equal( + _get_all_sorted_knots(x, 0, lower_bound=3, upper_bound=8), [3, 8] + ) + assert np.array_equal( + _get_all_sorted_knots(x, 2, lower_bound=1, upper_bound=9), [1, 4, 6, 9] + ) + pytest.raises(ValueError, _get_all_sorted_knots, x, 2, lower_bound=1, upper_bound=3) + pytest.raises( + ValueError, _get_all_sorted_knots, x, 1, lower_bound=1.3, upper_bound=1.4 + ) + assert np.array_equal( + _get_all_sorted_knots(x, 1, lower_bound=1, upper_bound=3), [1, 2, 3] + ) + pytest.raises(ValueError, _get_all_sorted_knots, x, 1, lower_bound=2, upper_bound=3) + pytest.raises(ValueError, _get_all_sorted_knots, x, 1, inner_knots=[2, 3]) + pytest.raises(ValueError, _get_all_sorted_knots, x, lower_bound=2, upper_bound=3) + assert np.array_equal(_get_all_sorted_knots(x, inner_knots=[3, 7]), [0, 3, 7, 10]) + assert np.array_equal( + _get_all_sorted_knots(x, inner_knots=[3, 7], lower_bound=2), [2, 3, 7, 10] + ) + pytest.raises( + ValueError, _get_all_sorted_knots, x, inner_knots=[3, 7], lower_bound=4 + ) + pytest.raises( + ValueError, _get_all_sorted_knots, x, inner_knots=[3, 7], upper_bound=6 + ) + + +def _get_centering_constraint_from_dmatrix(design_matrix): + """Computes the centering constraint from the given design matrix. + + We want to ensure that if ``b`` is the array of parameters, our + model is centered, ie ``np.mean(np.dot(design_matrix, b))`` is zero. + We can rewrite this as ``np.dot(c, b)`` being zero with ``c`` a 1-row + constraint matrix containing the mean of each column of ``design_matrix``. + + :param design_matrix: The 2-d array design matrix. + :return: A 2-d array (1 x ncols(design_matrix)) defining the + centering constraint. + """ + return design_matrix.mean(axis=0).reshape((1, design_matrix.shape[1])) + + +class CubicRegressionSpline(object): + """Base class for cubic regression spline stateful transforms + + This class contains all the functionality for the following stateful + transforms: + - ``cr(x, df=None, knots=None, lower_bound=None, upper_bound=None, constraints=None)`` + for natural cubic regression spline + - ``cc(x, df=None, knots=None, lower_bound=None, upper_bound=None, constraints=None)`` + for cyclic cubic regression spline + """ + + common_doc = """ + :arg df: The number of degrees of freedom to use for this spline. The + return value will have this many columns. You must specify at least one + of ``df`` and ``knots``. + :arg knots: The interior knots to use for the spline. If unspecified, then + equally spaced quantiles of the input data are used. You must specify at + least one of ``df`` and ``knots``. + :arg lower_bound: The lower exterior knot location. + :arg upper_bound: The upper exterior knot location. + :arg constraints: Either a 2-d array defining general linear constraints + (that is ``np.dot(constraints, betas)`` is zero, where ``betas`` denotes + the array of *initial* parameters, corresponding to the *initial* + unconstrained design matrix), or the string + ``'center'`` indicating that we should apply a centering constraint + (this constraint will be computed from the input data, remembered and + re-used for prediction from the fitted model). + The constraints are absorbed in the resulting design matrix which means + that the model is actually rewritten in terms of + *unconstrained* parameters. For more details see :ref:`spline-regression`. + + This is a stateful transforms (for details see + :ref:`stateful-transforms`). If ``knots``, ``lower_bound``, or + ``upper_bound`` are not specified, they will be calculated from the data + and then the chosen values will be remembered and re-used for prediction + from the fitted model. + + Using this function requires scipy be installed. + + .. versionadded:: 0.3.0 + """ + + def __init__(self, name, cyclic): + self._name = name + self._cyclic = cyclic + self._tmp = {} + self._all_knots = None + self._constraints = None + + def memorize_chunk( + self, + x, + df=None, + knots=None, + lower_bound=None, + upper_bound=None, + constraints=None, + ): + args = { + "df": df, + "knots": knots, + "lower_bound": lower_bound, + "upper_bound": upper_bound, + "constraints": constraints, + } + self._tmp["args"] = args + + x = np.atleast_1d(x) + if x.ndim == 2 and x.shape[1] == 1: + x = x[:, 0] + if x.ndim > 1: + raise ValueError( + "Input to %r must be 1-d, or a 2-d column vector." % (self._name,) + ) + + self._tmp.setdefault("xs", []).append(x) + + def memorize_finish(self): + args = self._tmp["args"] + xs = self._tmp["xs"] + # Guards against invalid subsequent memorize_chunk() calls. + del self._tmp + + x = np.concatenate(xs) + if args["df"] is None and args["knots"] is None: + raise ValueError("Must specify either 'df' or 'knots'.") + + constraints = args["constraints"] + n_constraints = 0 + if constraints is not None: + if safe_string_eq(constraints, "center"): + # Here we collect only number of constraints, + # actual centering constraint will be computed after all_knots + n_constraints = 1 + else: + constraints = np.atleast_2d(constraints) + if constraints.ndim != 2: + raise ValueError("Constraints must be 2-d array or 1-d vector.") + n_constraints = constraints.shape[0] + + n_inner_knots = None + if args["df"] is not None: + min_df = 1 + if not self._cyclic and n_constraints == 0: + min_df = 2 + if args["df"] < min_df: + raise ValueError( + "'df'=%r must be greater than or equal to %r." + % (args["df"], min_df) + ) + n_inner_knots = args["df"] - 2 + n_constraints + if self._cyclic: + n_inner_knots += 1 + self._all_knots = _get_all_sorted_knots( + x, + n_inner_knots=n_inner_knots, + inner_knots=args["knots"], + lower_bound=args["lower_bound"], + upper_bound=args["upper_bound"], + ) + if constraints is not None: + if safe_string_eq(constraints, "center"): + # Now we can compute centering constraints + constraints = _get_centering_constraint_from_dmatrix( + _get_free_crs_dmatrix(x, self._all_knots, cyclic=self._cyclic) + ) + + df_before_constraints = self._all_knots.size + if self._cyclic: + df_before_constraints -= 1 + if constraints.shape[1] != df_before_constraints: + raise ValueError( + "Constraints array should have %r columns but" + " %r found." % (df_before_constraints, constraints.shape[1]) + ) + self._constraints = constraints + + def transform( + self, + x, + df=None, + knots=None, + lower_bound=None, + upper_bound=None, + constraints=None, + ): + x_orig = x + x = np.atleast_1d(x) + if x.ndim == 2 and x.shape[1] == 1: + x = x[:, 0] + if x.ndim > 1: + raise ValueError( + "Input to %r must be 1-d, or a 2-d column vector." % (self._name,) + ) + dm = _get_crs_dmatrix( + x, self._all_knots, self._constraints, cyclic=self._cyclic + ) + if have_pandas: + if isinstance(x_orig, (pandas.Series, pandas.DataFrame)): + dm = pandas.DataFrame(dm) + dm.index = x_orig.index + return dm + + __getstate__ = no_pickling + + +class CR(CubicRegressionSpline): + """cr(x, df=None, knots=None, lower_bound=None, upper_bound=None, constraints=None) + + Generates a natural cubic spline basis for ``x`` + (with the option of absorbing centering or more general parameters + constraints), allowing non-linear fits. The usual usage is something like:: + + y ~ 1 + cr(x, df=5, constraints='center') + + to fit ``y`` as a smooth function of ``x``, with 5 degrees of freedom + given to the smooth, and centering constraint absorbed in + the resulting design matrix. Note that in this example, due to the centering + constraint, 6 knots will get computed from the input data ``x`` + to achieve 5 degrees of freedom. + + + .. note:: This function reproduce the cubic regression splines 'cr' and 'cs' + as implemented in the R package 'mgcv' (GAM modelling). + + """ + + # Under python -OO, __doc__ will be defined but set to None + if __doc__: + __doc__ += CubicRegressionSpline.common_doc + + def __init__(self): + CubicRegressionSpline.__init__(self, name="cr", cyclic=False) + + +cr = stateful_transform(CR) + + +class CC(CubicRegressionSpline): + """cc(x, df=None, knots=None, lower_bound=None, upper_bound=None, constraints=None) + + Generates a cyclic cubic spline basis for ``x`` + (with the option of absorbing centering or more general parameters + constraints), allowing non-linear fits. The usual usage is something like:: + + y ~ 1 + cc(x, df=7, constraints='center') + + to fit ``y`` as a smooth function of ``x``, with 7 degrees of freedom + given to the smooth, and centering constraint absorbed in + the resulting design matrix. Note that in this example, due to the centering + and cyclic constraints, 9 knots will get computed from the input data ``x`` + to achieve 7 degrees of freedom. + + .. note:: This function reproduce the cubic regression splines 'cc' + as implemented in the R package 'mgcv' (GAM modelling). + + """ + + # Under python -OO, __doc__ will be defined but set to None + if __doc__: + __doc__ += CubicRegressionSpline.common_doc + + def __init__(self): + CubicRegressionSpline.__init__(self, name="cc", cyclic=True) + + +cc = stateful_transform(CC) + + +def test_crs_errors(): + import pytest + + # Invalid 'x' shape + pytest.raises(ValueError, cr, np.arange(16).reshape((4, 4)), df=4) + pytest.raises(ValueError, CR().transform, np.arange(16).reshape((4, 4)), df=4) + # Should provide at least 'df' or 'knots' + pytest.raises(ValueError, cr, np.arange(50)) + # Invalid constraints shape + pytest.raises( + ValueError, + cr, + np.arange(50), + df=4, + constraints=np.arange(27).reshape((3, 3, 3)), + ) + # Invalid nb of columns in constraints + # (should have df + 1 = 5, but 6 provided) + pytest.raises(ValueError, cr, np.arange(50), df=4, constraints=np.arange(6)) + # Too small 'df' for natural cubic spline + pytest.raises(ValueError, cr, np.arange(50), df=1) + # Too small 'df' for cyclic cubic spline + pytest.raises(ValueError, cc, np.arange(50), df=0) + + +def test_crs_compat(): + from patsy.test_state import check_stateful + from patsy.test_splines_crs_data import ( + R_crs_test_x, + R_crs_test_data, + R_crs_num_tests, + ) + + lines = R_crs_test_data.split("\n") + tests_ran = 0 + start_idx = lines.index("--BEGIN TEST CASE--") + while True: + if not lines[start_idx] == "--BEGIN TEST CASE--": + break + start_idx += 1 + stop_idx = lines.index("--END TEST CASE--", start_idx) + block = lines[start_idx:stop_idx] + test_data = {} + for line in block: + key, value = line.split("=", 1) + test_data[key] = value + # Translate the R output into Python calling conventions + adjust_df = 0 + if test_data["spline_type"] == "cr" or test_data["spline_type"] == "cs": + spline_type = CR + elif test_data["spline_type"] == "cc": + spline_type = CC + adjust_df += 1 + else: + raise ValueError( + "Unrecognized spline type %r" % (test_data["spline_type"],) + ) + kwargs = {} + if test_data["absorb_cons"] == "TRUE": + kwargs["constraints"] = "center" + adjust_df += 1 + if test_data["knots"] != "None": + all_knots = np.asarray(eval(test_data["knots"])) + all_knots.sort() + kwargs["knots"] = all_knots[1:-1] + kwargs["lower_bound"] = all_knots[0] + kwargs["upper_bound"] = all_knots[-1] + else: + kwargs["df"] = eval(test_data["nb_knots"]) - adjust_df + output = np.asarray(eval(test_data["output"])) + # Do the actual test + check_stateful(spline_type, False, R_crs_test_x, output, **kwargs) + tests_ran += 1 + # Set up for the next one + start_idx = stop_idx + 1 + assert tests_ran == R_crs_num_tests + + +test_crs_compat.slow = True + + +def test_crs_with_specific_constraint(): + from patsy.highlevel import incr_dbuilder, build_design_matrices, dmatrix + + x = (-1.5) ** np.arange(20) + # Hard coded R values for smooth: s(x, bs="cr", k=5) + # R> knots <- smooth$xp + knots_R = np.array( + [ + -2216.837820053100585937, + -50.456909179687500000, + -0.250000000000000000, + 33.637939453125000000, + 1477.891880035400390625, + ] + ) + # R> centering.constraint <- t(qr.X(attr(smooth, "qrc"))) + centering_constraint_R = np.array( + [ + [ + 0.064910676323168478574, + 1.4519875239407085132, + -2.1947446912471946234, + 1.6129783104357671153, + 0.064868180547550072235, + ] + ] + ) + # values for which we want a prediction + new_x = np.array([-3000.0, -200.0, 300.0, 2000.0]) + result1 = dmatrix( + "cr(new_x, knots=knots_R[1:-1], " + "lower_bound=knots_R[0], upper_bound=knots_R[-1], " + "constraints=centering_constraint_R)" + ) + + data_chunked = [{"x": x[:10]}, {"x": x[10:]}] + new_data = {"x": new_x} + builder = incr_dbuilder( + "cr(x, df=4, constraints='center')", lambda: iter(data_chunked) + ) + result2 = build_design_matrices([builder], new_data)[0] + + assert np.allclose(result1, result2, rtol=1e-12, atol=0.0) + + +class TE(object): + """te(s1, .., sn, constraints=None) + + Generates smooth of several covariates as a tensor product of the bases + of marginal univariate smooths ``s1, .., sn``. The marginal smooths are + required to transform input univariate data into some kind of smooth + functions basis producing a 2-d array output with the ``(i, j)`` element + corresponding to the value of the ``j`` th basis function at the ``i`` th + data point. + The resulting basis dimension is the product of the basis dimensions of + the marginal smooths. The usual usage is something like:: + + y ~ 1 + te(cr(x1, df=5), cc(x2, df=6), constraints='center') + + to fit ``y`` as a smooth function of both ``x1`` and ``x2``, with a natural + cubic spline for ``x1`` marginal smooth and a cyclic cubic spline for + ``x2`` (and centering constraint absorbed in the resulting design matrix). + + :arg constraints: Either a 2-d array defining general linear constraints + (that is ``np.dot(constraints, betas)`` is zero, where ``betas`` denotes + the array of *initial* parameters, corresponding to the *initial* + unconstrained design matrix), or the string + ``'center'`` indicating that we should apply a centering constraint + (this constraint will be computed from the input data, remembered and + re-used for prediction from the fitted model). + The constraints are absorbed in the resulting design matrix which means + that the model is actually rewritten in terms of + *unconstrained* parameters. For more details see :ref:`spline-regression`. + + Using this function requires scipy be installed. + + .. note:: This function reproduce the tensor product smooth 'te' as + implemented in the R package 'mgcv' (GAM modelling). + See also 'Generalized Additive Models', Simon N. Wood, 2006, pp 158-163 + + .. versionadded:: 0.3.0 + """ + + def __init__(self): + self._tmp = {} + self._constraints = None + + def memorize_chunk(self, *args, **kwargs): + constraints = self._tmp.setdefault("constraints", kwargs.get("constraints")) + if safe_string_eq(constraints, "center"): + args_2d = [] + for arg in args: + arg = atleast_2d_column_default(arg) + if arg.ndim != 2: + raise ValueError( + "Each tensor product argument must be " + "a 2-d array or 1-d vector." + ) + args_2d.append(arg) + + tp = _row_tensor_product(args_2d) + self._tmp.setdefault("count", 0) + self._tmp["count"] += tp.shape[0] + + chunk_sum = np.atleast_2d(tp.sum(axis=0)) + self._tmp.setdefault("sum", np.zeros(chunk_sum.shape)) + self._tmp["sum"] += chunk_sum + + def memorize_finish(self): + tmp = self._tmp + constraints = self._tmp["constraints"] + # Guards against invalid subsequent memorize_chunk() calls. + del self._tmp + + if constraints is not None: + if safe_string_eq(constraints, "center"): + constraints = np.atleast_2d(tmp["sum"] / tmp["count"]) + else: + constraints = np.atleast_2d(constraints) + if constraints.ndim != 2: + raise ValueError("Constraints must be 2-d array or 1-d vector.") + + self._constraints = constraints + + def transform(self, *args, **kwargs): + args_2d = [] + for arg in args: + arg = atleast_2d_column_default(arg) + if arg.ndim != 2: + raise ValueError( + "Each tensor product argument must be a 2-d array or 1-d vector." + ) + args_2d.append(arg) + + return _get_te_dmatrix(args_2d, self._constraints) + + __getstate__ = no_pickling + + +te = stateful_transform(TE) + + +def test_te_errors(): + import pytest + + x = np.arange(27) + # Invalid input shape + pytest.raises(ValueError, te, x.reshape((3, 3, 3))) + pytest.raises(ValueError, te, x.reshape((3, 3, 3)), constraints="center") + # Invalid constraints shape + pytest.raises(ValueError, te, x, constraints=np.arange(8).reshape((2, 2, 2))) + + +def test_te_1smooth(): + from patsy.splines import bs + + # Tensor product of 1 smooth covariate should be the same + # as the smooth alone + x = (-1.5) ** np.arange(20) + assert np.allclose(cr(x, df=6), te(cr(x, df=6))) + assert np.allclose(cc(x, df=5), te(cc(x, df=5))) + assert np.allclose(bs(x, df=4), te(bs(x, df=4))) + # Adding centering constraint to tensor product + assert np.allclose( + cr(x, df=3, constraints="center"), te(cr(x, df=4), constraints="center") + ) + # Adding specific constraint + center_constraint = np.arange(1, 5) + assert np.allclose( + cr(x, df=3, constraints=center_constraint), + te(cr(x, df=4), constraints=center_constraint), + ) + + +def test_te_2smooths(): + from patsy.highlevel import incr_dbuilder, build_design_matrices + + x1 = (-1.5) ** np.arange(20) + x2 = (1.6) ** np.arange(20) + # Hard coded R results for smooth: te(x1, x2, bs=c("cs", "cc"), k=c(5,7)) + # Without centering constraint: + dmatrix_R_nocons = np.array( + [ + [ + -4.4303024184609255207e-06, + 7.9884438387230142235e-06, + 9.7987758194797719025e-06, + -7.2894213245475212959e-08, + 1.5907686862964493897e-09, + -3.2565884983072595159e-11, + 0.0170749607855874667439, + -3.0788499835965849050e-02, + -3.7765754357352458725e-02, + 2.8094376299826799787e-04, + -6.1310290747349201414e-06, + 1.2551314933193442915e-07, + -0.26012671685838206770, + 4.6904420337437874311e-01, + 0.5753384627946153129230, + -4.2800085814700449330e-03, + 9.3402525733484874533e-05, + -1.9121170389937518131e-06, + -0.0904312240489447832781, + 1.6305991924427923334e-01, + 2.0001237112941641638e-01, + -1.4879148887003382663e-03, + 3.2470731316462736135e-05, + -6.6473404365914134499e-07, + 2.0447857920168824846e-05, + -3.6870296695050991799e-05, + -4.5225801045409022233e-05, + 3.3643990293641665710e-07, + -7.3421200200015877329e-09, + 1.5030635073660743297e-10, + ], + [ + -9.4006130602653794302e-04, + 7.8681398069163730347e-04, + 2.4573006857381437217e-04, + -1.4524712230452725106e-04, + 7.8216741353106329551e-05, + -3.1304283003914264551e-04, + 3.6231183382798337611064, + -3.0324832476174168328e00, + -9.4707559178211142559e-01, + 5.5980126937492580286e-01, + -3.0145747744342332730e-01, + 1.2065077148806895302e00, + -35.17561267504181188315, + 2.9441339255948005160e01, + 9.1948319320782125885216, + -5.4349184288245195873e00, + 2.9267472035096449012e00, + -1.1713569391233907169e01, + 34.0275626863976370373166, + -2.8480442582712722555e01, + -8.8947340548151565542e00, + 5.2575353623762932642e00, + -2.8312249982592527786e00, + 1.1331265795534763541e01, + 7.9462158845078978420e-01, + -6.6508361863670617531e-01, + -2.0771242914526857892e-01, + 1.2277550230353953542e-01, + -6.6115593588420035198e-02, + 2.6461103043402139923e-01, + ], + ] + ) + # With centering constraint: + dmatrix_R_cons = np.array( + [ + [ + 0.00329998606323867252343, + 1.6537431155796576600e-04, + -1.2392262709790753433e-04, + 6.5405304166706783407e-05, + -6.6764045799537624095e-05, + -0.1386431081763726258504, + 0.124297283800864313830, + -3.5487293655619825405e-02, + -3.0527115315785902268e-03, + 5.2009247643311604277e-04, + -0.00384203992301702674378, + -0.058901915802819435064, + 0.266422358491648914036, + 0.5739281693874087597607, + -1.3171008503525844392e-03, + 8.2573456631878912413e-04, + 6.6730833453016958831e-03, + -0.1467677784718444955470, + 0.220757650934837484913, + 0.1983127687880171796664, + -1.6269930328365173316e-03, + -1.7785892412241208812e-03, + -3.2702835436351201243e-03, + -4.3252183044300757109e-02, + 4.3403766976235179376e-02, + 3.5973406402893762387e-05, + -5.4035858568225075046e-04, + 2.9565209382794241247e-04, + -2.2769990750264097637e-04, + ], + [ + 0.41547954838956052681098, + 1.9843570584107707994e-02, + -1.5746590234791378593e-02, + 8.3171184312221431434e-03, + -8.7233014052017516377e-03, + -15.9926770785086258541696, + 16.503663226274017716833, + -6.6005803955894726265e-01, + 1.3986092022708346283e-01, + -2.3516913533670955050e-01, + 0.72251037497207359905360, + -9.827337059999853963177, + 3.917078117294827688255, + 9.0171773596973618936090, + -5.0616811270787671617e00, + 3.0189990249009683865e00, + -1.0872720629943064097e01, + 26.9308504460453121964747, + -21.212262927009287949431, + -9.1088328555582247503253, + 5.2400156972500298025e00, + -3.0593641098325474736e00, + 1.0919392118399086300e01, + -4.6564290223265718538e00, + 4.8071307441606982991e00, + -1.9748377005689798924e-01, + 5.4664183716965096538e-02, + -2.8871392916916285148e-02, + 2.3592766838010845176e-01, + ], + ] + ) + new_x1 = np.array([11.390625, 656.84083557128906250]) + new_x2 = np.array([16.777216000000006346, 1844.6744073709567147]) + new_data = {"x1": new_x1, "x2": new_x2} + data_chunked = [{"x1": x1[:10], "x2": x2[:10]}, {"x1": x1[10:], "x2": x2[10:]}] + + builder = incr_dbuilder( + "te(cr(x1, df=5), cc(x2, df=6)) - 1", lambda: iter(data_chunked) + ) + dmatrix_nocons = build_design_matrices([builder], new_data)[0] + assert np.allclose(dmatrix_nocons, dmatrix_R_nocons, rtol=1e-12, atol=0.0) + + builder = incr_dbuilder( + "te(cr(x1, df=5), cc(x2, df=6), constraints='center') - 1", + lambda: iter(data_chunked), + ) + dmatrix_cons = build_design_matrices([builder], new_data)[0] + assert np.allclose(dmatrix_cons, dmatrix_R_cons, rtol=1e-12, atol=0.0) + + +def test_te_3smooths(): + from patsy.highlevel import incr_dbuilder, build_design_matrices + + x1 = (-1.5) ** np.arange(20) + x2 = (1.6) ** np.arange(20) + x3 = (-1.2) ** np.arange(20) + # Hard coded R results for smooth: te(x1, x2, x3, bs=c("cr", "cs", "cc"), k=c(3,3,4)) + design_matrix_R = np.array( + [ + [ + 7.2077663709837084334e-05, + 2.0648333344343273131e-03, + -4.7934014082310591768e-04, + 2.3923430783992746568e-04, + 6.8534265421922660466e-03, + -1.5909867344112936776e-03, + -6.8057712777151204314e-09, + -1.9496724335203412851e-07, + 4.5260614658693259131e-08, + 0.0101479754187435277507, + 0.290712501531622591333, + -0.067487370093906928759, + 0.03368233306025386619709, + 0.9649092451763204847381, + -0.2239985793289433757547, + -9.5819975394704535133e-07, + -2.7449874082511405643e-05, + 6.3723431275833230217e-06, + -1.5205851762850489204e-04, + -0.00435607204539782688624, + 0.00101123909269346416370, + -5.0470024059694933508e-04, + -1.4458319360584082416e-02, + 3.3564223914790921634e-03, + 1.4357783514933466209e-08, + 4.1131230514870551983e-07, + -9.5483976834512651038e-08, + ] + ] + ) + new_data = { + "x1": -38.443359375000000000, + "x2": 68.719476736000032702, + "x3": -5.1597803519999985156, + } + data_chunked = [ + {"x1": x1[:10], "x2": x2[:10], "x3": x3[:10]}, + {"x1": x1[10:], "x2": x2[10:], "x3": x3[10:]}, + ] + builder = incr_dbuilder( + "te(cr(x1, df=3), cr(x2, df=3), cc(x3, df=3)) - 1", lambda: iter(data_chunked) + ) + design_matrix = build_design_matrices([builder], new_data)[0] + assert np.allclose(design_matrix, design_matrix_R, rtol=1e-12, atol=0.0) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/missing.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/missing.py new file mode 100644 index 0000000000000000000000000000000000000000..0ea262b5c561c75c8ce4e36dad8a53db7df9538a --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/missing.py @@ -0,0 +1,269 @@ +# This file is part of Patsy +# Copyright (C) 2013 Nathaniel Smith +# See file LICENSE.txt for license information. + +# Missing data detection/handling + +# First, how do we represent missing data? (i.e., which values count as +# "missing"?) In the long run, we want to use numpy's NA support... but that +# doesn't exist yet. Until then, people use various sorts of ad-hoc +# things. Some things that might be considered NA: +# NA (eventually) +# NaN (in float or object arrays) +# None (in object arrays) +# np.ma.masked (in numpy.ma masked arrays) +# Pandas compatibility considerations: +# For numeric arrays, None is unconditionally converted to NaN. +# For object arrays (including string arrays!), None and NaN are preserved, +# but pandas.isnull() returns True for both. +# np.ma compatibility considerations: +# Preserving array subtypes is a huge pain, because it means that we can't +# just call 'asarray' and be done... we already jump through tons of hoops +# to write code that can handle both ndarray's and pandas objects, and +# just thinking about adding another item to this list makes me tired. So +# for now we don't support np.ma missing values. Use pandas! + +# Next, what should be done once we find missing data? R's options: +# -- throw away those rows (from all aligned matrices) +# -- with or without preserving information on which rows were discarded +# -- error out +# -- carry on +# The 'carry on' option requires that we have some way to represent NA in our +# output array. To avoid further solidifying the use of NaN for this purpose, +# we'll leave this option out for now, until real NA support is +# available. Also, we always preserve information on which rows were +# discarded, using the pandas index functionality (currently this is only +# returned to the original caller if they used return_type="dataframe", +# though). + +import numpy as np +from patsy import PatsyError +from patsy.util import safe_isnan, safe_scalar_isnan, no_pickling, assert_no_pickling + +# These are made available in the patsy.* namespace +__all__ = ["NAAction"] + +_valid_NA_types = ["None", "NaN"] +_valid_NA_responses = ["raise", "drop"] + + +def _desc_options(options): + return ", ".join([repr(opt) for opt in options]) + + +class NAAction(object): + """An :class:`NAAction` object defines a strategy for handling missing + data. + + "NA" is short for "Not Available", and is used to refer to any value which + is somehow unmeasured or unavailable. In the long run, it is devoutly + hoped that numpy will gain first-class missing value support. Until then, + we work around this lack as best we're able. + + There are two parts to this: First, we have to determine what counts as + missing data. For numerical data, the default is to treat NaN values + (e.g., ``numpy.nan``) as missing. For categorical data, the default is to + treat NaN values, and also the Python object None, as missing. (This is + consistent with how pandas does things, so if you're already using + None/NaN to mark missing data in your pandas DataFrames, you're good to + go.) + + Second, we have to decide what to do with any missing data when we + encounter it. One option is to simply discard any rows which contain + missing data from our design matrices (``drop``). Another option is to + raise an error (``raise``). A third option would be to simply let the + missing values pass through into the returned design matrices. However, + this last option is not yet implemented, because of the lack of any + standard way to represent missing values in arbitrary numpy matrices; + we're hoping numpy will get this sorted out before we standardize on + anything ourselves. + + You can control how patsy handles missing data through the ``NA_action=`` + argument to functions like :func:`build_design_matrices` and + :func:`dmatrix`. If all you want to do is to choose between ``drop`` and + ``raise`` behaviour, you can pass one of those strings as the + ``NA_action=`` argument directly. If you want more fine-grained control + over how missing values are detected and handled, then you can create an + instance of this class, or your own object that implements the same + interface, and pass that as the ``NA_action=`` argument instead. + """ + + def __init__(self, on_NA="drop", NA_types=["None", "NaN"]): + """The :class:`NAAction` constructor takes the following arguments: + + :arg on_NA: How to handle missing values. The default is ``"drop"``, + which removes all rows from all matrices which contain any missing + values. Also available is ``"raise"``, which raises an exception + when any missing values are encountered. + :arg NA_types: Which rules are used to identify missing values, as a + list of strings. Allowed values are: + + * ``"None"``: treat the ``None`` object as missing in categorical + data. + * ``"NaN"``: treat floating point NaN values as missing in + categorical and numerical data. + + .. versionadded:: 0.2.0 + """ + self.on_NA = on_NA + if self.on_NA not in _valid_NA_responses: + raise ValueError( + "invalid on_NA action %r " + "(should be one of %s)" % (on_NA, _desc_options(_valid_NA_responses)) + ) + if isinstance(NA_types, str): + raise ValueError("NA_types should be a list of strings") + self.NA_types = tuple(NA_types) + for NA_type in self.NA_types: + if NA_type not in _valid_NA_types: + raise ValueError( + "invalid NA_type %r " + "(should be one of %s)" % (NA_type, _desc_options(_valid_NA_types)) + ) + + def is_categorical_NA(self, obj): + """Return True if `obj` is a categorical NA value. + + Note that here `obj` is a single scalar value.""" + if "NaN" in self.NA_types and safe_scalar_isnan(obj): + return True + if "None" in self.NA_types and obj is None: + return True + return False + + def is_numerical_NA(self, arr): + """Returns a 1-d mask array indicating which rows in an array of + numerical values contain at least one NA value. + + Note that here `arr` is a numpy array or pandas DataFrame.""" + mask = np.zeros(arr.shape, dtype=bool) + if "NaN" in self.NA_types: + mask |= np.isnan(arr) + if mask.ndim > 1: + mask = np.any(mask, axis=1) + return mask + + def handle_NA(self, values, is_NAs, origins): + """Takes a set of factor values that may have NAs, and handles them + appropriately. + + :arg values: A list of `ndarray` objects representing the data. + These may be 1- or 2-dimensional, and may be of varying dtype. All + will have the same number of rows (or entries, for 1-d arrays). + :arg is_NAs: A list with the same number of entries as `values`, + containing boolean `ndarray` objects that indicate which rows + contain NAs in the corresponding entry in `values`. + :arg origins: A list with the same number of entries as + `values`, containing information on the origin of each + value. If we encounter a problem with some particular value, we use + the corresponding entry in `origins` as the origin argument when + raising a :class:`PatsyError`. + :returns: A list of new values (which may have a differing number of + rows.) + """ + assert len(values) == len(is_NAs) == len(origins) + if len(values) == 0: + return values + if self.on_NA == "raise": + return self._handle_NA_raise(values, is_NAs, origins) + elif self.on_NA == "drop": + return self._handle_NA_drop(values, is_NAs, origins) + else: # pragma: no cover + assert False + + def _handle_NA_raise(self, values, is_NAs, origins): + for is_NA, origin in zip(is_NAs, origins): + if np.any(is_NA): + raise PatsyError("factor contains missing values", origin) + return values + + def _handle_NA_drop(self, values, is_NAs, origins): + total_mask = np.zeros(is_NAs[0].shape[0], dtype=bool) + for is_NA in is_NAs: + total_mask |= is_NA + good_mask = ~total_mask + # "..." to handle 1- versus 2-dim indexing + return [v[good_mask] if v.ndim == 1 else v[good_mask, ...] for v in values] + + __getstate__ = no_pickling + + +def test_NAAction_basic(): + import pytest + + pytest.raises(ValueError, NAAction, on_NA="pord") + pytest.raises(ValueError, NAAction, NA_types=("NaN", "asdf")) + pytest.raises(ValueError, NAAction, NA_types="NaN") + + assert_no_pickling(NAAction()) + + +def test_NAAction_NA_types_numerical(): + for NA_types in [[], ["NaN"], ["None"], ["NaN", "None"]]: + action = NAAction(NA_types=NA_types) + for extra_shape in [(), (1,), (2,)]: + arr = np.ones((4,) + extra_shape, dtype=float) + nan_rows = [0, 2] + if arr.ndim > 1 and arr.shape[1] > 1: + arr[nan_rows, [0, 1]] = np.nan + else: + arr[nan_rows] = np.nan + exp_NA_mask = np.zeros(4, dtype=bool) + if "NaN" in NA_types: + exp_NA_mask[nan_rows] = True + got_NA_mask = action.is_numerical_NA(arr) + assert np.array_equal(got_NA_mask, exp_NA_mask) + + +def test_NAAction_NA_types_categorical(): + for NA_types in [[], ["NaN"], ["None"], ["NaN", "None"]]: + action = NAAction(NA_types=NA_types) + assert not action.is_categorical_NA("a") + assert not action.is_categorical_NA(1) + assert action.is_categorical_NA(None) == ("None" in NA_types) + assert action.is_categorical_NA(np.nan) == ("NaN" in NA_types) + + +def test_NAAction_drop(): + action = NAAction("drop") + in_values = [ + np.asarray([-1, 2, -1, 4, 5]), + np.asarray([10.0, 20.0, 30.0, 40.0, 50.0]), + np.asarray([[1.0, np.nan], [3.0, 4.0], [10.0, 5.0], [6.0, 7.0], [8.0, np.nan]]), + ] + is_NAs = [ + np.asarray([True, False, True, False, False]), + np.zeros(5, dtype=bool), + np.asarray([True, False, False, False, True]), + ] + out_values = action.handle_NA(in_values, is_NAs, [None] * 3) + assert len(out_values) == 3 + assert np.array_equal(out_values[0], [2, 4]) + assert np.array_equal(out_values[1], [20.0, 40.0]) + assert np.array_equal(out_values[2], [[3.0, 4.0], [6.0, 7.0]]) + + +def test_NAAction_raise(): + action = NAAction(on_NA="raise") + + # no-NA just passes through: + in_arrs = [np.asarray([1.1, 1.2]), np.asarray([1, 2])] + is_NAs = [np.asarray([False, False])] * 2 + got_arrs = action.handle_NA(in_arrs, is_NAs, [None, None]) + assert np.array_equal(got_arrs[0], in_arrs[0]) + assert np.array_equal(got_arrs[1], in_arrs[1]) + + from patsy.origin import Origin + + o1 = Origin("asdf", 0, 1) + o2 = Origin("asdf", 2, 3) + + # NA raises an error with a correct origin + in_idx = np.arange(2) + in_arrs = [np.asarray([1.1, 1.2]), np.asarray([1.0, np.nan])] + is_NAs = [np.asarray([False, False]), np.asarray([False, True])] + try: + action.handle_NA(in_arrs, is_NAs, [o1, o2]) + assert False + except PatsyError as e: + assert e.origin is o2 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/origin.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/origin.py new file mode 100644 index 0000000000000000000000000000000000000000..fcabf21f43fdb2d8d89fbe25d464546b0b4fb44e --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/origin.py @@ -0,0 +1,151 @@ +# This file is part of Patsy +# Copyright (C) 2011-2012 Nathaniel Smith +# See file LICENSE.txt for license information. + +# The core 'origin' tracking system. This point of this is to have machinery +# so if some object is ultimately derived from some portion of a string (e.g., +# a formula), then we can keep track of that, and use it to give proper error +# messages. + +# These are made available in the patsy.* namespace +__all__ = ["Origin"] + + +class Origin(object): + """This represents the origin of some object in some string. + + For example, if we have an object ``x1_obj`` that was produced by parsing + the ``x1`` in the formula ``"y ~ x1:x2"``, then we conventionally keep + track of that relationship by doing:: + + x1_obj.origin = Origin("y ~ x1:x2", 4, 6) + + Then later if we run into a problem, we can do:: + + raise PatsyError("invalid factor", x1_obj) + + and we'll produce a nice error message like:: + + PatsyError: invalid factor + y ~ x1:x2 + ^^ + + Origins are compared by value, and hashable. + """ + + def __init__(self, code, start, end): + self.code = code + self.start = start + self.end = end + + @classmethod + def combine(cls, origin_objs): + """Class method for combining a set of Origins into one large Origin + that spans them. + + Example usage: if we wanted to represent the origin of the "x1:x2" + term, we could do ``Origin.combine([x1_obj, x2_obj])``. + + Single argument is an iterable, and each element in the iterable + should be either: + + * An Origin object + * ``None`` + * An object that has a ``.origin`` attribute which fulfills the above + criteria. + + Returns either an Origin object, or None. + """ + origins = [] + for obj in origin_objs: + if obj is not None and not isinstance(obj, Origin): + obj = obj.origin + if obj is None: + continue + origins.append(obj) + if not origins: + return None + codes = set([o.code for o in origins]) + assert len(codes) == 1 + start = min([o.start for o in origins]) + end = max([o.end for o in origins]) + return cls(codes.pop(), start, end) + + def relevant_code(self): + """Extracts and returns the span of the original code represented by + this Origin. Example: ``x1``.""" + return self.code[self.start : self.end] + + def __eq__(self, other): + return ( + isinstance(other, Origin) + and self.code == other.code + and self.start == other.start + and self.end == other.end + ) + + def __ne__(self, other): + return not self == other + + def __hash__(self): + return hash((Origin, self.code, self.start, self.end)) + + def caretize(self, indent=0): + """Produces a user-readable two line string indicating the origin of + some code. Example:: + + y ~ x1:x2 + ^^ + + If optional argument 'indent' is given, then both lines will be + indented by this much. The returned string does not have a trailing + newline. + """ + return "%s%s\n%s%s%s" % ( + " " * indent, + self.code, + " " * indent, + " " * self.start, + "^" * (self.end - self.start), + ) + + def __repr__(self): + return "%s<-%s (%s-%s)>" % ( + self.code[: self.start], + self.code[self.start : self.end], + self.code[self.end :], + self.start, + self.end, + ) + + # We reimplement patsy.util.no_pickling, to avoid circular import issues + def __getstate__(self): + raise NotImplementedError + + +def test_Origin(): + o1 = Origin("012345", 2, 4) + o2 = Origin("012345", 4, 5) + assert o1.caretize() == "012345\n ^^" + assert o2.caretize() == "012345\n ^" + o3 = Origin.combine([o1, o2]) + assert o3.code == "012345" + assert o3.start == 2 + assert o3.end == 5 + assert o3.caretize(indent=2) == " 012345\n ^^^" + assert o3 == Origin("012345", 2, 5) + + class ObjWithOrigin(object): + def __init__(self, origin=None): + self.origin = origin + + o4 = Origin.combine([ObjWithOrigin(o1), ObjWithOrigin(), None]) + assert o4 == o1 + o5 = Origin.combine([ObjWithOrigin(o1), o2]) + assert o5 == o3 + + assert Origin.combine([ObjWithOrigin(), ObjWithOrigin()]) is None + + from patsy.util import assert_no_pickling + + assert_no_pickling(Origin("", 0, 0)) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/parse_formula.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/parse_formula.py new file mode 100644 index 0000000000000000000000000000000000000000..1a324f784df7da7c7cef7edd359f19189d915860 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/parse_formula.py @@ -0,0 +1,295 @@ +# This file is part of Patsy +# Copyright (C) 2011 Nathaniel Smith +# See file LICENSE.txt for license information. + +# This file defines a parser for a simple language based on S/R "formulas" +# (which are described in sections 2.3 and 2.4 in Chambers & Hastie, 1992). It +# uses the machinery in patsy.parse_core to do the heavy-lifting -- its +# biggest job is to handle tokenization. + + +__all__ = ["parse_formula"] + +# The Python tokenizer +import tokenize + +from io import StringIO + +from patsy import PatsyError +from patsy.origin import Origin +from patsy.infix_parser import Token, Operator, infix_parse, ParseNode +from patsy.tokens import python_tokenize, pretty_untokenize +from patsy.util import PushbackAdapter + +_atomic_token_types = ["PYTHON_EXPR", "ZERO", "ONE", "NUMBER"] + + +def _is_a(f, v): + try: + f(v) + except ValueError: + return False + else: + return True + + +# Helper function for _tokenize_formula: +def _read_python_expr(it, end_tokens): + # Read out a full python expression, stopping when we hit an + # unnested end token. + pytypes = [] + token_strings = [] + origins = [] + bracket_level = 0 + for pytype, token_string, origin in it: + assert bracket_level >= 0 + if bracket_level == 0 and token_string in end_tokens: + it.push_back((pytype, token_string, origin)) + break + if token_string in ("(", "[", "{"): + bracket_level += 1 + if token_string in (")", "]", "}"): + bracket_level -= 1 + if bracket_level < 0: + raise PatsyError("unmatched close bracket", origin) + pytypes.append(pytype) + token_strings.append(token_string) + origins.append(origin) + # Either we found an end_token, or we hit the end of the string + if bracket_level == 0: + expr_text = pretty_untokenize(zip(pytypes, token_strings)) + if expr_text == "0": + token_type = "ZERO" + elif expr_text == "1": + token_type = "ONE" + elif _is_a(int, expr_text) or _is_a(float, expr_text): + token_type = "NUMBER" + else: + token_type = "PYTHON_EXPR" + return Token(token_type, Origin.combine(origins), extra=expr_text) + else: + raise PatsyError( + "unclosed bracket in embedded Python expression", Origin.combine(origins) + ) + + +def _tokenize_formula(code, operator_strings): + assert "(" not in operator_strings + assert ")" not in operator_strings + magic_token_types = { + "(": Token.LPAREN, + ")": Token.RPAREN, + } + for operator_string in operator_strings: + magic_token_types[operator_string] = operator_string + # Once we enter a Python expression, a ( does not end it, but any other + # "magic" token does: + end_tokens = set(magic_token_types) + end_tokens.remove("(") + + it = PushbackAdapter(python_tokenize(code)) + for pytype, token_string, origin in it: + if token_string in magic_token_types: + yield Token(magic_token_types[token_string], origin) + else: + it.push_back((pytype, token_string, origin)) + yield _read_python_expr(it, end_tokens) + + +def test__tokenize_formula(): + code = "y ~ a + (foo(b,c + 2)) + -1 + 0 + 10" + tokens = list(_tokenize_formula(code, ["+", "-", "~"])) + expecteds = [ + ("PYTHON_EXPR", Origin(code, 0, 1), "y"), + ("~", Origin(code, 2, 3), None), + ("PYTHON_EXPR", Origin(code, 4, 5), "a"), + ("+", Origin(code, 6, 7), None), + (Token.LPAREN, Origin(code, 8, 9), None), + ("PYTHON_EXPR", Origin(code, 9, 23), "foo(b, c + 2)"), + (Token.RPAREN, Origin(code, 23, 24), None), + ("+", Origin(code, 25, 26), None), + ("-", Origin(code, 27, 28), None), + ("ONE", Origin(code, 28, 29), "1"), + ("+", Origin(code, 30, 31), None), + ("ZERO", Origin(code, 32, 33), "0"), + ("+", Origin(code, 34, 35), None), + ("NUMBER", Origin(code, 36, 38), "10"), + ] + for got, expected in zip(tokens, expecteds): + assert isinstance(got, Token) + assert got.type == expected[0] + assert got.origin == expected[1] + assert got.extra == expected[2] + + +_unary_tilde = Operator("~", 1, -100) +_default_ops = [ + _unary_tilde, + Operator("~", 2, -100), + Operator("+", 2, 100), + Operator("-", 2, 100), + Operator("*", 2, 200), + Operator("/", 2, 200), + Operator(":", 2, 300), + Operator("**", 2, 500), + Operator("+", 1, 100), + Operator("-", 1, 100), +] + + +def parse_formula(code, extra_operators=[]): + if not code.strip(): + code = "~ 1" + + for op in extra_operators: + if op.precedence < 0: + raise ValueError("all operators must have precedence >= 0") + + operators = _default_ops + extra_operators + operator_strings = [op.token_type for op in operators] + tree = infix_parse( + _tokenize_formula(code, operator_strings), operators, _atomic_token_types + ) + if not isinstance(tree, ParseNode) or tree.type != "~": + tree = ParseNode("~", None, [tree], tree.origin) + return tree + + +############# + +_parser_tests = { + "": ["~", "1"], + " ": ["~", "1"], + " \n ": ["~", "1"], + "1": ["~", "1"], + "a": ["~", "a"], + "a ~ b": ["~", "a", "b"], + "(a ~ b)": ["~", "a", "b"], + "a ~ ((((b))))": ["~", "a", "b"], + "a ~ ((((+b))))": ["~", "a", ["+", "b"]], + "a + b + c": ["~", ["+", ["+", "a", "b"], "c"]], + "a + (b ~ c) + d": ["~", ["+", ["+", "a", ["~", "b", "c"]], "d"]], + "a + np.log(a, base=10)": ["~", ["+", "a", "np.log(a, base=10)"]], + # Note different spacing: + "a + np . log(a , base = 10)": ["~", ["+", "a", "np.log(a, base=10)"]], + # Check precedence + "a + b ~ c * d": ["~", ["+", "a", "b"], ["*", "c", "d"]], + "a + b * c": ["~", ["+", "a", ["*", "b", "c"]]], + "-a**2": ["~", ["-", ["**", "a", "2"]]], + "-a:b": ["~", ["-", [":", "a", "b"]]], + "a + b:c": ["~", ["+", "a", [":", "b", "c"]]], + "(a + b):c": ["~", [":", ["+", "a", "b"], "c"]], + "a*b:c": ["~", ["*", "a", [":", "b", "c"]]], + "a+b / c": ["~", ["+", "a", ["/", "b", "c"]]], + "~ a": ["~", "a"], + "-1": ["~", ["-", "1"]], +} + + +def _compare_trees(got, expected): + assert isinstance(got, ParseNode) + if got.args: + assert got.type == expected[0] + for arg, expected_arg in zip(got.args, expected[1:]): + _compare_trees(arg, expected_arg) + else: + assert got.type in _atomic_token_types + assert got.token.extra == expected + + +def _do_parse_test(test_cases, extra_operators): + for code, expected in test_cases.items(): + actual = parse_formula(code, extra_operators=extra_operators) + print(repr(code), repr(expected)) + print(actual) + _compare_trees(actual, expected) + + +def test_parse_formula(): + _do_parse_test(_parser_tests, []) + + +def test_parse_origin(): + tree = parse_formula("a ~ b + c") + assert tree.origin == Origin("a ~ b + c", 0, 9) + assert tree.token.origin == Origin("a ~ b + c", 2, 3) + assert tree.args[0].origin == Origin("a ~ b + c", 0, 1) + assert tree.args[1].origin == Origin("a ~ b + c", 4, 9) + assert tree.args[1].token.origin == Origin("a ~ b + c", 6, 7) + assert tree.args[1].args[0].origin == Origin("a ~ b + c", 4, 5) + assert tree.args[1].args[1].origin == Origin("a ~ b + c", 8, 9) + + +# <> mark off where the error should be reported: +_parser_error_tests = [ + "a <+>", + "a + <(>", + "a + b <# asdf>", + "<)>", + "a + <)>", + "<*> a", + "a + <*>", + "a + ", + "a + ", + "a + ", + "a + <[bar>", + "a + <{bar>", + "a + <{bar[]>", + "a + foo<]>bar", + "a + foo[]<]>bar", + "a + foo{}<}>bar", + "a + foo<)>bar", + "a + b<)>", + "(a) <.>", + "<(>a + b", + "a +< >'foo", # Not the best placement for the error +] + + +# Split out so it can also be used by tests of the evaluator (which also +# raises PatsyError's) +def _parsing_error_test(parse_fn, error_descs): # pragma: no cover + for error_desc in error_descs: + letters = [] + start = None + end = None + for letter in error_desc: + if letter == "<": + start = len(letters) + elif letter == ">": + end = len(letters) + else: + letters.append(letter) + bad_code = "".join(letters) + assert start is not None and end is not None + print(error_desc) + print(repr(bad_code), start, end) + try: + parse_fn(bad_code) + except PatsyError as e: + print(e) + assert e.origin.code == bad_code + assert e.origin.start in (0, start) + assert e.origin.end in (end, len(bad_code)) + else: + assert False, "parser failed to report an error!" + + +def test_parse_errors(extra_operators=[]): + def parse_fn(code): + return parse_formula(code, extra_operators=extra_operators) + + _parsing_error_test(parse_fn, _parser_error_tests) + + +_extra_op_parser_tests = { + "a | b": ["~", ["|", "a", "b"]], + "a * b|c": ["~", ["*", "a", ["|", "b", "c"]]], +} + + +def test_parse_extra_op(): + extra_operators = [Operator("|", 2, 250)] + _do_parse_test(_parser_tests, extra_operators=extra_operators) + _do_parse_test(_extra_op_parser_tests, extra_operators=extra_operators) + test_parse_errors(extra_operators=extra_operators) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/redundancy.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/redundancy.py new file mode 100644 index 0000000000000000000000000000000000000000..c81d439f91044280c686b9b2fad7b68bf5d3e78c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/redundancy.py @@ -0,0 +1,278 @@ +# This file is part of Patsy +# Copyright (C) 2011 Nathaniel Smith +# See file LICENSE.txt for license information. + +# This file has the code that figures out how each factor in some given Term +# should be coded. This is complicated by dealing with models with categorical +# factors like: +# 1 + a + a:b +# then technically 'a' (which represents the space of vectors that can be +# produced as linear combinations of the dummy coding of the levels of the +# factor a) is collinear with the intercept, and 'a:b' (which represents the +# space of vectors that can be produced as linear combinations of the dummy +# coding *of a new factor whose levels are the cartesian product of a and b) +# is collinear with both 'a' and the intercept. +# +# In such a case, the rule is that we find some way to code each term so that +# the full space of vectors that it represents *is present in the model* BUT +# there is no collinearity between the different terms. In effect, we have to +# choose a set of vectors that spans everything that that term wants to span, +# *except* that part of the vector space which was already spanned by earlier +# terms. + +# How? We replace each term with the set of "subterms" that it covers, like +# so: +# 1 -> () +# a -> (), a- +# a:b -> (), a-, b-, a-:b- +# where "-" means "coded so as not to span the intercept". So that example +# above expands to +# [()] + [() + a-] + [() + a- + b- + a-:b-] +# so we go through from left to right, and for each term we: +# 1) toss out all the subterms that have already been used (this is a simple +# equality test, no magic) +# 2) simplify the terms that are left, according to rules like +# () + a- = a+ +# (here + means, "coded to span the intercept") +# 3) use the resulting subterm list as our coding for this term! +# So in the above, we go: +# (): stays the same, coded as intercept +# () + a-: reduced to just a-, which is what we code +# () + a- + b- + a-:b-: reduced to b- + a-:b-, which is simplified to a+:b-. + +from patsy.util import no_pickling + + +# This should really be a named tuple, but those don't exist until Python +# 2.6... +class _ExpandedFactor(object): + """A factor, with an additional annotation for whether it is coded + full-rank (includes_intercept=True) or not. + + These objects are treated as immutable.""" + + def __init__(self, includes_intercept, factor): + self.includes_intercept = includes_intercept + self.factor = factor + + def __hash__(self): + return hash((_ExpandedFactor, self.includes_intercept, self.factor)) + + def __eq__(self, other): + return ( + isinstance(other, _ExpandedFactor) + and other.includes_intercept == self.includes_intercept + and other.factor == self.factor + ) + + def __ne__(self, other): + return not self == other + + def __repr__(self): + if self.includes_intercept: + suffix = "+" + else: + suffix = "-" + return "%r%s" % (self.factor, suffix) + + __getstate__ = no_pickling + + +class _Subterm(object): + "Also immutable." + + def __init__(self, efactors): + self.efactors = frozenset(efactors) + + def can_absorb(self, other): + # returns True if 'self' is like a-:b-, and 'other' is like a- + return len(self.efactors) - len( + other.efactors + ) == 1 and self.efactors.issuperset(other.efactors) + + def absorb(self, other): + diff = self.efactors.difference(other.efactors) + assert len(diff) == 1 + efactor = list(diff)[0] + assert not efactor.includes_intercept + new_factors = set(other.efactors) + new_factors.add(_ExpandedFactor(True, efactor.factor)) + return _Subterm(new_factors) + + def __hash__(self): + return hash((_Subterm, self.efactors)) + + def __eq__(self, other): + return isinstance(other, _Subterm) and self.efactors == self.efactors + + def __ne__(self, other): + return not self == other + + def __repr__(self): + return "%s(%r)" % (self.__class__.__name__, list(self.efactors)) + + __getstate__ = no_pickling + + +# For testing: takes a shorthand description of a list of subterms like +# [(), ("a-",), ("a-", "b+")] +# and expands it into a list of _Subterm and _ExpandedFactor objects. +def _expand_test_abbrevs(short_subterms): + subterms = [] + for subterm in short_subterms: + factors = [] + for factor_name in subterm: + assert factor_name[-1] in ("+", "-") + factors.append(_ExpandedFactor(factor_name[-1] == "+", factor_name[:-1])) + subterms.append(_Subterm(factors)) + return subterms + + +def test__Subterm(): + s_ab = _expand_test_abbrevs([["a-", "b-"]])[0] + s_abc = _expand_test_abbrevs([["a-", "b-", "c-"]])[0] + s_null = _expand_test_abbrevs([[]])[0] + s_cd = _expand_test_abbrevs([["c-", "d-"]])[0] + s_a = _expand_test_abbrevs([["a-"]])[0] + s_ap = _expand_test_abbrevs([["a+"]])[0] + s_abp = _expand_test_abbrevs([["a-", "b+"]])[0] + for bad in s_abc, s_null, s_cd, s_ap, s_abp: + assert not s_ab.can_absorb(bad) + assert s_ab.can_absorb(s_a) + assert s_ab.absorb(s_a) == s_abp + + +# Importantly, this preserves the order of the input. Both the items inside +# each subset are in the order they were in the original tuple, and the tuples +# are emitted so that they're sorted with respect to their elements position +# in the original tuple. +def _subsets_sorted(tupl): + def helper(seq): + if not seq: + yield () + else: + obj = seq[0] + for subset in _subsets_sorted(seq[1:]): + yield subset + yield (obj,) + subset + + # Transform each obj -> (idx, obj) tuple, so that we can later sort them + # by their position in the original list. + expanded = list(enumerate(tupl)) + expanded_subsets = list(helper(expanded)) + # This exploits Python's stable sort: we want short before long, and ties + # broken by natural ordering on the (idx, obj) entries in each subset. So + # we sort by the latter first, then by the former. + expanded_subsets.sort() + expanded_subsets.sort(key=len) + # And finally, we strip off the idx's: + for subset in expanded_subsets: + yield tuple([obj for (idx, obj) in subset]) + + +def test__subsets_sorted(): + assert list(_subsets_sorted((1, 2))) == [(), (1,), (2,), (1, 2)] + assert list(_subsets_sorted((1, 2, 3))) == [ + (), + (1,), + (2,), + (3,), + (1, 2), + (1, 3), + (2, 3), + (1, 2, 3), + ] + assert len(list(_subsets_sorted(range(5)))) == 2**5 + + +def _simplify_one_subterm(subterms): + # We simplify greedily from left to right. + # Returns True if succeeded, False otherwise + for short_i, short_subterm in enumerate(subterms): + for long_i, long_subterm in enumerate(subterms[short_i + 1 :]): + if long_subterm.can_absorb(short_subterm): + new_subterm = long_subterm.absorb(short_subterm) + subterms[short_i + 1 + long_i] = new_subterm + subterms.pop(short_i) + return True + return False + + +def _simplify_subterms(subterms): + while _simplify_one_subterm(subterms): + pass + + +def test__simplify_subterms(): + def t(given, expected): + given = _expand_test_abbrevs(given) + expected = _expand_test_abbrevs(expected) + print("testing if:", given, "->", expected) + _simplify_subterms(given) + assert given == expected + + t([("a-",)], [("a-",)]) + t([(), ("a-",)], [("a+",)]) + t([(), ("a-",), ("b-",), ("a-", "b-")], [("a+", "b+")]) + t([(), ("a-",), ("a-", "b-")], [("a+",), ("a-", "b-")]) + t([("a-",), ("b-",), ("a-", "b-")], [("b-",), ("a-", "b+")]) + + +# 'term' is a Term +# 'numeric_factors' is any set-like object which lists the +# numeric/non-categorical factors in this term. Such factors are just +# ignored by this routine. +# 'used_subterms' is a set which records which subterms have previously been +# used. E.g., a:b has subterms (), a, b, a:b, and if we're processing +# y ~ a + a:b +# then by the time we reach a:b, the () and a subterms will have already +# been used. This is an in/out argument, and should be treated as opaque by +# callers -- really it is a way for multiple invocations of this routine to +# talk to each other. Each time it is called, this routine adds the subterms +# of each factor to this set in place. So the first time this routine is +# called, pass in an empty set, and then just keep passing the same set to +# any future calls. +# Returns: a list of dicts. Each dict maps from factors to booleans. The +# coding for the given term should use a full-rank contrast for those factors +# which map to True, a (n-1)-rank contrast for those factors which map to +# False, and any factors which are not mentioned are numeric and should be +# added back in. These dicts should add columns to the design matrix from left +# to right. +def pick_contrasts_for_term(term, numeric_factors, used_subterms): + categorical_factors = [f for f in term.factors if f not in numeric_factors] + # Converts a term into an expanded list of subterms like: + # a:b -> 1 + a- + b- + a-:b- + # and discards the ones that have already been used. + subterms = [] + for subset in _subsets_sorted(categorical_factors): + subterm = _Subterm([_ExpandedFactor(False, f) for f in subset]) + if subterm not in used_subterms: + subterms.append(subterm) + used_subterms.update(subterms) + _simplify_subterms(subterms) + factor_codings = [] + for subterm in subterms: + factor_coding = {} + for expanded in subterm.efactors: + factor_coding[expanded.factor] = expanded.includes_intercept + factor_codings.append(factor_coding) + return factor_codings + + +def test_pick_contrasts_for_term(): + from patsy.desc import Term + + used = set() + codings = pick_contrasts_for_term(Term([]), set(), used) + assert codings == [{}] + codings = pick_contrasts_for_term(Term(["a", "x"]), set(["x"]), used) + assert codings == [{"a": False}] + codings = pick_contrasts_for_term(Term(["a", "b"]), set(), used) + assert codings == [{"a": True, "b": False}] + used_snapshot = set(used) + codings = pick_contrasts_for_term(Term(["c", "d"]), set(), used) + assert codings == [{"d": False}, {"c": False, "d": True}] + # Do it again backwards, to make sure we're deterministic with respect to + # order: + codings = pick_contrasts_for_term(Term(["d", "c"]), set(), used_snapshot) + assert codings == [{"c": False}, {"c": True, "d": False}] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/splines.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/splines.py new file mode 100644 index 0000000000000000000000000000000000000000..a6735e5ce721322f1b0528ddffacd4c0333ec05a --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/splines.py @@ -0,0 +1,429 @@ +# This file is part of Patsy +# Copyright (C) 2012-2013 Nathaniel Smith +# See file LICENSE.txt for license information. + +# R-compatible spline basis functions + +# These are made available in the patsy.* namespace +__all__ = ["bs"] + +import numpy as np + +from patsy.util import have_pandas, no_pickling, assert_no_pickling +from patsy.state import stateful_transform + +if have_pandas: + import pandas + + +def _eval_bspline_basis(x, knots, degree): + try: + from scipy.interpolate import splev + except ImportError: # pragma: no cover + raise ImportError("spline functionality requires scipy") + # 'knots' are assumed to be already pre-processed. E.g. usually you + # want to include duplicate copies of boundary knots; you should do + # that *before* calling this constructor. + knots = np.atleast_1d(np.asarray(knots, dtype=float)) + assert knots.ndim == 1 + knots.sort() + degree = int(degree) + x = np.atleast_1d(x) + if x.ndim == 2 and x.shape[1] == 1: + x = x[:, 0] + assert x.ndim == 1 + # XX FIXME: when points fall outside of the boundaries, splev and R seem + # to handle them differently. I don't know why yet. So until we understand + # this and decide what to do with it, I'm going to play it safe and + # disallow such points. + if np.min(x) < np.min(knots) or np.max(x) > np.max(knots): + raise NotImplementedError( + "some data points fall outside the " + "outermost knots, and I'm not sure how " + "to handle them. (Patches accepted!)" + ) + # Thanks to Charles Harris for explaining splev. It's not well + # documented, but basically it computes an arbitrary b-spline basis + # given knots and degree on some specified points (or derivatives + # thereof, but we don't use that functionality), and then returns some + # linear combination of these basis functions. To get out the basis + # functions themselves, we use linear combinations like [1, 0, 0], [0, + # 1, 0], [0, 0, 1]. + # NB: This probably makes it rather inefficient (though I haven't checked + # to be sure -- maybe the fortran code actually skips computing the basis + # function for coefficients that are zero). + # Note: the order of a spline is the same as its degree + 1. + # Note: there are (len(knots) - order) basis functions. + n_bases = len(knots) - (degree + 1) + basis = np.empty((x.shape[0], n_bases), dtype=float) + for i in range(n_bases): + coefs = np.zeros((n_bases,)) + coefs[i] = 1 + basis[:, i] = splev(x, (knots, coefs, degree)) + return basis + + +def _R_compat_quantile(x, probs): + # return np.percentile(x, 100 * np.asarray(probs)) + probs = np.asarray(probs) + quantiles = np.asarray( + [np.percentile(x, 100 * prob) for prob in probs.ravel(order="C")] + ) + return quantiles.reshape(probs.shape, order="C") + + +def test__R_compat_quantile(): + def t(x, prob, expected): + assert np.allclose(_R_compat_quantile(x, prob), expected) + + t([10, 20], 0.5, 15) + t([10, 20], 0.3, 13) + t([10, 20], [0.3, 0.7], [13, 17]) + t(list(range(10)), [0.3, 0.7], [2.7, 6.3]) + + +class BS(object): + """bs(x, df=None, knots=None, degree=3, include_intercept=False, lower_bound=None, upper_bound=None) + + Generates a B-spline basis for ``x``, allowing non-linear fits. The usual + usage is something like:: + + y ~ 1 + bs(x, 4) + + to fit ``y`` as a smooth function of ``x``, with 4 degrees of freedom + given to the smooth. + + :arg df: The number of degrees of freedom to use for this spline. The + return value will have this many columns. You must specify at least one + of ``df`` and ``knots``. + :arg knots: The interior knots to use for the spline. If unspecified, then + equally spaced quantiles of the input data are used. You must specify at + least one of ``df`` and ``knots``. + :arg degree: The degree of the spline to use. + :arg include_intercept: If ``True``, then the resulting + spline basis will span the intercept term (i.e., the constant + function). If ``False`` (the default) then this will not be the case, + which is useful for avoiding overspecification in models that include + multiple spline terms and/or an intercept term. + :arg lower_bound: The lower exterior knot location. + :arg upper_bound: The upper exterior knot location. + + A spline with ``degree=0`` is piecewise constant with breakpoints at each + knot, and the default knot positions are quantiles of the input. So if you + find yourself in the situation of wanting to quantize a continuous + variable into ``num_bins`` equal-sized bins with a constant effect across + each bin, you can use ``bs(x, num_bins - 1, degree=0)``. (The ``- 1`` is + because one degree of freedom will be taken by the intercept; + alternatively, you could leave the intercept term out of your model and + use ``bs(x, num_bins, degree=0, include_intercept=True)``. + + A spline with ``degree=1`` is piecewise linear with breakpoints at each + knot. + + The default is ``degree=3``, which gives a cubic b-spline. + + This is a stateful transform (for details see + :ref:`stateful-transforms`). If ``knots``, ``lower_bound``, or + ``upper_bound`` are not specified, they will be calculated from the data + and then the chosen values will be remembered and re-used for prediction + from the fitted model. + + Using this function requires scipy be installed. + + .. note:: This function is very similar to the R function of the same + name. In cases where both return output at all (e.g., R's ``bs`` will + raise an error if ``degree=0``, while patsy's will not), they should + produce identical output given identical input and parameter settings. + + .. warning:: I'm not sure on what the proper handling of points outside + the lower/upper bounds is, so for now attempting to evaluate a spline + basis at such points produces an error. Patches gratefully accepted. + + .. versionadded:: 0.2.0 + """ + + def __init__(self): + self._tmp = {} + self._degree = None + self._all_knots = None + + def memorize_chunk( + self, + x, + df=None, + knots=None, + degree=3, + include_intercept=False, + lower_bound=None, + upper_bound=None, + ): + args = { + "df": df, + "knots": knots, + "degree": degree, + "include_intercept": include_intercept, + "lower_bound": lower_bound, + "upper_bound": upper_bound, + } + self._tmp["args"] = args + # XX: check whether we need x values before saving them + x = np.atleast_1d(x) + if x.ndim == 2 and x.shape[1] == 1: + x = x[:, 0] + if x.ndim > 1: + raise ValueError("input to 'bs' must be 1-d, or a 2-d column vector") + # There's no better way to compute exact quantiles than memorizing + # all data. + self._tmp.setdefault("xs", []).append(x) + + def memorize_finish(self): + tmp = self._tmp + args = tmp["args"] + del self._tmp + + if args["degree"] < 0: + raise ValueError( + "degree must be greater than 0 (not %r)" % (args["degree"],) + ) + if int(args["degree"]) != args["degree"]: + raise ValueError("degree must be an integer (not %r)" % (self._degree,)) + + # These are guaranteed to all be 1d vectors by the code above + x = np.concatenate(tmp["xs"]) + if args["df"] is None and args["knots"] is None: + raise ValueError("must specify either df or knots") + order = args["degree"] + 1 + if args["df"] is not None: + n_inner_knots = args["df"] - order + if not args["include_intercept"]: + n_inner_knots += 1 + if n_inner_knots < 0: + raise ValueError( + "df=%r is too small for degree=%r and " + "include_intercept=%r; must be >= %s" + % ( + args["df"], + args["degree"], + args["include_intercept"], + # We know that n_inner_knots is negative; + # if df were that much larger, it would + # have been zero, and things would work. + args["df"] - n_inner_knots, + ) + ) + if args["knots"] is not None: + if len(args["knots"]) != n_inner_knots: + raise ValueError( + "df=%s with degree=%r implies %s knots, " + "but %s knots were provided" + % ( + args["df"], + args["degree"], + n_inner_knots, + len(args["knots"]), + ) + ) + else: + # Need to compute inner knots + knot_quantiles = np.linspace(0, 1, n_inner_knots + 2)[1:-1] + inner_knots = _R_compat_quantile(x, knot_quantiles) + if args["knots"] is not None: + inner_knots = args["knots"] + if args["lower_bound"] is not None: + lower_bound = args["lower_bound"] + else: + lower_bound = np.min(x) + if args["upper_bound"] is not None: + upper_bound = args["upper_bound"] + else: + upper_bound = np.max(x) + if lower_bound > upper_bound: + raise ValueError( + "lower_bound > upper_bound (%r > %r)" % (lower_bound, upper_bound) + ) + inner_knots = np.asarray(inner_knots) + if inner_knots.ndim > 1: + raise ValueError("knots must be 1 dimensional") + if np.any(inner_knots < lower_bound): + raise ValueError( + "some knot values (%s) fall below lower bound " + "(%r)" % (inner_knots[inner_knots < lower_bound], lower_bound) + ) + if np.any(inner_knots > upper_bound): + raise ValueError( + "some knot values (%s) fall above upper bound " + "(%r)" % (inner_knots[inner_knots > upper_bound], upper_bound) + ) + all_knots = np.concatenate(([lower_bound, upper_bound] * order, inner_knots)) + all_knots.sort() + + self._degree = args["degree"] + self._all_knots = all_knots + + def transform( + self, + x, + df=None, + knots=None, + degree=3, + include_intercept=False, + lower_bound=None, + upper_bound=None, + ): + basis = _eval_bspline_basis(x, self._all_knots, self._degree) + if not include_intercept: + basis = basis[:, 1:] + if have_pandas: + if isinstance(x, (pandas.Series, pandas.DataFrame)): + basis = pandas.DataFrame(basis) + basis.index = x.index + return basis + + __getstate__ = no_pickling + + +bs = stateful_transform(BS) + + +def test_bs_compat(): + from patsy.test_state import check_stateful + from patsy.test_splines_bs_data import R_bs_test_x, R_bs_test_data, R_bs_num_tests + + lines = R_bs_test_data.split("\n") + tests_ran = 0 + start_idx = lines.index("--BEGIN TEST CASE--") + while True: + if not lines[start_idx] == "--BEGIN TEST CASE--": + break + start_idx += 1 + stop_idx = lines.index("--END TEST CASE--", start_idx) + block = lines[start_idx:stop_idx] + test_data = {} + for line in block: + key, value = line.split("=", 1) + test_data[key] = value + # Translate the R output into Python calling conventions + kwargs = { + "degree": int(test_data["degree"]), + # integer, or None + "df": eval(test_data["df"]), + # np.array() call, or None + "knots": eval(test_data["knots"]), + } + if test_data["Boundary.knots"] != "None": + lower, upper = eval(test_data["Boundary.knots"]) + kwargs["lower_bound"] = lower + kwargs["upper_bound"] = upper + kwargs["include_intercept"] = test_data["intercept"] == "TRUE" + # Special case: in R, setting intercept=TRUE increases the effective + # dof by 1. Adjust our arguments to match. + # if kwargs["df"] is not None and kwargs["include_intercept"]: + # kwargs["df"] += 1 + output = np.asarray(eval(test_data["output"])) + if kwargs["df"] is not None: + assert output.shape[1] == kwargs["df"] + # Do the actual test + check_stateful(BS, False, R_bs_test_x, output, **kwargs) + tests_ran += 1 + # Set up for the next one + start_idx = stop_idx + 1 + assert tests_ran == R_bs_num_tests + + +test_bs_compat.slow = 1 + + +# This isn't checked by the above, because R doesn't have zero degree +# b-splines. +def test_bs_0degree(): + x = np.logspace(-1, 1, 10) + result = bs(x, knots=[1, 4], degree=0, include_intercept=True) + assert result.shape[1] == 3 + expected_0 = np.zeros(10) + expected_0[x < 1] = 1 + assert np.array_equal(result[:, 0], expected_0) + expected_1 = np.zeros(10) + expected_1[(x >= 1) & (x < 4)] = 1 + assert np.array_equal(result[:, 1], expected_1) + expected_2 = np.zeros(10) + expected_2[x >= 4] = 1 + assert np.array_equal(result[:, 2], expected_2) + # Check handling of points that exactly fall on knots. They arbitrarily + # get included into the larger region, not the smaller. This is consistent + # with Python's half-open interval convention -- each basis function is + # constant on [knot[i], knot[i + 1]). + assert np.array_equal( + bs([0, 1, 2], degree=0, knots=[1], include_intercept=True), + [[1, 0], [0, 1], [0, 1]], + ) + + result_int = bs(x, knots=[1, 4], degree=0, include_intercept=True) + result_no_int = bs(x, knots=[1, 4], degree=0, include_intercept=False) + assert np.array_equal(result_int[:, 1:], result_no_int) + + +def test_bs_errors(): + import pytest + + x = np.linspace(-10, 10, 20) + # error checks: + # out of bounds + pytest.raises(NotImplementedError, bs, x, 3, lower_bound=0) + pytest.raises(NotImplementedError, bs, x, 3, upper_bound=0) + # must specify df or knots + pytest.raises(ValueError, bs, x) + # df/knots match/mismatch (with and without intercept) + # match: + bs(x, df=10, include_intercept=False, knots=[0] * 7) + bs(x, df=10, include_intercept=True, knots=[0] * 6) + bs(x, df=10, include_intercept=False, knots=[0] * 9, degree=1) + bs(x, df=10, include_intercept=True, knots=[0] * 8, degree=1) + # too many knots: + pytest.raises(ValueError, bs, x, df=10, include_intercept=False, knots=[0] * 8) + pytest.raises(ValueError, bs, x, df=10, include_intercept=True, knots=[0] * 7) + pytest.raises( + ValueError, bs, x, df=10, include_intercept=False, knots=[0] * 10, degree=1 + ) + pytest.raises( + ValueError, bs, x, df=10, include_intercept=True, knots=[0] * 9, degree=1 + ) + # too few knots: + pytest.raises(ValueError, bs, x, df=10, include_intercept=False, knots=[0] * 6) + pytest.raises(ValueError, bs, x, df=10, include_intercept=True, knots=[0] * 5) + pytest.raises( + ValueError, bs, x, df=10, include_intercept=False, knots=[0] * 8, degree=1 + ) + pytest.raises( + ValueError, bs, x, df=10, include_intercept=True, knots=[0] * 7, degree=1 + ) + # df too small + pytest.raises(ValueError, bs, x, df=1, degree=3) + pytest.raises(ValueError, bs, x, df=3, degree=5) + # bad degree + pytest.raises(ValueError, bs, x, df=10, degree=-1) + pytest.raises(ValueError, bs, x, df=10, degree=1.5) + # upper_bound < lower_bound + pytest.raises(ValueError, bs, x, 3, lower_bound=1, upper_bound=-1) + # multidimensional input + pytest.raises(ValueError, bs, np.column_stack((x, x)), 3) + # unsorted knots are okay, and get sorted + assert np.array_equal(bs(x, knots=[1, 4]), bs(x, knots=[4, 1])) + # 2d knots + pytest.raises(ValueError, bs, x, knots=[[0], [20]]) + # knots > upper_bound + pytest.raises(ValueError, bs, x, knots=[0, 20]) + pytest.raises(ValueError, bs, x, knots=[0, 4], upper_bound=3) + # knots < lower_bound + pytest.raises(ValueError, bs, x, knots=[-20, 0]) + pytest.raises(ValueError, bs, x, knots=[-4, 0], lower_bound=-3) + + +# differences between bs and ns (since the R code is a pile of copy-paste): +# - degree is always 3 +# - different number of interior knots given df (b/c fewer dof used at edges I +# guess) +# - boundary knots always repeated exactly 4 times (same as bs with degree=3) +# - complications at the end to handle boundary conditions +# the 'rcs' function uses slightly different conventions -- in particular it +# picks boundary knots that are not quite at the edges of the data, which +# makes sense for a natural spline. diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/state.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/state.py new file mode 100644 index 0000000000000000000000000000000000000000..8d674ba240d9af5d4c63728367ba555816100c18 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/state.py @@ -0,0 +1,199 @@ +# This file is part of Patsy +# Copyright (C) 2011 Nathaniel Smith +# See file LICENSE.txt for license information. + +# Stateful transform protocol: +# def __init__(self): +# pass +# def memorize_chunk(self, input_data): +# return None +# def memorize_finish(self): +# return None +# def transform(self, input_data): +# return output_data + +# BETTER WAY: always run the first row of data through the builder alone, and +# check that it gives the same output row as when running the whole block of +# data through at once. This gives us the same information, but it's robust +# against people writing their own centering functions. + +# QUESTION: right now we refuse to even fit a model that contains a +# my_transform(x)-style function. Maybe we should allow it to be fit (with a +# warning), and only disallow making predictions with it? Need to revisit this +# question once it's clearer what exactly our public API will look like, +# because right now I'm not sure how to tell whether we are being called for +# fitting versus being called for prediction. + +from functools import wraps +import numpy as np +from patsy.util import ( + atleast_2d_column_default, + asarray_or_pandas, + pandas_friendly_reshape, + wide_dtype_for, + safe_issubdtype, + no_pickling, + assert_no_pickling, +) + +# These are made available in the patsy.* namespace +__all__ = [ + "stateful_transform", + "center", + "standardize", + "scale", +] + + +def stateful_transform(class_): + """Create a stateful transform callable object from a class that fulfills + the :ref:`stateful transform protocol `. + """ + + @wraps(class_) + def stateful_transform_wrapper(*args, **kwargs): + transform = class_() + transform.memorize_chunk(*args, **kwargs) + transform.memorize_finish() + return transform.transform(*args, **kwargs) + + stateful_transform_wrapper.__patsy_stateful_transform__ = class_ + return stateful_transform_wrapper + + +# class NonIncrementalStatefulTransform(object): +# def __init__(self): +# self._data = [] +# +# def memorize_chunk(self, input_data, *args, **kwargs): +# self._data.append(input_data) +# self._args = _args +# self._kwargs = kwargs +# +# def memorize_finish(self): +# all_data = np.vstack(self._data) +# args = self._args +# kwargs = self._kwargs +# del self._data +# del self._args +# del self._kwargs +# self.memorize_all(all_data, *args, **kwargs) +# +# def memorize_all(self, input_data, *args, **kwargs): +# raise NotImplementedError +# +# def transform(self, input_data, *args, **kwargs): +# raise NotImplementedError +# +# class QuantileEstimatingTransform(NonIncrementalStatefulTransform): +# def memorize_all(self, input_data, *args, **kwargs): + + +class Center(object): + """center(x) + + A stateful transform that centers input data, i.e., subtracts the mean. + + If input has multiple columns, centers each column separately. + + Equivalent to ``standardize(x, rescale=False)`` + """ + + def __init__(self): + self._sum = None + self._count = 0 + + def memorize_chunk(self, x): + x = atleast_2d_column_default(x) + self._count += x.shape[0] + this_total = np.sum(x, 0, dtype=wide_dtype_for(x)) + # This is to handle potentially multi-column x's: + if self._sum is None: + self._sum = this_total + else: + self._sum += this_total + + def memorize_finish(self): + pass + + def transform(self, x): + x = asarray_or_pandas(x) + # This doesn't copy data unless our input is a DataFrame that has + # heterogeneous types. And in that case we're going to be munging the + # types anyway, so copying isn't a big deal. + x_arr = np.asarray(x) + if safe_issubdtype(x_arr.dtype, np.integer): + dt = float + else: + dt = x_arr.dtype + mean_val = np.asarray(self._sum / self._count, dtype=dt) + centered = atleast_2d_column_default(x, preserve_pandas=True) - mean_val + return pandas_friendly_reshape(centered, x.shape) + + __getstate__ = no_pickling + + +center = stateful_transform(Center) + + +# See: +# http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#On-line_algorithm +# or page 232 of Knuth vol. 3 (3rd ed.). +class Standardize(object): + """standardize(x, center=True, rescale=True, ddof=0) + + A stateful transform that standardizes input data, i.e. it subtracts the + mean and divides by the sample standard deviation. + + Either centering or rescaling or both can be disabled by use of keyword + arguments. The `ddof` argument controls the delta degrees of freedom when + computing the standard deviation (cf. :func:`numpy.std`). The default of + ``ddof=0`` produces the maximum likelihood estimate; use ``ddof=1`` if you + prefer the square root of the unbiased estimate of the variance. + + If input has multiple columns, standardizes each column separately. + + .. note:: This function computes the mean and standard deviation using a + memory-efficient online algorithm, making it suitable for use with + large incrementally processed data-sets. + """ + + def __init__(self): + self.current_n = 0 + self.current_mean = None + self.current_M2 = None + + def memorize_chunk(self, x, center=True, rescale=True, ddof=0): + x = atleast_2d_column_default(x) + if self.current_mean is None: + self.current_mean = np.zeros(x.shape[1], dtype=wide_dtype_for(x)) + self.current_M2 = np.zeros(x.shape[1], dtype=wide_dtype_for(x)) + # XX this can surely be vectorized but I am feeling lazy: + for i in range(x.shape[0]): + self.current_n += 1 + delta = x[i, :] - self.current_mean + self.current_mean += delta / self.current_n + self.current_M2 += delta * (x[i, :] - self.current_mean) + + def memorize_finish(self): + pass + + def transform(self, x, center=True, rescale=True, ddof=0): + # XX: this forces all inputs to double-precision real, even if the + # input is single- or extended-precision or complex. But I got all + # tangled up in knots trying to do that without breaking something + # else (e.g. by requiring an extra copy). + x = asarray_or_pandas(x, copy=True, dtype=float) + x_2d = atleast_2d_column_default(x, preserve_pandas=True) + if center: + x_2d -= self.current_mean + if rescale: + x_2d /= np.sqrt(self.current_M2 / (self.current_n - ddof)) + return pandas_friendly_reshape(x_2d, x.shape) + + __getstate__ = no_pickling + + +standardize = stateful_transform(Standardize) +# R compatibility: +scale = standardize diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/test_build.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/test_build.py new file mode 100644 index 0000000000000000000000000000000000000000..bad3be6556fc5f12d847b934222d3a5530c3506c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/test_build.py @@ -0,0 +1,798 @@ +# This file is part of Patsy +# Copyright (C) 2012-2013 Nathaniel Smith +# See file LICENSE.txt for license information. + +# There are a number of unit tests in build.py, but this file contains more +# thorough tests of the overall design matrix building system. (These are +# still not exhaustive end-to-end tests, though -- for that see +# test_highlevel.py.) + +import numpy as np +import pytest +from patsy import PatsyError +from patsy.util import atleast_2d_column_default, have_pandas, have_pandas_categorical +from patsy.desc import Term, INTERCEPT +from patsy.build import build_design_matrices, design_matrix_builders +from patsy.categorical import C +from patsy.user_util import balanced, LookupFactor +from patsy.design_info import DesignMatrix, DesignInfo + +if have_pandas: + import pandas + + +def assert_full_rank(m): + m = atleast_2d_column_default(m) + if m.shape[1] == 0: + return True + u, s, v = np.linalg.svd(m) + rank = np.sum(s > 1e-10) + assert rank == m.shape[1] + + +def test_assert_full_rank(): + assert_full_rank(np.eye(10)) + assert_full_rank([[1, 0], [1, 0], [1, 0], [1, 1]]) + pytest.raises(AssertionError, assert_full_rank, [[1, 0], [2, 0]]) + pytest.raises(AssertionError, assert_full_rank, [[1, 2], [2, 4]]) + pytest.raises(AssertionError, assert_full_rank, [[1, 2, 3], [1, 10, 100]]) + # col1 + col2 = col3 + pytest.raises(AssertionError, assert_full_rank, [[1, 2, 3], [1, 5, 6], [1, 6, 7]]) + + +def make_termlist(*entries): + terms = [] + for entry in entries: + terms.append(Term([LookupFactor(name) for name in entry])) + return terms + + +def check_design_matrix(mm, expected_rank, termlist, column_names=None): + assert_full_rank(mm) + assert set(mm.design_info.terms) == set(termlist) + if column_names is not None: + assert mm.design_info.column_names == column_names + assert mm.ndim == 2 + assert mm.shape[1] == expected_rank + + +def make_matrix(data, expected_rank, entries, column_names=None): + termlist = make_termlist(*entries) + + def iter_maker(): + yield data + + design_infos = design_matrix_builders([termlist], iter_maker, eval_env=0) + matrices = build_design_matrices(design_infos, data) + matrix = matrices[0] + assert design_infos[0].term_slices == matrix.design_info.term_slices + assert design_infos[0].column_names == matrix.design_info.column_names + assert matrix.design_info is design_infos[0] + check_design_matrix(matrix, expected_rank, termlist, column_names=column_names) + return matrix + + +def test_simple(): + data = balanced(a=2, b=2) + x1 = data["x1"] = np.linspace(0, 1, len(data["a"])) + x2 = data["x2"] = data["x1"] ** 2 + + m = make_matrix(data, 2, [["a"]], column_names=["a[a1]", "a[a2]"]) + assert np.allclose(m, [[1, 0], [1, 0], [0, 1], [0, 1]]) + + m = make_matrix(data, 2, [[], ["a"]], column_names=["Intercept", "a[T.a2]"]) + assert np.allclose(m, [[1, 0], [1, 0], [1, 1], [1, 1]]) + + m = make_matrix( + data, + 4, + [["a", "b"]], + column_names=["a[a1]:b[b1]", "a[a2]:b[b1]", "a[a1]:b[b2]", "a[a2]:b[b2]"], + ) + assert np.allclose(m, [[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]]) + + m = make_matrix( + data, + 4, + [[], ["a"], ["b"], ["a", "b"]], + column_names=["Intercept", "a[T.a2]", "b[T.b2]", "a[T.a2]:b[T.b2]"], + ) + assert np.allclose(m, [[1, 0, 0, 0], [1, 0, 1, 0], [1, 1, 0, 0], [1, 1, 1, 1]]) + + m = make_matrix( + data, + 4, + [[], ["b"], ["a"], ["b", "a"]], + column_names=["Intercept", "b[T.b2]", "a[T.a2]", "b[T.b2]:a[T.a2]"], + ) + assert np.allclose(m, [[1, 0, 0, 0], [1, 1, 0, 0], [1, 0, 1, 0], [1, 1, 1, 1]]) + + m = make_matrix( + data, + 4, + [["a"], ["x1"], ["a", "x1"]], + column_names=["a[a1]", "a[a2]", "x1", "a[T.a2]:x1"], + ) + assert np.allclose( + m, + [ + [1, 0, x1[0], 0], + [1, 0, x1[1], 0], + [0, 1, x1[2], x1[2]], + [0, 1, x1[3], x1[3]], + ], + ) + + m = make_matrix( + data, 3, [["x1"], ["x2"], ["x2", "x1"]], column_names=["x1", "x2", "x2:x1"] + ) + assert np.allclose(m, np.column_stack((x1, x2, x1 * x2))) + + +def test_R_bugs(): + data = balanced(a=2, b=2, c=2) + data["x"] = np.linspace(0, 1, len(data["a"])) + # For "1 + a:b", R produces a design matrix with too many columns (5 + # instead of 4), because it can't tell that there is a redundancy between + # the two terms. + make_matrix(data, 4, [[], ["a", "b"]]) + # For "0 + a:x + a:b", R produces a design matrix with too few columns (4 + # instead of 6), because it thinks that there is a redundancy which + # doesn't exist. + make_matrix(data, 6, [["a", "x"], ["a", "b"]]) + # This can be compared with "0 + a:c + a:b", where the redundancy does + # exist. Confusingly, adding another categorical factor increases the + # baseline dimensionality to 8, and then the redundancy reduces it to 6 + # again, so the result is the same as before but for different reasons. (R + # does get this one right, but we might as well test it.) + make_matrix(data, 6, [["a", "c"], ["a", "b"]]) + + +def test_redundancy_thoroughly(): + # To make sure there aren't any lurking bugs analogous to the ones that R + # has (see above), we check that we get the correct matrix rank for every + # possible combination of 2 categorical and 2 numerical factors. + data = balanced(a=2, b=2, repeat=5) + data["x1"] = np.linspace(0, 1, len(data["a"])) + data["x2"] = data["x1"] ** 2 + + def all_subsets(l): + if not l: + yield tuple() + else: + obj = l[0] + for subset in all_subsets(l[1:]): + yield tuple(sorted(subset)) + yield tuple(sorted((obj,) + subset)) + + all_terms = list(all_subsets(("a", "b", "x1", "x2"))) + all_termlist_templates = list(all_subsets(all_terms)) + print(len(all_termlist_templates)) + # eliminate some of the symmetric versions to speed things up + redundant = [ + [("b",), ("a",)], + [("x2",), ("x1",)], + [("b", "x2"), ("a", "x1")], + [("a", "b", "x2"), ("a", "b", "x1")], + [("b", "x1", "x2"), ("a", "x1", "x2")], + ] + count = 0 + import time + + start = time.time() + for termlist_template in all_termlist_templates: + termlist_set = set(termlist_template) + for dispreferred, preferred in redundant: + if dispreferred in termlist_set and preferred not in termlist_set: + break + else: + expanded_terms = set() + for term_template in termlist_template: + numeric = tuple([t for t in term_template if t.startswith("x")]) + rest = [t for t in term_template if not t.startswith("x")] + for subset_rest in all_subsets(rest): + expanded_terms.add(frozenset(subset_rest + numeric)) + # Because our categorical variables have 2 levels, each expanded + # term corresponds to 1 unique dimension of variation + expected_rank = len(expanded_terms) + if termlist_template in [(), ((),)]: + # No data dependence, should fail + pytest.raises( + PatsyError, make_matrix, data, expected_rank, termlist_template + ) + else: + make_matrix(data, expected_rank, termlist_template) + count += 1 + if count % 100 == 0: + print("Completed:", count) + print("Took %0.2f seconds" % (time.time() - start,)) + + +test_redundancy_thoroughly.slow = 1 + + +def test_data_types(): + basic_dict = {"a": ["a1", "a2", "a1", "a2"], "x": [1, 2, 3, 4]} + # On Python 2, this is identical to basic_dict: + basic_dict_bytes = dict(basic_dict) + basic_dict_bytes["a"] = [s.encode("ascii") for s in basic_dict_bytes["a"]] + # On Python 3, this is identical to basic_dict: + basic_dict_unicode = {"a": ["a1", "a2", "a1", "a2"], "x": [1, 2, 3, 4]} + basic_dict_unicode = dict(basic_dict) + basic_dict_unicode["a"] = [str(s) for s in basic_dict_unicode["a"]] + + structured_array_bytes = np.array( + list(zip(basic_dict["a"], basic_dict["x"])), dtype=[("a", "S2"), ("x", int)] + ) + structured_array_unicode = np.array( + list(zip(basic_dict["a"], basic_dict["x"])), dtype=[("a", "U2"), ("x", int)] + ) + recarray_bytes = structured_array_bytes.view(np.recarray) + recarray_unicode = structured_array_unicode.view(np.recarray) + datas = [ + basic_dict, + structured_array_bytes, + structured_array_unicode, + recarray_bytes, + recarray_unicode, + ] + if have_pandas: + df_bytes = pandas.DataFrame(basic_dict_bytes) + datas.append(df_bytes) + df_unicode = pandas.DataFrame(basic_dict_unicode) + datas.append(df_unicode) + for data in datas: + m = make_matrix( + data, + 4, + [["a"], ["a", "x"]], + column_names=["a[a1]", "a[a2]", "a[a1]:x", "a[a2]:x"], + ) + assert np.allclose(m, [[1, 0, 1, 0], [0, 1, 0, 2], [1, 0, 3, 0], [0, 1, 0, 4]]) + + +def test_build_design_matrices_dtype(): + data = {"x": [1, 2, 3]} + + def iter_maker(): + yield data + + builder = design_matrix_builders([make_termlist("x")], iter_maker, 0)[0] + + mat = build_design_matrices([builder], data)[0] + assert mat.dtype == np.dtype(np.float64) + + mat = build_design_matrices([builder], data, dtype=np.float32)[0] + assert mat.dtype == np.dtype(np.float32) + + if hasattr(np, "float128"): + mat = build_design_matrices([builder], data, dtype=np.float128)[0] + assert mat.dtype == np.dtype(np.float128) + + +def test_return_type(): + data = {"x": [1, 2, 3]} + + def iter_maker(): + yield data + + builder = design_matrix_builders([make_termlist("x")], iter_maker, 0)[0] + + # Check explicitly passing return_type="matrix" works + mat = build_design_matrices([builder], data, return_type="matrix")[0] + assert isinstance(mat, DesignMatrix) + + # Check that nonsense is detected + pytest.raises( + PatsyError, build_design_matrices, [builder], data, return_type="asdfsadf" + ) + + +def test_NA_action(): + initial_data = {"x": [1, 2, 3], "c": ["c1", "c2", "c1"]} + + def iter_maker(): + yield initial_data + + builder = design_matrix_builders([make_termlist("x", "c")], iter_maker, 0)[0] + + # By default drops rows containing either NaN or None + mat = build_design_matrices( + [builder], + {"x": [10.0, np.nan, 20.0], "c": np.asarray(["c1", "c2", None], dtype=object)}, + )[0] + assert mat.shape == (1, 3) + assert np.array_equal(mat, [[1.0, 0.0, 10.0]]) + + # NA_action="a string" also accepted: + mat = build_design_matrices( + [builder], + {"x": [10.0, np.nan, 20.0], "c": np.asarray(["c1", "c2", None], dtype=object)}, + NA_action="drop", + )[0] + assert mat.shape == (1, 3) + assert np.array_equal(mat, [[1.0, 0.0, 10.0]]) + + # And objects + from patsy.missing import NAAction + + # allows NaN's to pass through + NA_action = NAAction(NA_types=[]) + mat = build_design_matrices( + [builder], + {"x": [10.0, np.nan], "c": np.asarray(["c1", "c2"], dtype=object)}, + NA_action=NA_action, + )[0] + assert mat.shape == (2, 3) + # According to this (and only this) function, NaN == NaN. + np.testing.assert_array_equal(mat, [[1.0, 0.0, 10.0], [0.0, 1.0, np.nan]]) + + # NA_action="raise" + pytest.raises( + PatsyError, + build_design_matrices, + [builder], + {"x": [10.0, np.nan, 20.0], "c": np.asarray(["c1", "c2", None], dtype=object)}, + NA_action="raise", + ) + + +def test_NA_drop_preserves_levels(): + # Even if all instances of some level are dropped, we still include it in + # the output matrix (as an all-zeros column) + data = {"x": [1.0, np.nan, 3.0], "c": ["c1", "c2", "c3"]} + + def iter_maker(): + yield data + + design_info = design_matrix_builders([make_termlist("x", "c")], iter_maker, 0)[0] + + assert design_info.column_names == ["c[c1]", "c[c2]", "c[c3]", "x"] + + (mat,) = build_design_matrices([design_info], data) + + assert mat.shape == (2, 4) + assert np.array_equal(mat, [[1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 3.0]]) + + +def test_return_type_pandas(): + if not have_pandas: + return + + data = pandas.DataFrame( + {"x": [1, 2, 3], "y": [4, 5, 6], "a": ["a1", "a2", "a1"]}, index=[10, 20, 30] + ) + + def iter_maker(): + yield data + + (int_builder,) = design_matrix_builders([make_termlist([])], iter_maker, 0) + (y_builder, x_builder) = design_matrix_builders( + [make_termlist("y"), make_termlist("x")], iter_maker, eval_env=0 + ) + (x_a_builder,) = design_matrix_builders( + [make_termlist("x", "a")], iter_maker, eval_env=0 + ) + (x_y_builder,) = design_matrix_builders( + [make_termlist("x", "y")], iter_maker, eval_env=0 + ) + # Index compatibility is always checked for pandas input, regardless of + # whether we're producing pandas output + pytest.raises( + PatsyError, + build_design_matrices, + [x_a_builder], + {"x": data["x"], "a": data["a"][::-1]}, + ) + pytest.raises( + PatsyError, + build_design_matrices, + [y_builder, x_builder], + {"x": data["x"], "y": data["y"][::-1]}, + ) + + # And we also check consistency between data.index and value indexes + # Creating a mismatch between these is a bit tricky. We want a data object + # such that isinstance(data, DataFrame), but data["x"].index != + # data.index. + class CheatingDataFrame(pandas.DataFrame): + def __getitem__(self, key): + if key == "x": + return pandas.DataFrame.__getitem__(self, key)[::-1] + else: + return pandas.DataFrame.__getitem__(self, key) + + pytest.raises( + PatsyError, build_design_matrices, [x_builder], CheatingDataFrame(data) + ) + + # A mix of pandas input and unindexed input is fine + (mat,) = build_design_matrices([x_y_builder], {"x": data["x"], "y": [40, 50, 60]}) + assert np.allclose(mat, [[1, 40], [2, 50], [3, 60]]) + + # with return_type="dataframe", we get out DataFrames with nice indices + # and nice column names and design_info + y_df, x_df = build_design_matrices( + [y_builder, x_builder], data, return_type="dataframe" + ) + assert isinstance(y_df, pandas.DataFrame) + assert isinstance(x_df, pandas.DataFrame) + assert np.array_equal(y_df, [[4], [5], [6]]) + assert np.array_equal(x_df, [[1], [2], [3]]) + assert np.array_equal(y_df.index, [10, 20, 30]) + assert np.array_equal(x_df.index, [10, 20, 30]) + assert np.array_equal(y_df.columns, ["y"]) + assert np.array_equal(x_df.columns, ["x"]) + assert y_df.design_info.column_names == ["y"] + assert x_df.design_info.column_names == ["x"] + assert y_df.design_info.term_names == ["y"] + assert x_df.design_info.term_names == ["x"] + # Same with mix of pandas and unindexed info, even if in different + # matrices + y_df, x_df = build_design_matrices( + [y_builder, x_builder], + {"y": [7, 8, 9], "x": data["x"]}, + return_type="dataframe", + ) + assert isinstance(y_df, pandas.DataFrame) + assert isinstance(x_df, pandas.DataFrame) + assert np.array_equal(y_df, [[7], [8], [9]]) + assert np.array_equal(x_df, [[1], [2], [3]]) + assert np.array_equal(y_df.index, [10, 20, 30]) + assert np.array_equal(x_df.index, [10, 20, 30]) + assert np.array_equal(y_df.columns, ["y"]) + assert np.array_equal(x_df.columns, ["x"]) + assert y_df.design_info.column_names == ["y"] + assert x_df.design_info.column_names == ["x"] + assert y_df.design_info.term_names == ["y"] + assert x_df.design_info.term_names == ["x"] + # Check categorical works for carrying index too + (x_a_df,) = build_design_matrices( + [x_a_builder], {"x": [-1, -2, -3], "a": data["a"]}, return_type="dataframe" + ) + assert isinstance(x_a_df, pandas.DataFrame) + assert np.array_equal(x_a_df, [[1, 0, -1], [0, 1, -2], [1, 0, -3]]) + assert np.array_equal(x_a_df.index, [10, 20, 30]) + # And if we have no indexed input, then we let pandas make up an index as + # per its usual rules: + (x_y_df,) = build_design_matrices( + [x_y_builder], {"y": [7, 8, 9], "x": [10, 11, 12]}, return_type="dataframe" + ) + assert isinstance(x_y_df, pandas.DataFrame) + assert np.array_equal(x_y_df, [[10, 7], [11, 8], [12, 9]]) + assert np.array_equal(x_y_df.index, [0, 1, 2]) + + # If 'data' is a DataFrame, then that suffices, even if no factors are + # available. + (int_df,) = build_design_matrices([int_builder], data, return_type="dataframe") + assert isinstance(int_df, pandas.DataFrame) + assert np.array_equal(int_df, [[1], [1], [1]]) + assert int_df.index.equals(pandas.Index([10, 20, 30])) + + import patsy.build + + had_pandas = patsy.build.have_pandas + try: + patsy.build.have_pandas = False + # return_type="dataframe" gives a nice error if pandas is not available + pytest.raises( + PatsyError, + build_design_matrices, + [x_builder], + {"x": [1, 2, 3]}, + return_type="dataframe", + ) + finally: + patsy.build.have_pandas = had_pandas + + (x_df,) = build_design_matrices( + [x_a_builder], + {"x": [1.0, np.nan, 3.0], "a": np.asarray([None, "a2", "a1"], dtype=object)}, + NA_action="drop", + return_type="dataframe", + ) + assert x_df.index.equals(pandas.Index([2])) + + +def test_data_mismatch(): + test_cases_twoway = [ + # Data type mismatch + ([1, 2, 3], [True, False, True]), + ( + C(["a", "b", "c"], levels=["c", "b", "a"]), + C(["a", "b", "c"], levels=["a", "b", "c"]), + ), + # column number mismatches + ([[1], [2], [3]], [[1, 1], [2, 2], [3, 3]]), + ([[1, 1, 1], [2, 2, 2], [3, 3, 3]], [[1, 1], [2, 2], [3, 3]]), + ] + test_cases_oneway = [ + ([1, 2, 3], ["a", "b", "c"]), + ([1, 2, 3], C(["a", "b", "c"])), + ([True, False, True], C(["a", "b", "c"])), + ([True, False, True], ["a", "b", "c"]), + ] + setup_predict_only = [ + # This is not an error if both are fed in during make_builders, but it + # is an error to pass one to make_builders and the other to + # make_matrices. + (["a", "b", "c"], ["a", "b", "d"]), + ] + termlist = make_termlist(["x"]) + + def t_incremental(data1, data2): + def iter_maker(): + yield {"x": data1} + yield {"x": data2} + + try: + builders = design_matrix_builders([termlist], iter_maker, 0) + build_design_matrices(builders, {"x": data1}) + build_design_matrices(builders, {"x": data2}) + except PatsyError: + pass + else: + raise AssertionError + + def t_setup_predict(data1, data2): + def iter_maker(): + yield {"x": data1} + + builders = design_matrix_builders([termlist], iter_maker, 0) + pytest.raises(PatsyError, build_design_matrices, builders, {"x": data2}) + + for a, b in test_cases_twoway: + t_incremental(a, b) + t_incremental(b, a) + t_setup_predict(a, b) + t_setup_predict(b, a) + for a, b in test_cases_oneway: + t_incremental(a, b) + t_setup_predict(a, b) + for a, b in setup_predict_only: + t_setup_predict(a, b) + t_setup_predict(b, a) + + pytest.raises( + PatsyError, make_matrix, {"x": [1, 2, 3], "y": [1, 2, 3, 4]}, 2, [["x"], ["y"]] + ) + + +def test_data_independent_builder(): + data = {"x": [1, 2, 3]} + + def iter_maker(): + yield data + + # Trying to build a matrix that doesn't depend on the data at all is an + # error, if: + # - the index argument is not given + # - the data is not a DataFrame + # - there are no other matrices + null_builder = design_matrix_builders([make_termlist()], iter_maker, 0)[0] + pytest.raises(PatsyError, build_design_matrices, [null_builder], data) + + intercept_builder = design_matrix_builders( + [make_termlist([])], iter_maker, eval_env=0 + )[0] + pytest.raises(PatsyError, build_design_matrices, [intercept_builder], data) + + pytest.raises( + PatsyError, build_design_matrices, [null_builder, intercept_builder], data + ) + + # If data is a DataFrame, it sets the number of rows. + if have_pandas: + int_m, null_m = build_design_matrices( + [intercept_builder, null_builder], pandas.DataFrame(data) + ) + assert np.allclose(int_m, [[1], [1], [1]]) + assert null_m.shape == (3, 0) + + # If there are other matrices that do depend on the data, we make the + # data-independent matrices have the same number of rows. + x_termlist = make_termlist(["x"]) + + builders = design_matrix_builders( + [x_termlist, make_termlist()], iter_maker, eval_env=0 + ) + x_m, null_m = build_design_matrices(builders, data) + assert np.allclose(x_m, [[1], [2], [3]]) + assert null_m.shape == (3, 0) + + builders = design_matrix_builders( + [x_termlist, make_termlist([])], iter_maker, eval_env=0 + ) + x_m, null_m = build_design_matrices(builders, data) + x_m, intercept_m = build_design_matrices(builders, data) + assert np.allclose(x_m, [[1], [2], [3]]) + assert np.allclose(intercept_m, [[1], [1], [1]]) + + +def test_same_factor_in_two_matrices(): + data = {"x": [1, 2, 3], "a": ["a1", "a2", "a1"]} + + def iter_maker(): + yield data + + t1 = make_termlist(["x"]) + t2 = make_termlist(["x", "a"]) + builders = design_matrix_builders([t1, t2], iter_maker, eval_env=0) + m1, m2 = build_design_matrices(builders, data) + check_design_matrix(m1, 1, t1, column_names=["x"]) + assert np.allclose(m1, [[1], [2], [3]]) + check_design_matrix(m2, 2, t2, column_names=["x:a[a1]", "x:a[a2]"]) + assert np.allclose(m2, [[1, 0], [0, 2], [3, 0]]) + + +def test_eval_env_type_builder(): + data = {"x": [1, 2, 3]} + + def iter_maker(): + yield data + + pytest.raises( + TypeError, design_matrix_builders, [make_termlist("x")], iter_maker, "foo" + ) + + +def test_categorical(): + data_strings = {"a": ["a1", "a2", "a1"]} + data_categ = {"a": C(["a2", "a1", "a2"])} + datas = [data_strings, data_categ] + if have_pandas_categorical: + data_pandas = {"a": pandas.Categorical(["a1", "a2", "a2"])} + datas.append(data_pandas) + + def t(data1, data2): + def iter_maker(): + yield data1 + + builders = design_matrix_builders( + [make_termlist(["a"])], iter_maker, eval_env=0 + ) + build_design_matrices(builders, data2) + + for data1 in datas: + for data2 in datas: + t(data1, data2) + + +def test_contrast(): + from patsy.contrasts import ContrastMatrix, Sum + + values = ["a1", "a3", "a1", "a2"] + + # No intercept in model, full-rank coding of 'a' + m = make_matrix( + {"a": C(values)}, 3, [["a"]], column_names=["a[a1]", "a[a2]", "a[a3]"] + ) + + assert np.allclose(m, [[1, 0, 0], [0, 0, 1], [1, 0, 0], [0, 1, 0]]) + + for s in (Sum, Sum()): + m = make_matrix( + {"a": C(values, s)}, + 3, + [["a"]], + column_names=["a[mean]", "a[S.a1]", "a[S.a2]"], + ) + # Output from R + assert np.allclose(m, [[1, 1, 0], [1, -1, -1], [1, 1, 0], [1, 0, 1]]) + + m = make_matrix( + {"a": C(values, Sum(omit=0))}, + 3, + [["a"]], + column_names=["a[mean]", "a[S.a2]", "a[S.a3]"], + ) + # Output from R + assert np.allclose(m, [[1, -1, -1], [1, 0, 1], [1, -1, -1], [1, 1, 0]]) + + # Intercept in model, non-full-rank coding of 'a' + m = make_matrix( + {"a": C(values)}, + 3, + [[], ["a"]], + column_names=["Intercept", "a[T.a2]", "a[T.a3]"], + ) + + assert np.allclose(m, [[1, 0, 0], [1, 0, 1], [1, 0, 0], [1, 1, 0]]) + + for s in (Sum, Sum()): + m = make_matrix( + {"a": C(values, s)}, + 3, + [[], ["a"]], + column_names=["Intercept", "a[S.a1]", "a[S.a2]"], + ) + # Output from R + assert np.allclose(m, [[1, 1, 0], [1, -1, -1], [1, 1, 0], [1, 0, 1]]) + + m = make_matrix( + {"a": C(values, Sum(omit=0))}, + 3, + [[], ["a"]], + column_names=["Intercept", "a[S.a2]", "a[S.a3]"], + ) + # Output from R + assert np.allclose(m, [[1, -1, -1], [1, 0, 1], [1, -1, -1], [1, 1, 0]]) + + # Weird ad hoc less-than-full-rank coding of 'a' + m = make_matrix( + {"a": C(values, [[7, 12], [2, 13], [8, -1]])}, + 2, + [["a"]], + column_names=["a[custom0]", "a[custom1]"], + ) + assert np.allclose(m, [[7, 12], [8, -1], [7, 12], [2, 13]]) + + m = make_matrix( + { + "a": C( + values, ContrastMatrix([[7, 12], [2, 13], [8, -1]], ["[foo]", "[bar]"]) + ) + }, + 2, + [["a"]], + column_names=["a[foo]", "a[bar]"], + ) + assert np.allclose(m, [[7, 12], [8, -1], [7, 12], [2, 13]]) + + +def test_DesignInfo_subset(): + # For each combination of: + # formula, term names, term objects, mixed term name and term objects + # check that results match subset of full build + # and that removed variables don't hurt + all_data = {"x": [1, 2], "y": [[3.1, 3.2], [4.1, 4.2]], "z": [5, 6]} + all_terms = make_termlist("x", "y", "z") + + def iter_maker(): + yield all_data + + all_builder = design_matrix_builders([all_terms], iter_maker, 0)[0] + full_matrix = build_design_matrices([all_builder], all_data)[0] + + def t(which_terms, variables, columns): + sub_design_info = all_builder.subset(which_terms) + sub_data = {} + for variable in variables: + sub_data[variable] = all_data[variable] + sub_matrix = build_design_matrices([sub_design_info], sub_data)[0] + sub_full_matrix = full_matrix[:, columns] + if not isinstance(which_terms, str): + assert len(which_terms) == len(sub_design_info.terms) + assert np.array_equal(sub_matrix, sub_full_matrix) + + t("~ 0 + x + y + z", ["x", "y", "z"], slice(None)) + t(["x", "y", "z"], ["x", "y", "z"], slice(None)) + t(all_terms, ["x", "y", "z"], slice(None)) + t([all_terms[0], "y", all_terms[2]], ["x", "y", "z"], slice(None)) + + t("~ 0 + x + z", ["x", "z"], [0, 3]) + t(["x", "z"], ["x", "z"], [0, 3]) + t([all_terms[0], all_terms[2]], ["x", "z"], [0, 3]) + t([all_terms[0], "z"], ["x", "z"], [0, 3]) + + t("~ 0 + z + x", ["x", "z"], [3, 0]) + t(["z", "x"], ["x", "z"], [3, 0]) + t([all_terms[2], all_terms[0]], ["x", "z"], [3, 0]) + t([all_terms[2], "x"], ["x", "z"], [3, 0]) + + t("~ 0 + y", ["y"], [1, 2]) + t(["y"], ["y"], [1, 2]) + t([all_terms[1]], ["y"], [1, 2]) + + # Formula can't have a LHS + pytest.raises(PatsyError, all_builder.subset, "a ~ a") + # Term must exist + pytest.raises(KeyError, all_builder.subset, "~ asdf") + pytest.raises(KeyError, all_builder.subset, ["asdf"]) + pytest.raises(KeyError, all_builder.subset, [Term(["asdf"])]) + + # Also check for a minimal DesignInfo (column names only) + min_di = DesignInfo(["a", "b", "c"]) + min_di_subset = min_di.subset(["c", "a"]) + assert min_di_subset.column_names == ["c", "a"] + assert min_di_subset.terms is None diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/test_highlevel.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/test_highlevel.py new file mode 100644 index 0000000000000000000000000000000000000000..2fad925c9158c1dca11f3572f96c3110db07e33a --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/test_highlevel.py @@ -0,0 +1,999 @@ +# This file is part of Patsy +# Copyright (C) 2012-2013 Nathaniel Smith +# See file LICENSE.txt for license information. + +# Exhaustive end-to-end tests of the top-level API. + +import numpy as np +import pytest + +from patsy import PatsyError +from patsy.design_info import DesignMatrix, DesignInfo +from patsy.eval import EvalEnvironment +from patsy.desc import ModelDesc, Term, INTERCEPT +from patsy.categorical import C +from patsy.contrasts import Helmert +from patsy.user_util import balanced, LookupFactor +from patsy.build import design_matrix_builders, build_design_matrices +from patsy.highlevel import dmatrix, dmatrices, incr_dbuilder, incr_dbuilders +from patsy.util import ( + have_pandas, + have_pandas_categorical, + have_pandas_categorical_dtype, + pandas_Categorical_from_codes, +) +from patsy.origin import Origin + +if have_pandas: + import pandas + + +def check_result( + expect_full_designs, + lhs, + rhs, + data, + expected_rhs_values, + expected_rhs_names, + expected_lhs_values, + expected_lhs_names, +): # pragma: no cover + assert np.allclose(rhs, expected_rhs_values) + assert rhs.design_info.column_names == expected_rhs_names + if lhs is not None: + assert np.allclose(lhs, expected_lhs_values) + assert lhs.design_info.column_names == expected_lhs_names + else: + assert expected_lhs_values is None + assert expected_lhs_names is None + + if expect_full_designs: + if lhs is None: + (new_rhs,) = build_design_matrices([rhs.design_info], data) + else: + new_lhs, new_rhs = build_design_matrices( + [lhs.design_info, rhs.design_info], data + ) + assert np.allclose(new_lhs, lhs) + assert new_lhs.design_info.column_names == expected_lhs_names + assert np.allclose(new_rhs, rhs) + assert new_rhs.design_info.column_names == expected_rhs_names + else: + assert rhs.design_info.terms is None + assert lhs is None or lhs.design_info.terms is None + + +def dmatrix_pandas(formula_like, data={}, depth=0, return_type="matrix"): + return_type = "dataframe" + if isinstance(depth, int): + depth += 1 + return dmatrix(formula_like, data, depth, return_type=return_type) + + +def dmatrices_pandas(formula_like, data={}, depth=0, return_type="matrix"): + return_type = "dataframe" + if isinstance(depth, int): + depth += 1 + return dmatrices(formula_like, data, depth, return_type=return_type) + + +def t( + formula_like, + data, + depth, + expect_full_designs, + expected_rhs_values, + expected_rhs_names, + expected_lhs_values=None, + expected_lhs_names=None, +): # pragma: no cover + if isinstance(depth, int): + depth += 1 + + def data_iter_maker(): + return iter([data]) + + if ( + isinstance(formula_like, (str, ModelDesc, DesignInfo)) + or (isinstance(formula_like, tuple) and isinstance(formula_like[0], DesignInfo)) + or hasattr(formula_like, "__patsy_get_model_desc__") + ): + if expected_lhs_values is None: + builder = incr_dbuilder(formula_like, data_iter_maker, depth) + lhs = None + (rhs,) = build_design_matrices([builder], data) + else: + builders = incr_dbuilders(formula_like, data_iter_maker, depth) + lhs, rhs = build_design_matrices(builders, data) + check_result( + expect_full_designs, + lhs, + rhs, + data, + expected_rhs_values, + expected_rhs_names, + expected_lhs_values, + expected_lhs_names, + ) + else: + pytest.raises(PatsyError, incr_dbuilders, formula_like, data_iter_maker) + pytest.raises(PatsyError, incr_dbuilder, formula_like, data_iter_maker) + one_mat_fs = [dmatrix] + two_mat_fs = [dmatrices] + if have_pandas: + one_mat_fs.append(dmatrix_pandas) + two_mat_fs.append(dmatrices_pandas) + if expected_lhs_values is None: + for f in one_mat_fs: + rhs = f(formula_like, data, depth) + check_result( + expect_full_designs, + None, + rhs, + data, + expected_rhs_values, + expected_rhs_names, + expected_lhs_values, + expected_lhs_names, + ) + + # We inline assert_raises here to avoid complications with the + # depth argument. + for f in two_mat_fs: + try: + f(formula_like, data, depth) + except PatsyError: + pass + else: + raise AssertionError + else: + for f in one_mat_fs: + try: + f(formula_like, data, depth) + except PatsyError: + pass + else: + raise AssertionError + + for f in two_mat_fs: + (lhs, rhs) = f(formula_like, data, depth) + check_result( + expect_full_designs, + lhs, + rhs, + data, + expected_rhs_values, + expected_rhs_names, + expected_lhs_values, + expected_lhs_names, + ) + + +def t_invalid(formula_like, data, depth, exc=PatsyError): # pragma: no cover + if isinstance(depth, int): + depth += 1 + fs = [dmatrix, dmatrices] + if have_pandas: + fs += [dmatrix_pandas, dmatrices_pandas] + for f in fs: + try: + f(formula_like, data, depth) + except exc: + pass + else: + raise AssertionError + + +# Exercise all the different calling conventions for the high-level API +def test_formula_likes(): + # Plain array-like, rhs only + t([[1, 2, 3], [4, 5, 6]], {}, 0, False, [[1, 2, 3], [4, 5, 6]], ["x0", "x1", "x2"]) + t( + (None, [[1, 2, 3], [4, 5, 6]]), + {}, + 0, + False, + [[1, 2, 3], [4, 5, 6]], + ["x0", "x1", "x2"], + ) + t( + np.asarray([[1, 2, 3], [4, 5, 6]]), + {}, + 0, + False, + [[1, 2, 3], [4, 5, 6]], + ["x0", "x1", "x2"], + ) + t( + (None, np.asarray([[1, 2, 3], [4, 5, 6]])), + {}, + 0, + False, + [[1, 2, 3], [4, 5, 6]], + ["x0", "x1", "x2"], + ) + dm = DesignMatrix([[1, 2, 3], [4, 5, 6]], default_column_prefix="foo") + t(dm, {}, 0, False, [[1, 2, 3], [4, 5, 6]], ["foo0", "foo1", "foo2"]) + t((None, dm), {}, 0, False, [[1, 2, 3], [4, 5, 6]], ["foo0", "foo1", "foo2"]) + + # Plain array-likes, lhs and rhs + t( + ([1, 2], [[1, 2, 3], [4, 5, 6]]), + {}, + 0, + False, + [[1, 2, 3], [4, 5, 6]], + ["x0", "x1", "x2"], + [[1], [2]], + ["y0"], + ) + t( + ([[1], [2]], [[1, 2, 3], [4, 5, 6]]), + {}, + 0, + False, + [[1, 2, 3], [4, 5, 6]], + ["x0", "x1", "x2"], + [[1], [2]], + ["y0"], + ) + t( + (np.asarray([1, 2]), np.asarray([[1, 2, 3], [4, 5, 6]])), + {}, + 0, + False, + [[1, 2, 3], [4, 5, 6]], + ["x0", "x1", "x2"], + [[1], [2]], + ["y0"], + ) + t( + (np.asarray([[1], [2]]), np.asarray([[1, 2, 3], [4, 5, 6]])), + {}, + 0, + False, + [[1, 2, 3], [4, 5, 6]], + ["x0", "x1", "x2"], + [[1], [2]], + ["y0"], + ) + x_dm = DesignMatrix([[1, 2, 3], [4, 5, 6]], default_column_prefix="foo") + y_dm = DesignMatrix([1, 2], default_column_prefix="bar") + t( + (y_dm, x_dm), + {}, + 0, + False, + [[1, 2, 3], [4, 5, 6]], + ["foo0", "foo1", "foo2"], + [[1], [2]], + ["bar0"], + ) + # number of rows must match + t_invalid(([1, 2, 3], [[1, 2, 3], [4, 5, 6]]), {}, 0) + + # tuples must have the right size + t_invalid(([[1, 2, 3]],), {}, 0) + t_invalid(([[1, 2, 3]], [[1, 2, 3]], [[1, 2, 3]]), {}, 0) + + # plain Series and DataFrames + if have_pandas: + # Names are extracted + t(pandas.DataFrame({"x": [1, 2, 3]}), {}, 0, False, [[1], [2], [3]], ["x"]) + t( + pandas.Series([1, 2, 3], name="asdf"), + {}, + 0, + False, + [[1], [2], [3]], + ["asdf"], + ) + t( + (pandas.DataFrame({"y": [4, 5, 6]}), pandas.DataFrame({"x": [1, 2, 3]})), + {}, + 0, + False, + [[1], [2], [3]], + ["x"], + [[4], [5], [6]], + ["y"], + ) + t( + (pandas.Series([4, 5, 6], name="y"), pandas.Series([1, 2, 3], name="x")), + {}, + 0, + False, + [[1], [2], [3]], + ["x"], + [[4], [5], [6]], + ["y"], + ) + # Or invented + t( + ( + pandas.DataFrame([[4, 5, 6]]), + pandas.DataFrame([[1, 2, 3]], columns=[7, 8, 9]), + ), + {}, + 0, + False, + [[1, 2, 3]], + ["x7", "x8", "x9"], + [[4, 5, 6]], + ["y0", "y1", "y2"], + ) + t(pandas.Series([1, 2, 3]), {}, 0, False, [[1], [2], [3]], ["x0"]) + # indices must match + t_invalid( + (pandas.DataFrame([[1]], index=[1]), pandas.DataFrame([[1]], index=[2])), + {}, + 0, + ) + + # Foreign ModelDesc factories + class ForeignModelSource(object): + def __patsy_get_model_desc__(self, data): + return ModelDesc([Term([LookupFactor("Y")])], [Term([LookupFactor("X")])]) + + foreign_model = ForeignModelSource() + t( + foreign_model, + {"Y": [1, 2], "X": [[1, 2], [3, 4]]}, + 0, + True, + [[1, 2], [3, 4]], + ["X[0]", "X[1]"], + [[1], [2]], + ["Y"], + ) + + class BadForeignModelSource(object): + def __patsy_get_model_desc__(self, data): + return data + + t_invalid(BadForeignModelSource(), {}, 0) + + # string formulas + t( + "y ~ x", + {"y": [1, 2], "x": [3, 4]}, + 0, + True, + [[1, 3], [1, 4]], + ["Intercept", "x"], + [[1], [2]], + ["y"], + ) + t("~ x", {"y": [1, 2], "x": [3, 4]}, 0, True, [[1, 3], [1, 4]], ["Intercept", "x"]) + t( + "x + y", + {"y": [1, 2], "x": [3, 4]}, + 0, + True, + [[1, 3, 1], [1, 4, 2]], + ["Intercept", "x", "y"], + ) + + # ModelDesc + desc = ModelDesc([], [Term([LookupFactor("x")])]) + t(desc, {"x": [1.5, 2.5, 3.5]}, 0, True, [[1.5], [2.5], [3.5]], ["x"]) + desc = ModelDesc([], [Term([]), Term([LookupFactor("x")])]) + t( + desc, + {"x": [1.5, 2.5, 3.5]}, + 0, + True, + [[1, 1.5], [1, 2.5], [1, 3.5]], + ["Intercept", "x"], + ) + desc = ModelDesc([Term([LookupFactor("y")])], [Term([]), Term([LookupFactor("x")])]) + t( + desc, + {"x": [1.5, 2.5, 3.5], "y": [10, 20, 30]}, + 0, + True, + [[1, 1.5], [1, 2.5], [1, 3.5]], + ["Intercept", "x"], + [[10], [20], [30]], + ["y"], + ) + + # builders + termlists = ( + [], + [Term([LookupFactor("x")])], + [Term([]), Term([LookupFactor("x")])], + ) + builders = design_matrix_builders( + termlists, lambda: iter([{"x": [1, 2, 3]}]), eval_env=0 + ) + # twople but with no LHS + t( + (builders[0], builders[2]), + {"x": [10, 20, 30]}, + 0, + True, + [[1, 10], [1, 20], [1, 30]], + ["Intercept", "x"], + ) + # single DesignInfo + t( + builders[2], + {"x": [10, 20, 30]}, + 0, + True, + [[1, 10], [1, 20], [1, 30]], + ["Intercept", "x"], + ) + # twople with LHS + t( + (builders[1], builders[2]), + {"x": [10, 20, 30]}, + 0, + True, + [[1, 10], [1, 20], [1, 30]], + ["Intercept", "x"], + [[10], [20], [30]], + ["x"], + ) + + # check depth arguments + x_in_env = [1, 2, 3] + t("~ x_in_env", {}, 0, True, [[1, 1], [1, 2], [1, 3]], ["Intercept", "x_in_env"]) + t( + "~ x_in_env", + {"x_in_env": [10, 20, 30]}, + 0, + True, + [[1, 10], [1, 20], [1, 30]], + ["Intercept", "x_in_env"], + ) + # Trying to pull x_in_env out of our *caller* shouldn't work. + t_invalid("~ x_in_env", {}, 1, exc=(NameError, PatsyError)) + + # But then again it should, if called from one down on the stack: + def check_nested_call(): + x_in_env = "asdf" + t( + "~ x_in_env", + {}, + 1, + True, + [[1, 1], [1, 2], [1, 3]], + ["Intercept", "x_in_env"], + ) + + check_nested_call() + # passing in an explicit EvalEnvironment also works: + e = EvalEnvironment.capture(1) + t_invalid("~ x_in_env", {}, e, exc=(NameError, PatsyError)) + e = EvalEnvironment.capture(0) + + def check_nested_call_2(): + x_in_env = "asdf" + t( + "~ x_in_env", + {}, + e, + True, + [[1, 1], [1, 2], [1, 3]], + ["Intercept", "x_in_env"], + ) + + check_nested_call_2() + + +def test_return_pandas(): + if not have_pandas: + return + # basic check of pulling a Series out of the environment + s1 = pandas.Series([1, 2, 3], name="AA", index=[10, 20, 30]) + s2 = pandas.Series([4, 5, 6], name="BB", index=[10, 20, 30]) + df1 = dmatrix("s1", return_type="dataframe") + assert np.allclose(df1, [[1, 1], [1, 2], [1, 3]]) + assert np.array_equal(df1.columns, ["Intercept", "s1"]) + assert df1.design_info.column_names == ["Intercept", "s1"] + assert np.array_equal(df1.index, [10, 20, 30]) + df2, df3 = dmatrices("s2 ~ s1", return_type="dataframe") + assert np.allclose(df2, [[4], [5], [6]]) + assert np.array_equal(df2.columns, ["s2"]) + assert df2.design_info.column_names == ["s2"] + assert np.array_equal(df2.index, [10, 20, 30]) + assert np.allclose(df3, [[1, 1], [1, 2], [1, 3]]) + assert np.array_equal(df3.columns, ["Intercept", "s1"]) + assert df3.design_info.column_names == ["Intercept", "s1"] + assert np.array_equal(df3.index, [10, 20, 30]) + # indices are preserved if pandas is passed in directly + df4 = dmatrix(s1, return_type="dataframe") + assert np.allclose(df4, [[1], [2], [3]]) + assert np.array_equal(df4.columns, ["AA"]) + assert df4.design_info.column_names == ["AA"] + assert np.array_equal(df4.index, [10, 20, 30]) + df5, df6 = dmatrices((s2, s1), return_type="dataframe") + assert np.allclose(df5, [[4], [5], [6]]) + assert np.array_equal(df5.columns, ["BB"]) + assert df5.design_info.column_names == ["BB"] + assert np.array_equal(df5.index, [10, 20, 30]) + assert np.allclose(df6, [[1], [2], [3]]) + assert np.array_equal(df6.columns, ["AA"]) + assert df6.design_info.column_names == ["AA"] + assert np.array_equal(df6.index, [10, 20, 30]) + # Both combinations of with-index and without-index + df7, df8 = dmatrices((s1, [10, 11, 12]), return_type="dataframe") + assert np.array_equal(df7.index, s1.index) + assert np.array_equal(df8.index, s1.index) + df9, df10 = dmatrices(([10, 11, 12], s1), return_type="dataframe") + assert np.array_equal(df9.index, s1.index) + assert np.array_equal(df10.index, s1.index) + # pandas must be available + import patsy.highlevel + + had_pandas = patsy.highlevel.have_pandas + try: + patsy.highlevel.have_pandas = False + pytest.raises(PatsyError, dmatrix, "x", {"x": [1]}, 0, return_type="dataframe") + pytest.raises( + PatsyError, + dmatrices, + "y ~ x", + {"x": [1], "y": [2]}, + 0, + return_type="dataframe", + ) + finally: + patsy.highlevel.have_pandas = had_pandas + + +def test_term_info(): + data = balanced(a=2, b=2) + rhs = dmatrix("a:b", data) + assert rhs.design_info.column_names == [ + "Intercept", + "b[T.b2]", + "a[T.a2]:b[b1]", + "a[T.a2]:b[b2]", + ] + assert rhs.design_info.term_names == ["Intercept", "a:b"] + assert len(rhs.design_info.terms) == 2 + assert rhs.design_info.terms[0] == INTERCEPT + + +def test_data_types(): + data = { + "a": [1, 2, 3], + "b": [1.0, 2.0, 3.0], + "c": np.asarray([1, 2, 3], dtype=np.float32), + "d": [True, False, True], + "e": ["foo", "bar", "baz"], + "f": C([1, 2, 3]), + "g": C(["foo", "bar", "baz"]), + "h": np.array(["foo", 1, (1, "hi")], dtype=object), + } + t("~ 0 + a", data, 0, True, [[1], [2], [3]], ["a"]) + t("~ 0 + b", data, 0, True, [[1], [2], [3]], ["b"]) + t("~ 0 + c", data, 0, True, [[1], [2], [3]], ["c"]) + t("~ 0 + d", data, 0, True, [[0, 1], [1, 0], [0, 1]], ["d[False]", "d[True]"]) + t( + "~ 0 + e", + data, + 0, + True, + [[0, 0, 1], [1, 0, 0], [0, 1, 0]], + ["e[bar]", "e[baz]", "e[foo]"], + ) + t( + "~ 0 + f", + data, + 0, + True, + [[1, 0, 0], [0, 1, 0], [0, 0, 1]], + ["f[1]", "f[2]", "f[3]"], + ) + t( + "~ 0 + g", + data, + 0, + True, + [[0, 0, 1], [1, 0, 0], [0, 1, 0]], + ["g[bar]", "g[baz]", "g[foo]"], + ) + # This depends on Python's sorting behavior: + t( + "~ 0 + h", + data, + 0, + True, + [[0, 1, 0], [1, 0, 0], [0, 0, 1]], + ["h[1]", "h[foo]", "h[(1, 'hi')]"], + ) + + +def test_categorical(): + data = balanced(a=2, b=2) + # There are more exhaustive tests for all the different coding options in + # test_build; let's just make sure that C() and stuff works. + t( + "~ C(a)", + data, + 0, + True, + [[1, 0], [1, 0], [1, 1], [1, 1]], + ["Intercept", "C(a)[T.a2]"], + ) + t( + "~ C(a, levels=['a2', 'a1'])", + data, + 0, + True, + [[1, 1], [1, 1], [1, 0], [1, 0]], + ["Intercept", "C(a, levels=['a2', 'a1'])[T.a1]"], + ) + t( + "~ C(a, Treatment(reference=-1))", + data, + 0, + True, + [[1, 1], [1, 1], [1, 0], [1, 0]], + ["Intercept", "C(a, Treatment(reference=-1))[T.a1]"], + ) + + # Different interactions + t( + "a*b", + data, + 0, + True, + [[1, 0, 0, 0], [1, 0, 1, 0], [1, 1, 0, 0], [1, 1, 1, 1]], + ["Intercept", "a[T.a2]", "b[T.b2]", "a[T.a2]:b[T.b2]"], + ) + t( + "0 + a:b", + data, + 0, + True, + [[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]], + ["a[a1]:b[b1]", "a[a2]:b[b1]", "a[a1]:b[b2]", "a[a2]:b[b2]"], + ) + t( + "1 + a + a:b", + data, + 0, + True, + [[1, 0, 0, 0], [1, 0, 1, 0], [1, 1, 0, 0], [1, 1, 0, 1]], + ["Intercept", "a[T.a2]", "a[a1]:b[T.b2]", "a[a2]:b[T.b2]"], + ) + + # Changing contrast with C() + data["a"] = C(data["a"], Helmert) + t("a", data, 0, True, [[1, -1], [1, -1], [1, 1], [1, 1]], ["Intercept", "a[H.a2]"]) + t( + "C(a, Treatment)", + data, + 0, + True, + [[1, 0], [1, 0], [1, 1], [1, 1]], + ["Intercept", "C(a, Treatment)[T.a2]"], + ) + # That didn't affect the original object + t("a", data, 0, True, [[1, -1], [1, -1], [1, 1], [1, 1]], ["Intercept", "a[H.a2]"]) + + +def test_builtins(): + data = {"x": [1, 2, 3], "y": [4, 5, 6], "a b c": [10, 20, 30]} + t("0 + I(x + y)", data, 0, True, [[1], [2], [3], [4], [5], [6]], ["I(x + y)"]) + t( + "Q('a b c')", + data, + 0, + True, + [[1, 10], [1, 20], [1, 30]], + ["Intercept", "Q('a b c')"], + ) + t("center(x)", data, 0, True, [[1, -1], [1, 0], [1, 1]], ["Intercept", "center(x)"]) + + +def test_incremental(): + # incr_dbuilder(s) + # stateful transformations + datas = [ + {"a": ["a2", "a2", "a2"], "x": [1, 2, 3]}, + {"a": ["a2", "a2", "a1"], "x": [4, 5, 6]}, + ] + x = np.asarray([1, 2, 3, 4, 5, 6]) + sin_center_x = np.sin(x - np.mean(x)) + x_col = sin_center_x - np.mean(sin_center_x) + + def data_iter_maker(): + return iter(datas) + + builders = incr_dbuilders("1 ~ a + center(np.sin(center(x)))", data_iter_maker) + lhs, rhs = build_design_matrices(builders, datas[1]) + assert lhs.design_info.column_names == ["Intercept"] + assert rhs.design_info.column_names == [ + "Intercept", + "a[T.a2]", + "center(np.sin(center(x)))", + ] + assert np.allclose(lhs, [[1], [1], [1]]) + assert np.allclose(rhs, np.column_stack(([1, 1, 1], [1, 1, 0], x_col[3:]))) + + builder = incr_dbuilder("~ a + center(np.sin(center(x)))", data_iter_maker) + (rhs,) = build_design_matrices([builder], datas[1]) + assert rhs.design_info.column_names == [ + "Intercept", + "a[T.a2]", + "center(np.sin(center(x)))", + ] + assert np.allclose(lhs, [[1], [1], [1]]) + assert np.allclose(rhs, np.column_stack(([1, 1, 1], [1, 1, 0], x_col[3:]))) + + pytest.raises(PatsyError, incr_dbuilder, "x ~ x", data_iter_maker) + pytest.raises(PatsyError, incr_dbuilders, "x", data_iter_maker) + + +def test_env_transform(): + t( + "~ np.sin(x)", + {"x": [1, 2, 3]}, + 0, + True, + [[1, np.sin(1)], [1, np.sin(2)], [1, np.sin(3)]], + ["Intercept", "np.sin(x)"], + ) + + +# Term ordering: +# 1) all 0-order no-numeric +# 2) all 1st-order no-numeric +# 3) all 2nd-order no-numeric +# 4) ... +# 5) all 0-order with the first numeric interaction encountered +# 6) all 1st-order with the first numeric interaction encountered +# 7) ... +# 8) all 0-order with the second numeric interaction encountered +# 9) ... +def test_term_order(): + data = balanced(a=2, b=2) + data["x1"] = np.linspace(0, 1, 4) + data["x2"] = data["x1"] ** 2 + + def t_terms(formula, order): + m = dmatrix(formula, data) + assert m.design_info.term_names == order + + t_terms("a + b + x1 + x2", ["Intercept", "a", "b", "x1", "x2"]) + t_terms("b + a + x2 + x1", ["Intercept", "b", "a", "x2", "x1"]) + t_terms("0 + x1 + a + x2 + b + 1", ["Intercept", "a", "b", "x1", "x2"]) + t_terms("0 + a:b + a + b + 1", ["Intercept", "a", "b", "a:b"]) + t_terms("a + a:x1 + x2 + x1 + b", ["Intercept", "a", "b", "x1", "a:x1", "x2"]) + t_terms( + "0 + a:x1:x2 + a + x2:x1:b + x2 + x1 + a:x1 + x1:x2 + x1:a:x2:a:b", + ["a", "x1:x2", "a:x1:x2", "x2:x1:b", "x1:a:x2:b", "x2", "x1", "a:x1"], + ) + + +def _check_division(expect_true_division): # pragma: no cover + # We evaluate the formula "I(x / y)" in our *caller's* scope, so the + # result depends on whether our caller has done 'from __future__ import + # division'. + data = {"x": 5, "y": 2} + m = dmatrix("0 + I(x / y)", data, 1) + if expect_true_division: + assert np.allclose(m, [[2.5]]) + else: + assert np.allclose(m, [[2]]) + + +def test_multicolumn(): + data = { + "a": ["a1", "a2"], + "X": [[1, 2], [3, 4]], + "Y": [[1, 3], [2, 4]], + } + t( + "X*Y", + data, + 0, + True, + [ + [1, 1, 2, 1, 3, 1 * 1, 2 * 1, 1 * 3, 2 * 3], + [1, 3, 4, 2, 4, 3 * 2, 4 * 2, 3 * 4, 4 * 4], + ], + [ + "Intercept", + "X[0]", + "X[1]", + "Y[0]", + "Y[1]", + "X[0]:Y[0]", + "X[1]:Y[0]", + "X[0]:Y[1]", + "X[1]:Y[1]", + ], + ) + t( + "a:X + Y", + data, + 0, + True, + [[1, 1, 0, 2, 0, 1, 3], [1, 0, 3, 0, 4, 2, 4]], + [ + "Intercept", + "a[a1]:X[0]", + "a[a2]:X[0]", + "a[a1]:X[1]", + "a[a2]:X[1]", + "Y[0]", + "Y[1]", + ], + ) + + +def test_dmatrix_dmatrices_no_data(): + x = [1, 2, 3] + y = [4, 5, 6] + assert np.allclose(dmatrix("x"), [[1, 1], [1, 2], [1, 3]]) + lhs, rhs = dmatrices("y ~ x") + assert np.allclose(lhs, [[4], [5], [6]]) + assert np.allclose(rhs, [[1, 1], [1, 2], [1, 3]]) + + +def test_designinfo_describe(): + lhs, rhs = dmatrices( + "y ~ x + a", {"y": [1, 2, 3], "x": [4, 5, 6], "a": ["a1", "a2", "a3"]} + ) + assert lhs.design_info.describe() == "y" + assert rhs.design_info.describe() == "1 + a + x" + + +def test_evalfactor_reraise(): + # This will produce a PatsyError, but buried inside the factor evaluation, + # so the original code has no way to give it an appropriate origin= + # attribute. EvalFactor should notice this, and add a useful origin: + def raise_patsy_error(x): + raise PatsyError("WHEEEEEE") + + formula = "raise_patsy_error(X) + Y" + try: + dmatrix(formula, {"X": [1, 2, 3], "Y": [4, 5, 6]}) + except PatsyError as e: + assert e.origin == Origin(formula, 0, formula.index(" ")) + else: + assert False + # This will produce a KeyError, which on Python 3 we can do wrap without + # destroying the traceback, so we do so. On Python 2 we let the original + # exception escape. + try: + dmatrix("1 + x[1]", {"x": {}}) + except Exception as e: + assert isinstance(e, PatsyError) + assert e.origin == Origin("1 + x[1]", 4, 8) + else: + assert False + + +def test_dmatrix_NA_action(): + data = {"x": [1, 2, 3, np.nan], "y": [np.nan, 20, 30, 40]} + + return_types = ["matrix"] + if have_pandas: + return_types.append("dataframe") + + for return_type in return_types: + mat = dmatrix("x + y", data=data, return_type=return_type) + assert np.array_equal(mat, [[1, 2, 20], [1, 3, 30]]) + if return_type == "dataframe": + assert mat.index.equals(pandas.Index([1, 2])) + pytest.raises( + PatsyError, + dmatrix, + "x + y", + data=data, + return_type=return_type, + NA_action="raise", + ) + + lmat, rmat = dmatrices("y ~ x", data=data, return_type=return_type) + assert np.array_equal(lmat, [[20], [30]]) + assert np.array_equal(rmat, [[1, 2], [1, 3]]) + if return_type == "dataframe": + assert lmat.index.equals(pandas.Index([1, 2])) + assert rmat.index.equals(pandas.Index([1, 2])) + pytest.raises( + PatsyError, + dmatrices, + "y ~ x", + data=data, + return_type=return_type, + NA_action="raise", + ) + + # Initial release for the NA handling code had problems with + # non-data-dependent matrices like "~ 1". + lmat, rmat = dmatrices("y ~ 1", data=data, return_type=return_type) + assert np.array_equal(lmat, [[20], [30], [40]]) + assert np.array_equal(rmat, [[1], [1], [1]]) + if return_type == "dataframe": + assert lmat.index.equals(pandas.Index([1, 2, 3])) + assert rmat.index.equals(pandas.Index([1, 2, 3])) + pytest.raises( + PatsyError, + dmatrices, + "y ~ 1", + data=data, + return_type=return_type, + NA_action="raise", + ) + + +def test_0d_data(): + # Use case from statsmodels/statsmodels#1881 + data_0d = {"x1": 1.1, "x2": 1.2, "a": "a1"} + + for formula, expected in [ + ("x1 + x2", [[1, 1.1, 1.2]]), + ("C(a, levels=('a1', 'a2')) + x1", [[1, 0, 1.1]]), + ]: + mat = dmatrix(formula, data_0d) + assert np.allclose(mat, expected) + + assert np.allclose( + build_design_matrices([mat.design_info], data_0d)[0], expected + ) + if have_pandas: + data_series = pandas.Series(data_0d) + assert np.allclose(dmatrix(formula, data_series), expected) + + assert np.allclose( + build_design_matrices([mat.design_info], data_series)[0], expected + ) + + +def test_env_not_saved_in_builder(): + x_in_env = [1, 2, 3] + design_matrix = dmatrix("x_in_env", {}) + + x_in_env = [10, 20, 30] + design_matrix2 = dmatrix(design_matrix.design_info, {}) + + assert np.allclose(design_matrix, design_matrix2) + + +def test_C_and_pandas_categorical(): + if not have_pandas_categorical: + return + + objs = [pandas_Categorical_from_codes([1, 0, 1], ["b", "a"])] + if have_pandas_categorical_dtype: + objs.append(pandas.Series(objs[0])) + for obj in objs: + d = {"obj": obj} + assert np.allclose(dmatrix("obj", d), [[1, 1], [1, 0], [1, 1]]) + + assert np.allclose(dmatrix("C(obj)", d), [[1, 1], [1, 0], [1, 1]]) + + assert np.allclose( + dmatrix("C(obj, levels=['b', 'a'])", d), [[1, 1], [1, 0], [1, 1]] + ) + + assert np.allclose( + dmatrix("C(obj, levels=['a', 'b'])", d), [[1, 0], [1, 1], [1, 0]] + ) + + +def test_NAActioon_pandas_string_index(): + if not have_pandas: + return + from patsy.missing import NAAction + + formula = "1 + x + z" + action = NAAction("drop") + data = pandas.DataFrame( + {"z": [1.0, np.nan, 2.0], "x": [1, 2, 3]}, index=["a", "b", "c"] + ) + dm = dmatrix(formula, data, 0, NA_action=action, return_type="dataframe") + di = dm.design_info + data2 = pandas.DataFrame({"z": [4.0, 5.0], "x": [6, 7]}) + dm2 = dmatrix(di, data2, 0, return_type="dataframe") + assert np.allclose(dm2, [[1.0, 6.0, 4.0], [1.0, 7.0, 5.0]]) + assert list(dm2.columns) == ["Intercept", "x", "z"] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/test_regressions.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/test_regressions.py new file mode 100644 index 0000000000000000000000000000000000000000..2760846382b940556c313412814572a8d79e82ff --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/test_regressions.py @@ -0,0 +1,24 @@ +# This file is part of Patsy +# Copyright (C) 2013 Nathaniel Smith +# See file LICENSE.txt for license information. + +# Regression tests for fixed bugs (when not otherwise better covered somewhere +# else) + +from patsy import EvalEnvironment, dmatrix, build_design_matrices, PatsyError, Origin + + +def test_issue_11(): + # Give a sensible error message for level mismatches + # (At some points we've failed to put an origin= on these errors) + env = EvalEnvironment.capture() + data = {"X": [0, 1, 2, 3], "Y": [1, 2, 3, 4]} + formula = "C(X) + Y" + new_data = {"X": [0, 0, 1, 2, 3, 3, 4], "Y": [1, 2, 3, 4, 5, 6, 7]} + info = dmatrix(formula, data) + try: + build_design_matrices([info.design_info], new_data) + except PatsyError as e: + assert e.origin == Origin(formula, 0, 4) + else: + assert False diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/test_splines_bs_data.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/test_splines_bs_data.py new file mode 100644 index 0000000000000000000000000000000000000000..6b233fcdec9eac4ea77f0ab18f9de87963859fae --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/test_splines_bs_data.py @@ -0,0 +1,607 @@ +# This file auto-generated by tools/get-R-bs-test-vectors.R +# Using: R version 2.15.1 (2012-06-22) +import numpy as np + +R_bs_test_x = np.array( + [ + 1, + 1.5, + 2.25, + 3.375, + 5.0625, + 7.59375, + 11.390625, + 17.0859375, + 25.62890625, + 38.443359375, + 57.6650390625, + 86.49755859375, + 129.746337890625, + 194.6195068359375, + 291.92926025390625, + 437.893890380859375, + 656.8408355712890625, + 985.26125335693359375, + 1477.8918800354003906, + 2216.8378200531005859, + ] +) +R_bs_test_data = """ +--BEGIN TEST CASE-- +degree=1 +df=3 +intercept=TRUE +Boundary.knots=None +knots=None +output=np.array([1, 0.98937395581474985029, 0.97343488953687462573, 0.94952629012006184439, 0.91366339099484261688, 0.85986904230701377561, 0.77917751927527056921, 0.65814023472765570411, 0.47658430790623346196, 0.20425041767410004323, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.010626044185250137566, 0.026565110463125343049, 0.050473709879938155609, 0.086336609005157369245, 0.14013095769298619664, 0.22082248072472943079, 0.34185976527234429589, 0.52341569209376659355, 0.79574958232589998453, 0.99556855753085560234, 0.98227423012342263142, 0.96233273901227300851, 0.93242050234554862964, 0.88755214734546206135, 0.82024961484533231992, 0.71929581609513748575, 0.56786511796984540101, 0.34071907078190727391, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0044314424691443508181, 0.017725769876577403272, 0.037667260987726984556, 0.067579497654451342603, 0.11244785265453789702, 0.17975038515466773559, 0.28070418390486245874, 0.43213488203015459899, 0.6592809292180927816, 1, ]).reshape((20, 3, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=5 +intercept=TRUE +Boundary.knots=None +knots=None +output=np.array([1, 0.9161205766710354137, 0.79030144167758842322, 0.60157273918741804852, 0.31847968545216254199, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.083879423328964614059, 0.20969855832241152127, 0.39842726081258189597, 0.68152031454783745801, 0.9846005774783446185, 0.89220404234841199642, 0.7536092396535130078, 0.54571703561116458037, 0.23387872954764196698, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.015399422521655438748, 0.10779595765158807297, 0.24639076034648701996, 0.45428296438883541963, 0.76612127045235811629, 0.96572040707016604255, 0.86288162828066417021, 0.7086234600964114172, 0.47723620782003217666, 0.13015532940546331586, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.034279592929833957449, 0.13711837171933582979, 0.29137653990358863831, 0.52276379217996793436, 0.86984467059453673965, 0.94202898550724645244, 0.82608695652173913526, 0.65217391304347827052, 0.39130434782608697342, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.057971014492753623892, 0.17391304347826089249, 0.34782608695652178499, 0.60869565217391308209, 1, ]).reshape((20, 5, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=12 +intercept=TRUE +Boundary.knots=None +knots=None +output=np.array([1, 0.52173913043478281626, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.47826086956521718374, 0.90243902439024414885, 0.36585365853658557977, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.097560975609755906657, 0.63414634146341442023, 0.77777777777777779011, 0.16666666666666651864, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.22222222222222218213, 0.83333333333333348136, 0.625, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.37499999999999994449, 0.96992481203007530066, 0.47368421052631592971, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.030075187969924695869, 0.52631578947368407029, 0.86440677966101697738, 0.30508474576271171763, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.13559322033898302262, 0.69491525423728828237, 0.72815533980582491935, 0.087378640776698143777, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.27184466019417513616, 0.91262135922330189786, 0.57446808510638269762, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.42553191489361730238, 0.9375, 0.4218750000000004996, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.062499999999999958367, 0.57812499999999944489, 0.82300884955752262595, 0.23893805309734547637, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.17699115044247745732, 0.76106194690265460689, 0.67346938775510212238, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.32653061224489787762, 1, ]).reshape((20, 12, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=None +intercept=TRUE +Boundary.knots=None +knots=np.array([]) +output=np.array([1, 0.99977435171677508929, 0.9994358792919375567, 0.99892817065468131332, 0.99816660769879694826, 0.99702426326497040066, 0.99531074661423057925, 0.99274047163812084715, 0.98888505917395630451, 0.98310194047770937953, 0.97442726243333910308, 0.96141524536678357737, 0.94189721976695039984, 0.91262018136720068906, 0.86870462376757595635, 0.8028312873681389128, 0.70402128276898334747, 0.55580627587024999947, 0.33348376552215003299, 0, 0, 0.00022564828322499611425, 0.00056412070806249024497, 0.001071829345318731563, 0.0018333923012030933775, 0.0029757367350296362075, 0.0046892533857694502358, 0.0072595283618791719288, 0.011114940826043754468, 0.01689805952229062741, 0.025572737566660935088, 0.038584754633216401809, 0.058102780233049600156, 0.087379818632799394207, 0.13129537623242407141, 0.19716871263186111496, 0.29597871723101670804, 0.44419372412975000053, 0.66651623447785002252, 1, ]).reshape((20, 2, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=None +intercept=TRUE +Boundary.knots=None +knots=np.array([100, ]) +output=np.array([1, 0.994949494949495028, 0.98737373737373745897, 0.97601010101010110542, 0.9589646464646465196, 0.93339646464646475188, 0.89504419191919204479, 0.83751578282828287314, 0.75122316919191922668, 0.62178424873737381251, 0.42762586805555558023, 0.13638829703282828731, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0050505050505050509344, 0.01262626262626262777, 0.023989898989898991721, 0.041035353535353535914, 0.066603535353535359143, 0.10495580808080809398, 0.16248421717171718237, 0.24877683080808082883, 0.37821575126262629851, 0.5723741319444445308, 0.86361170296717182371, 0.98594774828339049044, 0.95530148510216805757, 0.90933209033033446378, 0.84037799817258396207, 0.7369468599359582095, 0.58180015258101969167, 0.3490800915486118039, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.014052251716609454046, 0.044698514897831886916, 0.090667909669665536221, 0.15962200182741601018, 0.26305314006404173499, 0.41819984741898030833, 0.65091990845138814059, 1, ]).reshape((20, 3, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=None +intercept=TRUE +Boundary.knots=None +knots=np.array([1000, ]) +output=np.array([1, 0.99949949949949945527, 0.99874874874874874919, 0.99762262262262257906, 0.99593343343343343488, 0.9933996496496496631, 0.98959897397397400542, 0.98389796046046040789, 0.97534644019019023364, 0.96251915978478475022, 0.94327823917667663611, 0.91441685826451446495, 0.87112478689627126371, 0.80618667984390635084, 0.70877951926535909255, 0.5626687783975381496, 0.34350266709580673519, 0.014753500143209615295, 0, 0, 0, 0.00050050050050050049616, 0.0012512512512512512404, 0.0023773773773773775736, 0.0040665665665665668566, 0.0066003503503503499136, 0.0104010260260260258, 0.016102039539539540064, 0.02465355980980980799, 0.037480840215215215083, 0.056721760823323322254, 0.08558314173548547954, 0.12887521310372873629, 0.19381332015609359365, 0.29122048073464090745, 0.4373312216024618504, 0.6564973329041932093, 0.98524649985679035868, 0.60726740066762052717, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.39273259933237941732, 1, ]).reshape((20, 3, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=None +intercept=TRUE +Boundary.knots=None +knots=np.array([10, 100, 1000, ]) +output=np.array([1, 0.94444444444444441977, 0.86111111111111104943, 0.73611111111111104943, 0.54861111111111104943, 0.26736111111111110494, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.055555555555555552472, 0.13888888888888889506, 0.26388888888888889506, 0.45138888888888883955, 0.73263888888888883955, 0.98454861111111113825, 0.92126736111111118266, 0.82634548611111113825, 0.68396267361111118266, 0.47038845486111113825, 0.15002712673611112715, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.015451388888888889506, 0.07873263888888888673, 0.17365451388888888951, 0.31603732638888892836, 0.52961154513888886175, 0.84997287326388892836, 0.96694851345486110272, 0.89486721462673612937, 0.78674526638454855831, 0.62456234402126731275, 0.38128796047634549993, 0.016376385158962673133, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.033051486545138890338, 0.10513278537326388451, 0.21325473361545138618, 0.37543765597873263173, 0.61871203952365450007, 0.98362361484103733034, 0.60726740066762052717, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.39273259933237941732, 1, ]).reshape((20, 5, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=3 +intercept=TRUE +Boundary.knots=np.array([0, 3000, ]) +knots=None +output=np.array([0.97919016410100090386, 0.9687852461515014113, 0.95317786922725200593, 0.92976680384087795339, 0.89465020576131693009, 0.84197530864197533962, 0.76296296296296306494, 0.64444444444444448639, 0.46666666666666667407, 0.2000000000000000111, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.020809835898999137771, 0.031214753848498706656, 0.046822130772748063454, 0.070233196159122088242, 0.1053497942386831393, 0.15802469135802471589, 0.23703703703703704608, 0.35555555555555556912, 0.53333333333333332593, 0.80000000000000004441, 0.99674423566950098863, 0.98697694267800384349, 0.9723260031907582368, 0.95034959395988971576, 0.9173849801135870452, 0.86793805934413292835, 0.7937676781899518641, 0.68251210645868021221, 0.51562874886177267886, 0.26530371246641143435, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0032557643304990334897, 0.013023057321996133959, 0.027673996809241787481, 0.049650406040110263428, 0.082615019886412982553, 0.13206194065586704389, 0.20623232181004816366, 0.3174878935413198433, 0.48437125113822732114, 0.73469628753358862117, ]).reshape((20, 3, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=5 +intercept=TRUE +Boundary.knots=np.array([0, 3000, ]) +knots=None +output=np.array([0.85634118967452310667, 0.78451178451178460449, 0.67676767676767679571, 0.51515151515151524908, 0.2727272727272727626, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.14365881032547700435, 0.21548821548821550653, 0.3232323232323232598, 0.48484848484848486194, 0.72727272727272729291, 0.9846005774783446185, 0.89220404234841199642, 0.7536092396535130078, 0.54571703561116458037, 0.23387872954764196698, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.015399422521655438748, 0.10779595765158807297, 0.24639076034648701996, 0.45428296438883541963, 0.76612127045235811629, 0.96572040707016604255, 0.86288162828066417021, 0.7086234600964114172, 0.47723620782003217666, 0.13015532940546331586, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.034279592929833957449, 0.13711837171933582979, 0.29137653990358863831, 0.52276379217996793436, 0.86984467059453673965, 0.9590229415870602514, 0.8770688247611807542, 0.7541376495223615084, 0.56974088666413258419, 0.29314574237678914237, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.040977058412939762477, 0.12293117523881928743, 0.24586235047763857486, 0.43025911333586747132, 0.70685425762321085763, ]).reshape((20, 5, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=12 +intercept=TRUE +Boundary.knots=np.array([0, 3000, ]) +knots=None +output=np.array([0.51111111111111118266, 0.2666666666666668295, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.48888888888888881734, 0.7333333333333331705, 0.90243902439024414885, 0.36585365853658557977, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.097560975609755906657, 0.63414634146341442023, 0.77777777777777779011, 0.16666666666666651864, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.22222222222222218213, 0.83333333333333348136, 0.625, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.37499999999999994449, 0.96992481203007530066, 0.47368421052631592971, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.030075187969924695869, 0.52631578947368407029, 0.86440677966101697738, 0.30508474576271171763, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.13559322033898302262, 0.69491525423728828237, 0.72815533980582491935, 0.087378640776698143777, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.27184466019417513616, 0.91262135922330189786, 0.57446808510638269762, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.42553191489361730238, 0.9375, 0.4218750000000004996, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.062499999999999958367, 0.57812499999999944489, 0.82300884955752262595, 0.23893805309734547637, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.17699115044247745732, 0.76106194690265460689, 0.80946623645948467818, 0.41649034915717175753, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.19053376354051526631, 0.58350965084282824247, ]).reshape((20, 12, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=None +intercept=TRUE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([]) +output=np.array([0.99966666666666659236, 0.99949999999999994404, 0.99924999999999997158, 0.99887499999999995737, 0.99831249999999993605, 0.9974687500000000151, 0.99620312499999996714, 0.99430468750000000622, 0.99145703124999995381, 0.98718554687499993072, 0.98077832031250000711, 0.97116748046875001066, 0.95675122070312501599, 0.93512683105468752398, 0.90269024658203123046, 0.85403536987304684569, 0.78105305480957032405, 0.67157958221435543056, 0.50736937332153320135, 0.26105405998229980202, 0.0003333333333333333222, 0.00050000000000000001041, 0.00075000000000000001561, 0.001124999999999999915, 0.0016874999999999999809, 0.0025312500000000000798, 0.0037968749999999999029, 0.0056953124999999998543, 0.0085429687499999993477, 0.012814453124999999889, 0.019221679687499999833, 0.02883251953124999975, 0.043248779296874997891, 0.064873168945312503775, 0.097309753417968741784, 0.14596463012695312655, 0.21894694519042967595, 0.32842041778564451393, 0.49263062667846679865, 0.73894594001770019798, ]).reshape((20, 2, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=None +intercept=TRUE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([100, ]) +output=np.array([0.98999999999999999112, 0.98499999999999998668, 0.97750000000000003553, 0.96625000000000005329, 0.94937499999999996891, 0.92406250000000000888, 0.88609375000000001332, 0.82914062499999996447, 0.74371093750000005773, 0.61556640625000003109, 0.42334960937499999112, 0.13502441406250001443, 0, 0, 0, 0, 0, 0, 0, 0, 0.010000000000000000208, 0.014999999999999999445, 0.022499999999999999167, 0.03375000000000000222, 0.050625000000000003331, 0.075937500000000004996, 0.11390625000000000056, 0.17085937500000000777, 0.25628906249999999778, 0.38443359375000002442, 0.57665039062500000888, 0.86497558593750001332, 0.98974264210668094766, 0.96737258384967661495, 0.93381749646417022692, 0.88348486538591053385, 0.80798591876852099425, 0.69473749884243662933, 0.52486486895331019298, 0.27005592411962048294, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.010257357893318963873, 0.032627416150323274024, 0.066182503535829731445, 0.11651513461408942451, 0.192014081231478978, 0.30526250115756325965, 0.47513513104668975151, 0.72994407588037946155, ]).reshape((20, 3, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=None +intercept=TRUE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([1000, ]) +output=np.array([0.99899999999999999911, 0.99850000000000005418, 0.99775000000000002576, 0.99662499999999998312, 0.9949375000000000302, 0.9924062500000000453, 0.98860937500000001243, 0.98291406250000001865, 0.97437109374999997247, 0.96155664062500001421, 0.94233496093750002132, 0.91350244140625003197, 0.87025366210937504796, 0.80538049316406257194, 0.7080707397460938024, 0.56210610961914064809, 0.34315916442871097214, 0.014738746643066406167, 0, 0, 0.0010000000000000000208, 0.0015000000000000000312, 0.0022500000000000002637, 0.0033749999999999999618, 0.0050625000000000001596, 0.0075937499999999998057, 0.011390624999999999709, 0.017085937499999998695, 0.025628906249999999778, 0.038443359374999999667, 0.0576650390624999995, 0.086497558593749995781, 0.12974633789062500755, 0.19461950683593751132, 0.29192926025390625311, 0.43789389038085940742, 0.65684083557128902786, 0.9852612533569335973, 0.76105405998229980202, 0.39158108997344970303, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.23894594001770019798, 0.60841891002655035248, ]).reshape((20, 3, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=None +intercept=TRUE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([10, 100, 1000, ]) +output=np.array([0.9000000000000000222, 0.85000000000000008882, 0.7750000000000000222, 0.66250000000000008882, 0.4937500000000000222, 0.24062500000000000555, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.10000000000000000555, 0.1500000000000000222, 0.22500000000000000555, 0.3375000000000000222, 0.5062499999999999778, 0.7593750000000000222, 0.98454861111111113825, 0.92126736111111118266, 0.82634548611111113825, 0.68396267361111118266, 0.47038845486111113825, 0.15002712673611112715, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.015451388888888889506, 0.07873263888888888673, 0.17365451388888888951, 0.31603732638888892836, 0.52961154513888886175, 0.84997287326388892836, 0.96694851345486110272, 0.89486721462673612937, 0.78674526638454855831, 0.62456234402126731275, 0.38128796047634549993, 0.016376385158962673133, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.033051486545138890338, 0.10513278537326388451, 0.21325473361545138618, 0.37543765597873263173, 0.61871203952365450007, 0.98362361484103733034, 0.76105405998229980202, 0.39158108997344970303, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.23894594001770019798, 0.60841891002655035248, ]).reshape((20, 5, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=3 +intercept=FALSE +Boundary.knots=None +knots=None +output=np.array([0, 0.040686586141131603211, 0.10171646535282900803, 0.19326128417037510832, 0.33057851239669427956, 0.53655435473617296704, 0.84551811824539113704, 0.97622585438335818253, 0.92273402674591387118, 0.84249628528974740416, 0.72213967310549775913, 0.54160475482912329159, 0.27080237741456153477, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.023774145616641918083, 0.077265973254086212085, 0.1575037147102526236, 0.27786032689450229638, 0.45839524517087676392, 0.72919762258543852074, 0.98941973879980160689, 0.9418085633989089489, 0.87039180029756990642, 0.76326665564556128718, 0.60257893866754841383, 0.3615473632005290483, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.010580261200198394847, 0.058191436601091106606, 0.12960819970243014909, 0.23673334435443876833, 0.39742106133245164168, 0.63845263679947106272, 1, ]).reshape((20, 3, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=5 +intercept=FALSE +Boundary.knots=None +knots=None +output=np.array([0, 0.1342281879194630323, 0.33557046979865756686, 0.63758389261744941034, 0.98069963811821481148, 0.83594692400482528694, 0.61881785283474100012, 0.2931242460796145699, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.019300361881785188523, 0.16405307599517471306, 0.38118214716525899988, 0.70687575392038548561, 0.9581151832460734763, 0.80104712041884851281, 0.56544502617801106759, 0.21204188481675489975, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.041884816753926495947, 0.19895287958115145943, 0.4345549738219888769, 0.78795811518324510025, 0.93133047210300479168, 0.75965665236051571618, 0.50214592274678215844, 0.11587982832618169693, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.068669527896995374849, 0.2403433476394844226, 0.49785407725321800809, 0.88412017167381840022, 0.89905362776025266047, 0.70977917981072580211, 0.42586750788643545906, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.10094637223974732565, 0.29022082018927419789, 0.57413249211356454094, 1, ]).reshape((20, 5, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=12 +intercept=FALSE +Boundary.knots=None +knots=None +output=np.array([0, 0.53333333333333343695, 0.81818181818181801024, 0.16363636363636296922, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.18181818181818207303, 0.83636363636363708629, 0.57446808510638280865, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.42553191489361724686, 0.9000000000000000222, 0.29999999999999982236, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.10000000000000003331, 0.70000000000000017764, 0.67346938775510178932, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.32653061224489815517, 0.96923076923076900702, 0.41538461538461529665, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.030769230769230916656, 0.58461538461538464784, 0.7714285714285711304, 0.085714285714284479956, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.22857142857142889736, 0.91428571428571558943, 0.5217391304347820391, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.47826086956521790539, 0.86086956521739110837, 0.23478260869565212299, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.13913043478260883612, 0.76521739130434784926, 0.62499999999999966693, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.37500000000000027756, 0.93599999999999949907, 0.35999999999999854339, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.064000000000000500933, 0.64000000000000145661, 0.7199999999999991962, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.2800000000000008038, 1, ]).reshape((20, 12, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=None +intercept=FALSE +Boundary.knots=None +knots=np.array([]) +output=np.array([0, 0.00022564828322499611425, 0.00056412070806249024497, 0.001071829345318731563, 0.0018333923012030933775, 0.0029757367350296362075, 0.0046892533857694502358, 0.0072595283618791719288, 0.011114940826043754468, 0.01689805952229062741, 0.025572737566660935088, 0.038584754633216401809, 0.058102780233049600156, 0.087379818632799394207, 0.13129537623242407141, 0.19716871263186111496, 0.29597871723101670804, 0.44419372412975000053, 0.66651623447785002252, 1, ]).reshape((20, 1, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=None +intercept=FALSE +Boundary.knots=None +knots=np.array([100, ]) +output=np.array([0, 0.0050505050505050509344, 0.01262626262626262777, 0.023989898989898991721, 0.041035353535353535914, 0.066603535353535359143, 0.10495580808080809398, 0.16248421717171718237, 0.24877683080808082883, 0.37821575126262629851, 0.5723741319444445308, 0.86361170296717182371, 0.98594774828339049044, 0.95530148510216805757, 0.90933209033033446378, 0.84037799817258396207, 0.7369468599359582095, 0.58180015258101969167, 0.3490800915486118039, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.014052251716609454046, 0.044698514897831886916, 0.090667909669665536221, 0.15962200182741601018, 0.26305314006404173499, 0.41819984741898030833, 0.65091990845138814059, 1, ]).reshape((20, 2, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=None +intercept=FALSE +Boundary.knots=None +knots=np.array([1000, ]) +output=np.array([0, 0.00050050050050050049616, 0.0012512512512512512404, 0.0023773773773773775736, 0.0040665665665665668566, 0.0066003503503503499136, 0.0104010260260260258, 0.016102039539539540064, 0.02465355980980980799, 0.037480840215215215083, 0.056721760823323322254, 0.08558314173548547954, 0.12887521310372873629, 0.19381332015609359365, 0.29122048073464090745, 0.4373312216024618504, 0.6564973329041932093, 0.98524649985679035868, 0.60726740066762052717, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.39273259933237941732, 1, ]).reshape((20, 2, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=None +intercept=FALSE +Boundary.knots=None +knots=np.array([10, 100, 1000, ]) +output=np.array([0, 0.055555555555555552472, 0.13888888888888889506, 0.26388888888888889506, 0.45138888888888883955, 0.73263888888888883955, 0.98454861111111113825, 0.92126736111111118266, 0.82634548611111113825, 0.68396267361111118266, 0.47038845486111113825, 0.15002712673611112715, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.015451388888888889506, 0.07873263888888888673, 0.17365451388888888951, 0.31603732638888892836, 0.52961154513888886175, 0.84997287326388892836, 0.96694851345486110272, 0.89486721462673612937, 0.78674526638454855831, 0.62456234402126731275, 0.38128796047634549993, 0.016376385158962673133, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.033051486545138890338, 0.10513278537326388451, 0.21325473361545138618, 0.37543765597873263173, 0.61871203952365450007, 0.98362361484103733034, 0.60726740066762052717, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.39273259933237941732, 1, ]).reshape((20, 4, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=3 +intercept=FALSE +Boundary.knots=np.array([0, 3000, ]) +knots=None +output=np.array([0.075249853027630819735, 0.1128747795414462296, 0.16931216931216935828, 0.25396825396825400967, 0.38095238095238104226, 0.57142857142857150787, 0.85714285714285731732, 0.97622585438335818253, 0.92273402674591387118, 0.84249628528974740416, 0.72213967310549775913, 0.54160475482912329159, 0.27080237741456153477, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.023774145616641918083, 0.077265973254086212085, 0.1575037147102526236, 0.27786032689450229638, 0.45839524517087676392, 0.72919762258543852074, 0.99235077739698696053, 0.95792927568342844946, 0.90629702311309068286, 0.82884864425758408846, 0.71267607597432414135, 0.53841722354943410966, 0.27702894491209917316, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0076492226030130125794, 0.042070724316571522783, 0.093702976886909289389, 0.1711513557424159393, 0.28732392402567591416, 0.46158277645056589034, 0.72297105508790082684, ]).reshape((20, 3, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=5 +intercept=FALSE +Boundary.knots=np.array([0, 3000, ]) +knots=None +output=np.array([0.21164021164021157295, 0.31746031746031733167, 0.47619047619047605302, 0.71428571428571407953, 0.98069963811821481148, 0.83594692400482528694, 0.61881785283474100012, 0.2931242460796145699, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.019300361881785188523, 0.16405307599517471306, 0.38118214716525899988, 0.70687575392038548561, 0.9581151832460734763, 0.80104712041884851281, 0.56544502617801106759, 0.21204188481675489975, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.041884816753926495947, 0.19895287958115145943, 0.4345549738219888769, 0.78795811518324510025, 0.93133047210300479168, 0.75965665236051571618, 0.50214592274678215844, 0.11587982832618169693, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.068669527896995374849, 0.2403433476394844226, 0.49785407725321800809, 0.88412017167381840022, 0.93044657380826634174, 0.80003389969876526067, 0.60441488853451352803, 0.31098637178813609561, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.069553426191733672135, 0.19996610030123476709, 0.39558511146548641646, 0.68901362821186384888, ]).reshape((20, 5, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=12 +intercept=FALSE +Boundary.knots=np.array([0, 3000, ]) +knots=None +output=np.array([0.51612903225806461283, 0.77419354838709697475, 0.81818181818181801024, 0.16363636363636296922, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.18181818181818207303, 0.83636363636363708629, 0.57446808510638280865, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.42553191489361724686, 0.9000000000000000222, 0.29999999999999982236, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.10000000000000003331, 0.70000000000000017764, 0.67346938775510178932, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.32653061224489815517, 0.96923076923076900702, 0.41538461538461529665, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.030769230769230916656, 0.58461538461538464784, 0.7714285714285711304, 0.085714285714284479956, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.22857142857142889736, 0.91428571428571558943, 0.5217391304347820391, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.47826086956521790539, 0.86086956521739110837, 0.23478260869565212299, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.13913043478260883612, 0.76521739130434784926, 0.62499999999999966693, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.37500000000000027756, 0.93599999999999949907, 0.35999999999999854339, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.064000000000000500933, 0.64000000000000145661, 0.84118724544512846197, 0.43281159087546033915, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.15881275455487159354, 0.56718840912453971637, ]).reshape((20, 12, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=None +intercept=FALSE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([]) +output=np.array([0.0003333333333333333222, 0.00050000000000000001041, 0.00075000000000000001561, 0.001124999999999999915, 0.0016874999999999999809, 0.0025312500000000000798, 0.0037968749999999999029, 0.0056953124999999998543, 0.0085429687499999993477, 0.012814453124999999889, 0.019221679687499999833, 0.02883251953124999975, 0.043248779296874997891, 0.064873168945312503775, 0.097309753417968741784, 0.14596463012695312655, 0.21894694519042967595, 0.32842041778564451393, 0.49263062667846679865, 0.73894594001770019798, ]).reshape((20, 1, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=None +intercept=FALSE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([100, ]) +output=np.array([0.010000000000000000208, 0.014999999999999999445, 0.022499999999999999167, 0.03375000000000000222, 0.050625000000000003331, 0.075937500000000004996, 0.11390625000000000056, 0.17085937500000000777, 0.25628906249999999778, 0.38443359375000002442, 0.57665039062500000888, 0.86497558593750001332, 0.98974264210668094766, 0.96737258384967661495, 0.93381749646417022692, 0.88348486538591053385, 0.80798591876852099425, 0.69473749884243662933, 0.52486486895331019298, 0.27005592411962048294, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.010257357893318963873, 0.032627416150323274024, 0.066182503535829731445, 0.11651513461408942451, 0.192014081231478978, 0.30526250115756325965, 0.47513513104668975151, 0.72994407588037946155, ]).reshape((20, 2, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=None +intercept=FALSE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([1000, ]) +output=np.array([0.0010000000000000000208, 0.0015000000000000000312, 0.0022500000000000002637, 0.0033749999999999999618, 0.0050625000000000001596, 0.0075937499999999998057, 0.011390624999999999709, 0.017085937499999998695, 0.025628906249999999778, 0.038443359374999999667, 0.0576650390624999995, 0.086497558593749995781, 0.12974633789062500755, 0.19461950683593751132, 0.29192926025390625311, 0.43789389038085940742, 0.65684083557128902786, 0.9852612533569335973, 0.76105405998229980202, 0.39158108997344970303, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.23894594001770019798, 0.60841891002655035248, ]).reshape((20, 2, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=None +intercept=FALSE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([10, 100, 1000, ]) +output=np.array([0.10000000000000000555, 0.1500000000000000222, 0.22500000000000000555, 0.3375000000000000222, 0.5062499999999999778, 0.7593750000000000222, 0.98454861111111113825, 0.92126736111111118266, 0.82634548611111113825, 0.68396267361111118266, 0.47038845486111113825, 0.15002712673611112715, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.015451388888888889506, 0.07873263888888888673, 0.17365451388888888951, 0.31603732638888892836, 0.52961154513888886175, 0.84997287326388892836, 0.96694851345486110272, 0.89486721462673612937, 0.78674526638454855831, 0.62456234402126731275, 0.38128796047634549993, 0.016376385158962673133, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.033051486545138890338, 0.10513278537326388451, 0.21325473361545138618, 0.37543765597873263173, 0.61871203952365450007, 0.98362361484103733034, 0.76105405998229980202, 0.39158108997344970303, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.23894594001770019798, 0.60841891002655035248, ]).reshape((20, 4, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=5 +intercept=TRUE +Boundary.knots=None +knots=None +output=np.array([1, 0.96845940607276881362, 0.92240303675860391142, 0.85609306993676004272, 0.76270864919645953162, 0.63576547531534310931, 0.47305239057526615731, 0.28507250058887945166, 0.10824783418564158655, 0.0085209665393945269174, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.031533426700978403612, 0.077552412011353655252, 0.14374742102560256196, 0.23683044051100490823, 0.36304322063581223601, 0.52407464745263665495, 0.70834870097260460575, 0.8774087197542927985, 0.96206652916722557034, 0.94530079752693674244, 0.90793500327984399956, 0.85375309463923021447, 0.77659028109030259213, 0.66978920735324132263, 0.52868210857343611586, 0.35651607003382906891, 0.175425242216674937, 0.037891852318801787225, 0, 0, 7.1666852050360488124e-06, 4.4542776169713856592e-05, 0.00015945105252372870864, 0.00046062008693220732759, 0.0011900631879368495612, 0.002868106285078954841, 0.0065607821717948554968, 0.014278782285967288324, 0.029185282443915855355, 0.053915675965905400513, 0.089616579303442189808, 0.13947317683937743293, 0.20621746127156848072, 0.28916251068209719577, 0.37804948423631462573, 0.44191546230800060613, 0.4167872147195200716, 0.22637517283088642861, 0, 0, 5.4104786148500394417e-10, 8.4538728357031864466e-09, 5.7985113780088147304e-08, 2.9020560343812349123e-07, 1.2408609078339073411e-06, 4.8556870182056249453e-06, 1.8016266721020254751e-05, 6.4663774098311141273e-05, 0.00022722184946421446292, 0.0007834394838982231728, 0.0024428479280998137424, 0.0067202853620942429314, 0.016883622849287124174, 0.039626432891546964354, 0.087460636122680179838, 0.179450426719582945, 0.32709043481102628714, 0.44917563313558994675, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8.7023259593866311309e-08, 5.5694886140074439238e-06, 5.3443159298083143627e-05, 0.00030863478884180254799, 0.001421849073114332283, 0.0058077710675691540318, 0.022118040938587192612, 0.080697108252778662618, 0.28655734171472191374, 1, ]).reshape((20, 5, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=12 +intercept=TRUE +Boundary.knots=None +knots=None +output=np.array([1, 0.25770097670924113631, 0.00075131480090157780165, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.64290814257309680801, 0.55191727963673464785, 0.16384783952351522629, 0.0025601224925549254108, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.097791408043809202599, 0.4223396450334132024, 0.68523715148898289851, 0.53751029745031897455, 0.17971670556949506659, 0.0066561742803516550301, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0015994726738528394164, 0.024991760528950617698, 0.14994115610379393777, 0.44102623014868380658, 0.69378612010084461659, 0.57911832988268308053, 0.21512754628498662046, 0.013768162962239142988, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00097385288370810028057, 0.018903349908442362848, 0.12592791140580222864, 0.39992732893636862013, 0.67912381051853998315, 0.61416869876328705757, 0.2513505357806551932, 0.023605422218318485722, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00056926292385829722204, 0.014298166900596829057, 0.10543398177170558438, 0.36126140155236396989, 0.66048745076429016265, 0.64290852334776726895, 0.28801011480255123143, 0.036001264350318869234, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00031466142476788003723, 0.010801736722109872915, 0.088001307706519454888, 0.32534582615335716493, 0.63869155767138829916, 0.66560703209160065885, 0.32480624491998255632, 0.050709395542809954094, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00016070574853527342459, 0.0081402282805572035579, 0.073225347399450108066, 0.29228033065100789134, 0.61441387376474365656, 0.68269380491744569017, 0.36150149884261828515, 0.067452174711159121334, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7.2980126610408391891e-05, 0.006111372907072773128, 0.06075244688059205922, 0.26203239546958334572, 0.58821589703491272694, 0.69467005250274826977, 0.39790980589205254825, 0.08594851807268334698, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2.7434434681658694525e-05, 0.004564404070160951038, 0.05026345997459336773, 0.22896647107718723357, 0.49280704180866574671, 0.39171522957479332216, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.9144147875867501007e-05, 0.0089113017089054759323, 0.10925932166656721067, 0.44968558969337457665, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2.383063271446895644e-05, 0.072650662659148546041, 1, ]).reshape((20, 12, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=None +intercept=TRUE +Boundary.knots=None +knots=np.array([]) +output=np.array([1, 0.9993232078902789528, 0.99830859239281100059, 0.99678795718714330309, 0.99450990091574942298, 0.99109932847208381812, 0.98599810402219045802, 0.97837913458786918142, 0.96702443008955374371, 0.95015762953345339614, 0.92522695834704149487, 0.88865464163271656872, 0.83562330741598667139, 0.7600990769655836532, 0.65556596659430688145, 0.51745533329454529436, 0.34894530919915062173, 0.17170001728344266856, 0.037087203733223626789, 0, 0, 0.00067663938125675493745, 0.0016904532697119580269, 0.0032085988210942785123, 0.0054800274275235618532, 0.0088741592009194299184, 0.013936134910759763808, 0.021463528321228261819, 0.032607690503775640933, 0.048995387512752772152, 0.072844594278869884141, 0.10699389717286836299, 0.15464119556617272888, 0.21832955541935578081, 0.29724527028257624606, 0.38124822804791375086, 0.44010197217760271826, 0.41166179703994132399, 0.22237265440082615298, 0, 0, 1.5271697506625337419e-07, 9.5415795571804482003e-07, 3.4427604254568415078e-06, 1.0065494095385778498e-05, 2.6485976820866183047e-05, 6.5657954600734260006e-05, 0.00015695450829847096968, 0.00036650624565625982386, 0.00084215780726247437687, 0.0019117237011529813161, 0.0042940168564642817658, 0.0095393459205458924072, 0.020904202366139650049, 0.044925430954654600735, 0.093631406124953353576, 0.18502397635429304601, 0.32899518168053926148, 0.4444443765651269751, 0, 0, 1.1489366970270387462e-11, 1.7952135891047479178e-10, 1.2313370007669466487e-09, 6.1626316488486427104e-09, 2.6350175916113057325e-08, 1.0311244903883365944e-07, 3.825826041044410135e-07, 1.3731610143675871737e-06, 4.8251465313854754769e-06, 1.6723672935651049261e-05, 5.7444337950753896285e-05, 0.0001961510972947611009, 0.00066716524892103249485, 0.0022633321684622557078, 0.0076650325325876428328, 0.025928742268953787475, 0.087643003996076676576, 0.29609576530082332146, 1, ]).reshape((20, 4, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=None +intercept=TRUE +Boundary.knots=None +knots=np.array([100, ]) +output=np.array([1, 0.98492487882601165161, 0.96259746673448087773, 0.92974304223814019377, 0.88187654067159670923, 0.81320203136184721071, 0.71702357673990413378, 0.58746094552406258327, 0.42394246616286163087, 0.24039152271518871018, 0.078197326716827678106, 0.0025370634003338671768, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.015071708273510188089, 0.037381259008501491192, 0.070180462942842899987, 0.11790098280764790828, 0.18621717511273339074, 0.28155389351842002865, 0.40920060085307918829, 0.56848075164647782209, 0.74296035718046105067, 0.88664340493727211712, 0.92755941161894106539, 0.87470363121335126255, 0.79564729322794469635, 0.68622539174158070363, 0.5416556180357140482, 0.36526473871966497198, 0.17973006169687555378, 0.038821693326525116841, 0, 0, 3.4126433211387775282e-06, 2.1270238934697356366e-05, 7.6467258985853174243e-05, 0.00022233858750032365649, 0.00058020375050652503793, 0.0014202218581983020763, 0.003329890582419185209, 0.0075460478259266952628, 0.0165401227086783148, 0.03478495575013232366, 0.06861779430820802439, 0.12096540781627201921, 0.191329633412285538, 0.27905349779077742722, 0.37374631578125083742, 0.44360195032526716918, 0.42250875072786614473, 0.23095694223535656597, 0, 0, 2.5715731172923263021e-10, 4.0180829957692598212e-09, 2.7560031267981358852e-08, 1.3793325533914163604e-07, 5.8977491272702679876e-07, 2.3078834777630869564e-06, 8.5630404390810414166e-06, 3.0734364733920997454e-05, 0.00010799739567214114531, 0.00037431259576781883034, 0.0012857306725170922646, 0.0043281861315545133023, 0.012933767638577380737, 0.033975759516814023342, 0.080531027913042049771, 0.17293083479161802662, 0.32462175106248042367, 0.45442872954598834134, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2.7748388221855075202e-06, 8.9305721192384863918e-05, 0.00074535095082784331034, 0.0040670382699930507364, 0.018202476163449766294, 0.07313943651277800273, 0.27579263489213001748, 1, ]).reshape((20, 5, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=None +intercept=TRUE +Boundary.knots=None +knots=np.array([1000, ]) +output=np.array([1, 0.9984992498753757495, 0.99625094117633150592, 0.99288481020069696559, 0.98784984394255781481, 0.98032935528140474624, 0.96912034075214636974, 0.95246753354617186282, 0.92784773021983435459, 0.89171926591812056273, 0.83930429776320658597, 0.76459714573223325207, 0.66106035705829924165, 0.52397052211349615103, 0.35606843795797349372, 0.17813877131971986301, 0.040531281972235988498, 3.2113319168708665608e-06, 0, 0, 0, 0.0015004113953972979083, 0.0037469425348356701772, 0.0071075541598605747329, 0.012127833209738946019, 0.019611910086607075437, 0.030734076107229148234, 0.04718451762439003494, 0.071340002591639736784, 0.10641511473995685089, 0.15646348082190494888, 0.22590626848315542574, 0.31787571113275914225, 0.42998547021895328069, 0.54537912943555955092, 0.61788880868397033641, 0.56161589860385985329, 0.31265651834613988891, 0.067535071081621433908, 0, 0, 3.3870374289331948997e-07, 2.1158906445184196164e-06, 7.6329082682329570748e-06, 2.2309178641915861703e-05, 5.8676185825556269023e-05, 0.00014535443145101360611, 0.00034710023984489360048, 0.00080922144066932952776, 0.0018549168973065219106, 0.0041951273738663188637, 0.0093691710332807192491, 0.020628857715017115404, 0.044564197866965707395, 0.093532235391030102423, 0.18697094954821646962, 0.34034142027880176506, 0.49294319032437394767, 0.3494912754584255099, 0, 0, 2.5484057919113140944e-11, 3.9818840498614283815e-10, 2.7311742697999542126e-09, 1.3669061339914938246e-08, 5.844616252249814789e-08, 2.2870917347201761224e-07, 8.4858959306208503663e-07, 3.0457478565146930827e-06, 1.0702444616158128632e-05, 3.7094041022036097191e-05, 0.00012741475133052262828, 0.00043507409392457165433, 0.0014798098005849495782, 0.0050201972154368997708, 0.017001470448093195659, 0.057511399145102344577, 0.1943970799975693331, 0.52239901147403788872, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.060574641985915035625, 1, ]).reshape((20, 5, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=None +intercept=TRUE +Boundary.knots=None +knots=np.array([10, 100, 1000, ]) +output=np.array([1, 0.84242112482853226396, 0.63852451989026048906, 0.39886884859396426473, 0.16511776352451987271, 0.019111497248478225702, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.1567541293972270211, 0.35648024152864221659, 0.58396161300859317222, 0.78843465486178421209, 0.87349958752470602263, 0.78872593441389438063, 0.64620704007646878608, 0.46633671277914778841, 0.26443067498670752569, 0.086017059388510438978, 0.0027907697403672538511, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00082460534200152601353, 0.0049930443273597038822, 0.017154488011057174995, 0.046372256997114502663, 0.10706684228609344989, 0.21001709629214043717, 0.349560411044427366, 0.52164005645501687614, 0.7052885939808604121, 0.84461817796425076033, 0.85332055763972392004, 0.74044769630139117833, 0.58689461845094414993, 0.39882902037092649028, 0.19953161831184262898, 0.045398720470901786361, 3.5969836861605402089e-06, 0, 0, 0, 1.4043223919767127475e-07, 2.1942537374636142735e-06, 1.5050386385262928333e-05, 7.5324616581368114944e-05, 0.0003220729407222703883, 0.001256955617244540557, 0.0042307394405898370374, 0.012003815755055342179, 0.030163701749655900952, 0.068814016157702301291, 0.14161203135855129909, 0.25097331049689530769, 0.38604331096967514636, 0.52843933204950088722, 0.62702364005086641541, 0.58518234575989880319, 0.32861311390225123041, 0.070981847410833104339, 0, 0, 0, 0, 0, 0, 0, 1.3676720629513371727e-08, 1.8094385139768081762e-06, 1.9415010780026244647e-05, 0.00011702928277625300924, 0.00055074648953661010323, 0.0022766412613576141911, 0.0085724666641985424603, 0.026852019770306118779, 0.070978550821878275134, 0.16387889672004127273, 0.32660594492319316995, 0.49935626095003893266, 0.36224174733681202554, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6.5265375148376491226e-06, 0.00021005080907461989208, 0.0017530967576943525671, 0.0095658449172495805396, 0.042812988846006136412, 0.17202702816402348773, 0.50620176326643973042, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.060574641985915035625, 1, ]).reshape((20, 7, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=5 +intercept=TRUE +Boundary.knots=np.array([0, 3000, ]) +knots=None +output=np.array([0.93886062842918460714, 0.90924840659363448392, 0.86600789475617090396, 0.80375207763469636024, 0.71607712169296244831, 0.5968951736881422665, 0.4441302646954225497, 0.26764334705075454313, 0.1016296296296296392, 0.0080000000000000019013, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.061118708396877156896, 0.090705266259710190524, 0.13388842602098646739, 0.1960165235067286571, 0.28340857382601336578, 0.40196904868840105385, 0.55338648582541094534, 0.72701318595705810566, 0.88717054427173769326, 0.96957793066711428498, 0.95879430886579075644, 0.93088336665495841071, 0.89004087164963097134, 0.83104478735029430059, 0.74753085865141255528, 0.63305354842556382788, 0.48423310979820943789, 0.30782602005074449769, 0.13273505055352541326, 0.018080241660177655966, 2.0660861734307157164e-05, 4.6319342966912629609e-05, 0.00010365288539398855667, 0.00023130996968619285063, 0.00051400448102423420497, 0.0011347651234567903995, 0.0024798322916666664696, 0.005331933984375000421, 0.011160902197265624297, 0.022290701165771482917, 0.040764443570473873901, 0.067755947834115426431, 0.10621083986053703185, 0.15942942065206799906, 0.22958192424619683347, 0.31428339352859285816, 0.39934193575081916583, 0.44659448090264364239, 0.38447678365411958046, 0.15324078379324712618, 2.3122039887776819585e-09, 7.8036884621246768168e-09, 2.6337448559670789633e-08, 8.888888888888889516e-08, 3.0000000000000003936e-07, 1.0125000000000002586e-06, 3.4171875000000000522e-06, 1.1533007812500000494e-05, 3.892390136718749976e-05, 0.0001313681671142578227, 0.00044121305262908775248, 0.0013584768001177710377, 0.0037270943566249025922, 0.0094033956626723494421, 0.022323349639243747489, 0.050359850764330853223, 0.10765352865786298464, 0.21357717575211032646, 0.36914715819588089785, 0.43210561538410807714, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3.451110638240695161e-08, 2.208710808474044903e-06, 2.1194133207095667231e-05, 0.00012239633496539237658, 0.00056386746314699115034, 0.0023032072815124867565, 0.0087714257931084897019, 0.032002323294501686113, 0.11364100759647420558, 0.3965733591624671095, ]).reshape((20, 5, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=12 +intercept=TRUE +Boundary.knots=np.array([0, 3000, ]) +knots=None +output=np.array([0.19405161102201490264, 0.050007289692374980172, 0.00014579384749963551142, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.62621171786550611227, 0.59601302425037649968, 0.37359381834086596852, 0.11076923076923075873, 0.0017307692307692306051, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.17410393357590786545, 0.33496919687132054033, 0.56209998680912809377, 0.6845598495992195609, 0.49785783114523274318, 0.16619304988878053075, 0.0061552981440288964676, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0056327375365711959687, 0.019010489185927782058, 0.064160401002506278756, 0.20369706674784149314, 0.48150804971555583034, 0.70730977578155906915, 0.57961920601900573935, 0.21512754628498662046, 0.013768162962239142988, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00097385288370810028057, 0.018903349908442362848, 0.12592791140580222864, 0.39992732893636862013, 0.67912381051853998315, 0.61416869876328705757, 0.2513505357806551932, 0.023605422218318485722, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00056926292385829722204, 0.014298166900596829057, 0.10543398177170558438, 0.36126140155236396989, 0.66048745076429016265, 0.64290852334776726895, 0.28801011480255123143, 0.036001264350318869234, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00031466142476788003723, 0.010801736722109872915, 0.088001307706519454888, 0.32534582615335716493, 0.63869155767138829916, 0.66560703209160065885, 0.32480624491998255632, 0.050709395542809954094, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00016070574853527342459, 0.0081402282805572035579, 0.073225347399450108066, 0.29228033065100789134, 0.61441387376474365656, 0.68269380491744569017, 0.36150149884261828515, 0.067452174711159121334, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7.2980126610408391891e-05, 0.006111372907072773128, 0.06076004701308617556, 0.2632968675132925096, 0.60214193117458769677, 0.75884556552586945877, 0.54356876952344934661, 0.23438768460872402843, 0.031926653602217504313, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.9834302187538887846e-05, 0.0032999320264517715412, 0.03634723886267338111, 0.16935876914548009253, 0.40315927025443520915, 0.49317292913076199445, 0.23502476599459576345, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9.3311201208237671141e-06, 0.004343490617491435786, 0.053266330072947364049, 0.25527517275326377932, 0.49679177449105649256, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5.6301491679855540114e-06, 0.017164213507250107582, 0.23625680591213024662, ]).reshape((20, 12, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=None +intercept=TRUE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([]) +output=np.array([0.99900033329629622791, 0.99850074987500003765, 0.9977516870781251157, 0.9966287954511718894, 0.99494603816333004875, 0.99242545546139537826, 0.98865256904256049175, 0.98301118751693283837, 0.97458941720955349908, 0.96204716698765402327, 0.94343627795644391387, 0.91597241507140558792, 0.87578413786327058421, 0.81773305675994945041, 0.73555685971681306068, 0.62291325464817093316, 0.47647663168935677769, 0.30289524241999998821, 0.13060889169932207721, 0.017790631148623885227, 0.00099933344444444439057, 0.0014985003750000000684, 0.0022466262656250001253, 0.003367410521484375148, 0.0050454284787597655781, 0.0075553552955017096171, 0.011304291651615143086, 0.016891872202619076515, 0.02519288281652980882, 0.037464410913716578166, 0.055469506915694993809, 0.081581580145842852447, 0.11876628136094780075, 0.1701874001952980997, 0.23787846467254591953, 0.31938947503806314199, 0.40070172821401484065, 0.44437167848162473227, 0.38044436785608970464, 0.1510757732538548781, 3.3322222222222224585e-07, 7.4962500000000004377e-07, 1.6862343750000001263e-06, 3.7926035156249994121e-06, 8.5285524902343742213e-06, 1.9173024810791016186e-05, 4.3084569087982178912e-05, 9.675554396295546727e-05, 0.00021707648827975990682, 0.00048631783460495621712, 0.0010871132367784521085, 0.0024220359003474063384, 0.0053686857976677918383, 0.011806522493618208658, 0.025643231250562635581, 0.054587395598501557703, 0.11232581293261123534, 0.217309662419816918, 0.36939270915445387988, 0.42763873999331791786, 3.7037037037037035514e-11, 1.2500000000000000779e-10, 4.2187500000000000366e-10, 1.4238281249999998508e-09, 4.8054199218749994447e-09, 1.6218292236328128606e-08, 5.4736736297607425773e-08, 1.8473648500442501235e-07, 6.234856368899344564e-07, 2.1042640245035291742e-06, 7.1018910826994105393e-06, 2.3968882404110509299e-05, 8.0894978113872978626e-05, 0.00027302055113432129778, 0.00092144436007833422416, 0.003109874715264377993, 0.010495827164017276431, 0.035423416678558306003, 0.11955403129013431052, 0.40349485560420322861, ]).reshape((20, 4, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=None +intercept=TRUE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([100, ]) +output=np.array([0.97029899999999991156, 0.95567162499999991354, 0.93400735937500012351, 0.9021287441406251606, 0.8556839255371094799, 0.78904911782836917311, 0.69572725948715208322, 0.57001276798105227073, 0.41135095097535856468, 0.23325165409902481883, 0.075874787916011168787, 0.0024617100802805510704, 0, 0, 0, 0, 0, 0, 0, 0, 0.029691034444444444618, 0.044305991250000002768, 0.06594240796875000532, 0.097758673769531262421, 0.1440642544409179715, 0.21038931479278566439, 0.30302618229869843214, 0.4272397443474625911, 0.58266048231123623857, 0.75392639264340943761, 0.89747740349010274308, 0.94501107412874996161, 0.90598359089303848179, 0.84593074837236126307, 0.76092088936222046502, 0.64439302204983184286, 0.49290686036830000383, 0.31333990595172406257, 0.13511264658550559137, 0.018404101188231606484, 9.9644444444444446617e-06, 2.2379999999999999178e-05, 5.0219999999999996902e-05, 0.00011253937500000000703, 0.00025167585937500001371, 0.0005610808300781249848, 0.0012449161120605468141, 0.002741945576934814565, 0.0059698621442985533997, 0.012758825336830616898, 0.02643475186140507513, 0.051808149318846051512, 0.091620856894323976505, 0.14688590543057178373, 0.21984251899359169569, 0.30818245617558825966, 0.39752224089834975462, 0.44889001546541440479, 0.38890408238266155339, 0.15565065849749706861, 1.1111111111111110654e-09, 3.7499999999999996649e-09, 1.2656249999999997938e-08, 4.2714843750000004622e-08, 1.4416259765625001146e-07, 4.8654876708984372583e-07, 1.6421020889282224026e-06, 5.5420945501327518529e-06, 1.8704569106698035598e-05, 6.3127920735105882001e-05, 0.00021305673248098232295, 0.00071906647212331535352, 0.002394473001231371169, 0.0071486127371715351211, 0.018946704087009914874, 0.045842738337222695144, 0.10249145334758576198, 0.20932413300445151805, 0.3687199031810673433, 0.43701763935524273741, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.0792114061605856464e-06, 3.473345989527011488e-05, 0.00028988755717800383316, 0.0015817834373569547059, 0.0070794453857644188549, 0.028445945578409920912, 0.10726336785076537317, 0.38892760095902845219, ]).reshape((20, 5, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=None +intercept=TRUE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([1000, ]) +output=np.array([0.99700299900000011188, 0.99550674662500016066, 0.99326517610937503644, 0.98990913343164044225, 0.9848892569724120305, 0.97739130722329725653, 0.96621588612179176714, 0.94961298739566668559, 0.92506696964451773368, 0.88904678238644452293, 0.83678890194350608045, 0.76230564732187677812, 0.65907915850713516548, 0.52240018193475146191, 0.35500130049334505111, 0.17760488924393591503, 0.040409809679633923452, 3.2017075519046728555e-06, 0, 0, 0.0029960014444444446613, 0.0044910048749999993689, 0.0067297664531250009357, 0.010079493029296874088, 0.015085171786376951053, 0.02255122235714721729, 0.033655024381153107738, 0.050097300181899548366, 0.074283671347553537068, 0.10950057690181402847, 0.15997106401940666687, 0.23050015162429349225, 0.3250574690342031281, 0.44299931223779698275, 0.57083333883520204211, 0.6679625481063525827, 0.65410023301458430911, 0.45433806106867219432, 0.19591333754898310193, 0.026685946722935827841, 9.9944444444444452216e-07, 2.2481249999999997573e-06, 5.0561718750000005462e-06, 1.1369267578125000521e-05, 2.5556824951171875081e-05, 5.7421764678955089446e-05, 0.00012892528684616086799, 0.00028915821297883983077, 0.00064748855101794003473, 0.0014463279196678473747, 0.0032187283638391594488, 0.0071222944066175568334, 0.015620687524320137074, 0.033781444174048706752, 0.071401027591217913759, 0.14510293850391842163, 0.2740024758137300509, 0.43938848718810108451, 0.4727098830096430615, 0.21327068651931446741, 1.1111111111111111947e-10, 3.750000000000000492e-10, 1.2656250000000001661e-09, 4.2714843749999999659e-09, 1.4416259765625000816e-08, 4.8654876708984385818e-08, 1.6421020889282225085e-07, 5.5420945501327514294e-07, 1.8704569106698034751e-06, 6.3127920735105875225e-06, 2.1305673248098235006e-05, 7.190664721233152451e-05, 0.00024268493434161889522, 0.00081906165340296394756, 0.0027643330802350029977, 0.0093296241457931361474, 0.031487481492051827558, 0.10627025003567493189, 0.31773412222685926132, 0.53482276673031980962, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.013642657214514538819, 0.22522060002743005125, ]).reshape((20, 5, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=None +intercept=TRUE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([10, 100, 1000, ]) +output=np.array([0.72899999999999987033, 0.61412500000000003197, 0.46548437500000000577, 0.29077539062500001865, 0.12037084960937501077, 0.013932281494140625472, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.26810999999999995946, 0.37949624999999997943, 0.52058109375000005681, 0.6792815039062500837, 0.81701452880859382066, 0.86124092926025386241, 0.77303028831905795659, 0.63334751997894722653, 0.45705661219484272628, 0.2591685045544720456, 0.084305319906679110353, 0.002735233422533945441, 0, 0, 0, 0, 0, 0, 0, 0, 0.0028890000000000000749, 0.0063753749999999990983, 0.013923140625000001921, 0.029904662109375004103, 0.062484875244140626604, 0.12438889535522459906, 0.22549483803134068305, 0.36206390866050391919, 0.53039385361573909705, 0.70984283151236515774, 0.8454844390975239099, 0.85252274549222006872, 0.73970724860508996201, 0.58630772383249318835, 0.39843019135055551816, 0.19933208669353075226, 0.045353321750430879156, 3.5933867024743799741e-06, 0, 0, 9.9999999999999995475e-07, 3.3749999999999998737e-06, 1.1390625000000002433e-05, 3.8443359375000005034e-05, 0.00012974633789062501275, 0.00043789389038085933673, 0.0014748635551852823811, 0.00458723586310897085, 0.012535204497088376849, 0.030902287796947387061, 0.069803749964903766267, 0.14306169398214990673, 0.2539595816136605011, 0.39367833655080086697, 0.54755337589389629915, 0.67082414394774525501, 0.67380308481828354861, 0.47157640817504958841, 0.20334679251999171479, 0.027698480049178006435, 0, 0, 0, 0, 0, 0, 1.009441616706038712e-08, 1.3354974400350171813e-06, 1.4329692329799520979e-05, 8.6376136215493001325e-05, 0.00040649103089326774291, 0.0016803271030961133663, 0.0063296923222741757059, 0.019902020690376800299, 0.053082350626863387955, 0.12474691161612924684, 0.25803204718826688868, 0.43676084046337160238, 0.48134381599312991984, 0.21958058358824134038, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3.4774589754063323979e-06, 0.00011191892632920368619, 0.00093408212868467904808, 0.0050968577425946322637, 0.022811546243018676616, 0.091659157974876420694, 0.30166673427236384564, 0.52750033633515069909, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.013642657214514538819, 0.22522060002743005125, ]).reshape((20, 7, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=5 +intercept=FALSE +Boundary.knots=None +knots=None +output=np.array([0, 0.11681123728381428983, 0.2730259078882545376, 0.46749900909245512004, 0.67935641673089897097, 0.85057627482867270707, 0.88934886597560480759, 0.80216081429413377268, 0.67739211125208298458, 0.51560190205519351725, 0.32469390916595280983, 0.13698024292938629221, 0.017122530366173265709, 0, 0, 0, 0, 0, 0, 0, 0, 0.0003496520800200754106, 0.0021367360720303471555, 0.0074505054668944550172, 0.02064467788236522966, 0.049822794327671247883, 0.10672495197833482827, 0.1969631195446764349, 0.31985257188474064405, 0.47686971233712693863, 0.65666375567302859295, 0.82030294962505467815, 0.89243231477003071017, 0.82865930832017831165, 0.7146974084023058893, 0.56412932414843675044, 0.38041985226043306678, 0.187187199501233692, 0.04043243509226646798, 0, 0, 2.6689299275350298406e-08, 4.1702030117734841467e-07, 2.86034224577543261e-06, 1.4315525026353663709e-05, 6.1210311482175452555e-05, 0.00023952573005394856335, 0.00087599557622739540694, 0.0027528938137588820738, 0.0075078612376215788857, 0.018529647319498028513, 0.042210845625950982329, 0.088408426246782453872, 0.16366728062036642322, 0.25992689327612594763, 0.36501727743515482993, 0.44566378087513086603, 0.43199704724253940036, 0.23880246889964723556, 0, 0, 0, 0, 0, 0, 0, 0, 7.058496255109760934e-08, 2.4230494175743949962e-06, 2.0524370058046372483e-05, 0.00011268784152075793045, 0.00050596181960801099326, 0.0020367286170134709343, 0.0076722266846277449928, 0.025178647959627011715, 0.068676202883725015469, 0.1606491966704423624, 0.31804567985939574681, 0.46051790249468016469, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.1843748275951593331e-06, 0.00019705036194114395882, 0.0021771955326834735445, 0.013267170193993682234, 0.062770073396831202461, 0.26024719351340613871, 1, ]).reshape((20, 5, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=12 +intercept=FALSE +Boundary.knots=None +knots=None +output=np.array([0, 0.67103518571234044288, 0.42848228882111855098, 0.069535818471346141911, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.13629558602559715963, 0.52330141887680614587, 0.67103578567914412556, 0.33835295499291540011, 0.045464904980911415022, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0030869584374568800715, 0.048215269973619155619, 0.25524093849303608472, 0.60346220790852211913, 0.66476640009174547963, 0.3023720875414114273, 0.032137228723967029009, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.0223284561703245952e-06, 0.0041874573564736911752, 0.058175656367661768287, 0.28413057856289342107, 0.62749346465948352414, 0.64458417746071206, 0.26642650281928137446, 0.020972348618427394396, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9.1807309007930243297e-06, 0.0056381163644495775958, 0.070099504751495456123, 0.31573089553161143295, 0.64918292160807222757, 0.61885031117979483195, 0.23077208437307619726, 0.012169621636861570682, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3.494304760976545528e-05, 0.0075476982837094025794, 0.084296696676371143941, 0.3501161628650154567, 0.66789290688121760731, 0.58719180485958433202, 0.19572881144127046715, 0.0058504368174458563218, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9.3878896275372805593e-05, 0.010061177336762315224, 0.10112604997332759471, 0.38726521207131708868, 0.68285613364861541541, 0.54940228374944388712, 0.16169301614535666611, 0.001987124003607085819, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00020895877237870428959, 0.013373361432237074534, 0.12100109812882933746, 0.42699888243551975542, 0.69315383369930994029, 0.50558220978145163027, 0.12915009496447266146, 0.00028659920802505926699, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00041395678128490346389, 0.017748396997590374508, 0.14439460468269080251, 0.46888258402048205165, 0.69769409523153691488, 0.45636616933565676835, 0.098685730485585029803, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00075854547264270536476, 0.023548082194459314664, 0.16992724106945886198, 0.46662458342302287617, 0.42010939261246582621, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0032285687345316718341, 0.076722648033295162695, 0.42847050190194924113, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.052734374999999840405, 1, ]).reshape((20, 12, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=None +intercept=FALSE +Boundary.knots=None +knots=np.array([]) +output=np.array([0, 0.00067663938125675493745, 0.0016904532697119580269, 0.0032085988210942785123, 0.0054800274275235618532, 0.0088741592009194299184, 0.013936134910759763808, 0.021463528321228261819, 0.032607690503775640933, 0.048995387512752772152, 0.072844594278869884141, 0.10699389717286836299, 0.15464119556617272888, 0.21832955541935578081, 0.29724527028257624606, 0.38124822804791375086, 0.44010197217760271826, 0.41166179703994132399, 0.22237265440082615298, 0, 0, 1.5271697506625337419e-07, 9.5415795571804482003e-07, 3.4427604254568415078e-06, 1.0065494095385778498e-05, 2.6485976820866183047e-05, 6.5657954600734260006e-05, 0.00015695450829847096968, 0.00036650624565625982386, 0.00084215780726247437687, 0.0019117237011529813161, 0.0042940168564642817658, 0.0095393459205458924072, 0.020904202366139650049, 0.044925430954654600735, 0.093631406124953353576, 0.18502397635429304601, 0.32899518168053926148, 0.4444443765651269751, 0, 0, 1.1489366970270387462e-11, 1.7952135891047479178e-10, 1.2313370007669466487e-09, 6.1626316488486427104e-09, 2.6350175916113057325e-08, 1.0311244903883365944e-07, 3.825826041044410135e-07, 1.3731610143675871737e-06, 4.8251465313854754769e-06, 1.6723672935651049261e-05, 5.7444337950753896285e-05, 0.0001961510972947611009, 0.00066716524892103249485, 0.0022633321684622557078, 0.0076650325325876428328, 0.025928742268953787475, 0.087643003996076676576, 0.29609576530082332146, 1, ]).reshape((20, 3, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=None +intercept=FALSE +Boundary.knots=None +knots=np.array([100, ]) +output=np.array([0, 0.015071708273510188089, 0.037381259008501491192, 0.070180462942842899987, 0.11790098280764790828, 0.18621717511273339074, 0.28155389351842002865, 0.40920060085307918829, 0.56848075164647782209, 0.74296035718046105067, 0.88664340493727211712, 0.92755941161894106539, 0.87470363121335126255, 0.79564729322794469635, 0.68622539174158070363, 0.5416556180357140482, 0.36526473871966497198, 0.17973006169687555378, 0.038821693326525116841, 0, 0, 3.4126433211387775282e-06, 2.1270238934697356366e-05, 7.6467258985853174243e-05, 0.00022233858750032365649, 0.00058020375050652503793, 0.0014202218581983020763, 0.003329890582419185209, 0.0075460478259266952628, 0.0165401227086783148, 0.03478495575013232366, 0.06861779430820802439, 0.12096540781627201921, 0.191329633412285538, 0.27905349779077742722, 0.37374631578125083742, 0.44360195032526716918, 0.42250875072786614473, 0.23095694223535656597, 0, 0, 2.5715731172923263021e-10, 4.0180829957692598212e-09, 2.7560031267981358852e-08, 1.3793325533914163604e-07, 5.8977491272702679876e-07, 2.3078834777630869564e-06, 8.5630404390810414166e-06, 3.0734364733920997454e-05, 0.00010799739567214114531, 0.00037431259576781883034, 0.0012857306725170922646, 0.0043281861315545133023, 0.012933767638577380737, 0.033975759516814023342, 0.080531027913042049771, 0.17293083479161802662, 0.32462175106248042367, 0.45442872954598834134, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2.7748388221855075202e-06, 8.9305721192384863918e-05, 0.00074535095082784331034, 0.0040670382699930507364, 0.018202476163449766294, 0.07313943651277800273, 0.27579263489213001748, 1, ]).reshape((20, 4, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=None +intercept=FALSE +Boundary.knots=None +knots=np.array([1000, ]) +output=np.array([0, 0.0015004113953972979083, 0.0037469425348356701772, 0.0071075541598605747329, 0.012127833209738946019, 0.019611910086607075437, 0.030734076107229148234, 0.04718451762439003494, 0.071340002591639736784, 0.10641511473995685089, 0.15646348082190494888, 0.22590626848315542574, 0.31787571113275914225, 0.42998547021895328069, 0.54537912943555955092, 0.61788880868397033641, 0.56161589860385985329, 0.31265651834613988891, 0.067535071081621433908, 0, 0, 3.3870374289331948997e-07, 2.1158906445184196164e-06, 7.6329082682329570748e-06, 2.2309178641915861703e-05, 5.8676185825556269023e-05, 0.00014535443145101360611, 0.00034710023984489360048, 0.00080922144066932952776, 0.0018549168973065219106, 0.0041951273738663188637, 0.0093691710332807192491, 0.020628857715017115404, 0.044564197866965707395, 0.093532235391030102423, 0.18697094954821646962, 0.34034142027880176506, 0.49294319032437394767, 0.3494912754584255099, 0, 0, 2.5484057919113140944e-11, 3.9818840498614283815e-10, 2.7311742697999542126e-09, 1.3669061339914938246e-08, 5.844616252249814789e-08, 2.2870917347201761224e-07, 8.4858959306208503663e-07, 3.0457478565146930827e-06, 1.0702444616158128632e-05, 3.7094041022036097191e-05, 0.00012741475133052262828, 0.00043507409392457165433, 0.0014798098005849495782, 0.0050201972154368997708, 0.017001470448093195659, 0.057511399145102344577, 0.1943970799975693331, 0.52239901147403788872, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.060574641985915035625, 1, ]).reshape((20, 4, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=None +intercept=FALSE +Boundary.knots=None +knots=np.array([10, 100, 1000, ]) +output=np.array([0, 0.1567541293972270211, 0.35648024152864221659, 0.58396161300859317222, 0.78843465486178421209, 0.87349958752470602263, 0.78872593441389438063, 0.64620704007646878608, 0.46633671277914778841, 0.26443067498670752569, 0.086017059388510438978, 0.0027907697403672538511, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00082460534200152601353, 0.0049930443273597038822, 0.017154488011057174995, 0.046372256997114502663, 0.10706684228609344989, 0.21001709629214043717, 0.349560411044427366, 0.52164005645501687614, 0.7052885939808604121, 0.84461817796425076033, 0.85332055763972392004, 0.74044769630139117833, 0.58689461845094414993, 0.39882902037092649028, 0.19953161831184262898, 0.045398720470901786361, 3.5969836861605402089e-06, 0, 0, 0, 1.4043223919767127475e-07, 2.1942537374636142735e-06, 1.5050386385262928333e-05, 7.5324616581368114944e-05, 0.0003220729407222703883, 0.001256955617244540557, 0.0042307394405898370374, 0.012003815755055342179, 0.030163701749655900952, 0.068814016157702301291, 0.14161203135855129909, 0.25097331049689530769, 0.38604331096967514636, 0.52843933204950088722, 0.62702364005086641541, 0.58518234575989880319, 0.32861311390225123041, 0.070981847410833104339, 0, 0, 0, 0, 0, 0, 0, 1.3676720629513371727e-08, 1.8094385139768081762e-06, 1.9415010780026244647e-05, 0.00011702928277625300924, 0.00055074648953661010323, 0.0022766412613576141911, 0.0085724666641985424603, 0.026852019770306118779, 0.070978550821878275134, 0.16387889672004127273, 0.32660594492319316995, 0.49935626095003893266, 0.36224174733681202554, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6.5265375148376491226e-06, 0.00021005080907461989208, 0.0017530967576943525671, 0.0095658449172495805396, 0.042812988846006136412, 0.17202702816402348773, 0.50620176326643973042, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.060574641985915035625, 1, ]).reshape((20, 6, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=5 +intercept=FALSE +Boundary.knots=np.array([0, 3000, ]) +knots=None +output=np.array([0.20791834248678603414, 0.29902312242189532654, 0.42058546782444744538, 0.57127689681172544311, 0.73389736255977222612, 0.86146730066325027941, 0.87986332643537079612, 0.79291382076038952054, 0.66958340212426392668, 0.50965824665676062732, 0.32095096582466564605, 0.13540118870728076739, 0.016925148588410078576, 0, 0, 0, 0, 0, 0, 0, 0.0012695557913002517882, 0.0028166847710175994465, 0.0062031625467877079053, 0.013503589345765960872, 0.028852424480264381862, 0.059752006107076843788, 0.11700693595529969293, 0.20637160010579103098, 0.32827217823508614281, 0.48461478028531612683, 0.66503213888472001436, 0.83266225254172265835, 0.91555098377957688793, 0.87163430177910428132, 0.78404142346700400612, 0.66397286412208100792, 0.507883804798330174, 0.32286071959112722096, 0.1392180359854287286, 0.018963308663199267973, 1.4499417527118528165e-07, 4.893553415402503421e-07, 1.6515742776983449575e-06, 5.5740631872319126435e-06, 1.8812463256907710572e-05, 6.3492063492063516403e-05, 0.000214285714285714356, 0.0007145407126011744112, 0.0021431007122621795712, 0.0057158011131347528228, 0.013955556387630695808, 0.03166115066306447734, 0.066415223634956249699, 0.12418853438999710725, 0.20209136094044644061, 0.29685688827833944803, 0.39377505733963352741, 0.45246903544196670488, 0.39638281649040951748, 0.1597891894713379668, 0, 0, 0, 0, 0, 0, 0, 3.8421218399486777976e-08, 1.3189283878698809637e-06, 1.117194478839918966e-05, 6.133890298378388427e-05, 0.00027540808793216300541, 0.0011086439970568826713, 0.0041767162702452207551, 0.013792752688869525796, 0.038347512235655537016, 0.093327637726685397368, 0.20095020769675242533, 0.36605493991801690834, 0.4433598240831516657, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4.4756065322375969297e-07, 7.4462903680102773569e-05, 0.0008227353639237797861, 0.0050135001353509671407, 0.023720037270153770254, 0.09834420760614477619, 0.37788767778231108219, ]).reshape((20, 5, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=12 +intercept=FALSE +Boundary.knots=np.array([0, 3000, ]) +knots=None +output=np.array([0.61574942641905272556, 0.5337910278271761344, 0.26630652260904380535, 0.04321728691476599965, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.21709357831448763965, 0.40428360185244682778, 0.62558529044677246844, 0.63046184489143586305, 0.30534794185536534572, 0.041029980550522253402, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0094918061936686368846, 0.032034845903631647968, 0.10810716461572758562, 0.32213341083732455195, 0.63646722104607222903, 0.66920132452213465513, 0.3023720875414114273, 0.032137228723967029009, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.0223284561703245952e-06, 0.0041874573564736911752, 0.058175656367661768287, 0.28413057856289342107, 0.62749346465948352414, 0.64458417746071206, 0.26642650281928137446, 0.020972348618427394396, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9.1807309007930243297e-06, 0.0056381163644495775958, 0.070099504751495456123, 0.31573089553161143295, 0.64918292160807222757, 0.61885031117979483195, 0.23077208437307619726, 0.012169621636861570682, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3.494304760976545528e-05, 0.0075476982837094025794, 0.084296696676371143941, 0.3501161628650154567, 0.66789290688121760731, 0.58719180485958433202, 0.19572881144127046715, 0.0058504368174458563218, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9.3878896275372805593e-05, 0.010061177336762315224, 0.10112604997332759471, 0.38726521207131708868, 0.68285613364861541541, 0.54940228374944388712, 0.16169301614535666611, 0.001987124003607085819, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00020895877237870428959, 0.013373361432237074534, 0.12100109812882933746, 0.42699888243551975542, 0.69315383369930994029, 0.50558220978145163027, 0.12915009496447266146, 0.00028659920802505926699, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00041395678128490346389, 0.017748396997590374508, 0.14460859026960704021, 0.4755254951851585199, 0.74591378938143138022, 0.59473172632230031365, 0.2566313326020329133, 0.03495652799821041129, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00054455988572647427617, 0.016905171029782832537, 0.12340338564379622899, 0.3685583814319431939, 0.50219016290765505772, 0.24887848966988834754, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0015327300102998579149, 0.03642329303773143151, 0.22969990963832651043, 0.49849681328683803638, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.011478594851985721506, 0.21766816904506322561, ]).reshape((20, 12, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=None +intercept=FALSE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([]) +output=np.array([0.00099933344444444439057, 0.0014985003750000000684, 0.0022466262656250001253, 0.003367410521484375148, 0.0050454284787597655781, 0.0075553552955017096171, 0.011304291651615143086, 0.016891872202619076515, 0.02519288281652980882, 0.037464410913716578166, 0.055469506915694993809, 0.081581580145842852447, 0.11876628136094780075, 0.1701874001952980997, 0.23787846467254591953, 0.31938947503806314199, 0.40070172821401484065, 0.44437167848162473227, 0.38044436785608970464, 0.1510757732538548781, 3.3322222222222224585e-07, 7.4962500000000004377e-07, 1.6862343750000001263e-06, 3.7926035156249994121e-06, 8.5285524902343742213e-06, 1.9173024810791016186e-05, 4.3084569087982178912e-05, 9.675554396295546727e-05, 0.00021707648827975990682, 0.00048631783460495621712, 0.0010871132367784521085, 0.0024220359003474063384, 0.0053686857976677918383, 0.011806522493618208658, 0.025643231250562635581, 0.054587395598501557703, 0.11232581293261123534, 0.217309662419816918, 0.36939270915445387988, 0.42763873999331791786, 3.7037037037037035514e-11, 1.2500000000000000779e-10, 4.2187500000000000366e-10, 1.4238281249999998508e-09, 4.8054199218749994447e-09, 1.6218292236328128606e-08, 5.4736736297607425773e-08, 1.8473648500442501235e-07, 6.234856368899344564e-07, 2.1042640245035291742e-06, 7.1018910826994105393e-06, 2.3968882404110509299e-05, 8.0894978113872978626e-05, 0.00027302055113432129778, 0.00092144436007833422416, 0.003109874715264377993, 0.010495827164017276431, 0.035423416678558306003, 0.11955403129013431052, 0.40349485560420322861, ]).reshape((20, 3, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=None +intercept=FALSE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([100, ]) +output=np.array([0.029691034444444444618, 0.044305991250000002768, 0.06594240796875000532, 0.097758673769531262421, 0.1440642544409179715, 0.21038931479278566439, 0.30302618229869843214, 0.4272397443474625911, 0.58266048231123623857, 0.75392639264340943761, 0.89747740349010274308, 0.94501107412874996161, 0.90598359089303848179, 0.84593074837236126307, 0.76092088936222046502, 0.64439302204983184286, 0.49290686036830000383, 0.31333990595172406257, 0.13511264658550559137, 0.018404101188231606484, 9.9644444444444446617e-06, 2.2379999999999999178e-05, 5.0219999999999996902e-05, 0.00011253937500000000703, 0.00025167585937500001371, 0.0005610808300781249848, 0.0012449161120605468141, 0.002741945576934814565, 0.0059698621442985533997, 0.012758825336830616898, 0.02643475186140507513, 0.051808149318846051512, 0.091620856894323976505, 0.14688590543057178373, 0.21984251899359169569, 0.30818245617558825966, 0.39752224089834975462, 0.44889001546541440479, 0.38890408238266155339, 0.15565065849749706861, 1.1111111111111110654e-09, 3.7499999999999996649e-09, 1.2656249999999997938e-08, 4.2714843750000004622e-08, 1.4416259765625001146e-07, 4.8654876708984372583e-07, 1.6421020889282224026e-06, 5.5420945501327518529e-06, 1.8704569106698035598e-05, 6.3127920735105882001e-05, 0.00021305673248098232295, 0.00071906647212331535352, 0.002394473001231371169, 0.0071486127371715351211, 0.018946704087009914874, 0.045842738337222695144, 0.10249145334758576198, 0.20932413300445151805, 0.3687199031810673433, 0.43701763935524273741, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.0792114061605856464e-06, 3.473345989527011488e-05, 0.00028988755717800383316, 0.0015817834373569547059, 0.0070794453857644188549, 0.028445945578409920912, 0.10726336785076537317, 0.38892760095902845219, ]).reshape((20, 4, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=None +intercept=FALSE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([1000, ]) +output=np.array([0.0029960014444444446613, 0.0044910048749999993689, 0.0067297664531250009357, 0.010079493029296874088, 0.015085171786376951053, 0.02255122235714721729, 0.033655024381153107738, 0.050097300181899548366, 0.074283671347553537068, 0.10950057690181402847, 0.15997106401940666687, 0.23050015162429349225, 0.3250574690342031281, 0.44299931223779698275, 0.57083333883520204211, 0.6679625481063525827, 0.65410023301458430911, 0.45433806106867219432, 0.19591333754898310193, 0.026685946722935827841, 9.9944444444444452216e-07, 2.2481249999999997573e-06, 5.0561718750000005462e-06, 1.1369267578125000521e-05, 2.5556824951171875081e-05, 5.7421764678955089446e-05, 0.00012892528684616086799, 0.00028915821297883983077, 0.00064748855101794003473, 0.0014463279196678473747, 0.0032187283638391594488, 0.0071222944066175568334, 0.015620687524320137074, 0.033781444174048706752, 0.071401027591217913759, 0.14510293850391842163, 0.2740024758137300509, 0.43938848718810108451, 0.4727098830096430615, 0.21327068651931446741, 1.1111111111111111947e-10, 3.750000000000000492e-10, 1.2656250000000001661e-09, 4.2714843749999999659e-09, 1.4416259765625000816e-08, 4.8654876708984385818e-08, 1.6421020889282225085e-07, 5.5420945501327514294e-07, 1.8704569106698034751e-06, 6.3127920735105875225e-06, 2.1305673248098235006e-05, 7.190664721233152451e-05, 0.00024268493434161889522, 0.00081906165340296394756, 0.0027643330802350029977, 0.0093296241457931361474, 0.031487481492051827558, 0.10627025003567493189, 0.31773412222685926132, 0.53482276673031980962, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.013642657214514538819, 0.22522060002743005125, ]).reshape((20, 4, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=None +intercept=FALSE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([10, 100, 1000, ]) +output=np.array([0.26810999999999995946, 0.37949624999999997943, 0.52058109375000005681, 0.6792815039062500837, 0.81701452880859382066, 0.86124092926025386241, 0.77303028831905795659, 0.63334751997894722653, 0.45705661219484272628, 0.2591685045544720456, 0.084305319906679110353, 0.002735233422533945441, 0, 0, 0, 0, 0, 0, 0, 0, 0.0028890000000000000749, 0.0063753749999999990983, 0.013923140625000001921, 0.029904662109375004103, 0.062484875244140626604, 0.12438889535522459906, 0.22549483803134068305, 0.36206390866050391919, 0.53039385361573909705, 0.70984283151236515774, 0.8454844390975239099, 0.85252274549222006872, 0.73970724860508996201, 0.58630772383249318835, 0.39843019135055551816, 0.19933208669353075226, 0.045353321750430879156, 3.5933867024743799741e-06, 0, 0, 9.9999999999999995475e-07, 3.3749999999999998737e-06, 1.1390625000000002433e-05, 3.8443359375000005034e-05, 0.00012974633789062501275, 0.00043789389038085933673, 0.0014748635551852823811, 0.00458723586310897085, 0.012535204497088376849, 0.030902287796947387061, 0.069803749964903766267, 0.14306169398214990673, 0.2539595816136605011, 0.39367833655080086697, 0.54755337589389629915, 0.67082414394774525501, 0.67380308481828354861, 0.47157640817504958841, 0.20334679251999171479, 0.027698480049178006435, 0, 0, 0, 0, 0, 0, 1.009441616706038712e-08, 1.3354974400350171813e-06, 1.4329692329799520979e-05, 8.6376136215493001325e-05, 0.00040649103089326774291, 0.0016803271030961133663, 0.0063296923222741757059, 0.019902020690376800299, 0.053082350626863387955, 0.12474691161612924684, 0.25803204718826688868, 0.43676084046337160238, 0.48134381599312991984, 0.21958058358824134038, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3.4774589754063323979e-06, 0.00011191892632920368619, 0.00093408212868467904808, 0.0050968577425946322637, 0.022811546243018676616, 0.091659157974876420694, 0.30166673427236384564, 0.52750033633515069909, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.013642657214514538819, 0.22522060002743005125, ]).reshape((20, 6, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=5 +df=12 +intercept=TRUE +Boundary.knots=None +knots=None +output=np.array([1, 0.24780328615799376846, 0.0091743090758214639741, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.64369896942547122354, 0.57211971408849160436, 0.24237606578683060232, 0.044144491052264721309, 0.00040499520490831021667, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.10612816657504857421, 0.39035389287158045457, 0.63115822592338399755, 0.61942792972003923868, 0.3746409686363950664, 0.1299270153679348283, 0.01456850160548600788, 2.4933115730197022697e-06, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0023615475345642161081, 0.028071577965966144214, 0.12345862383415923125, 0.3183634697319876472, 0.55248624494736087165, 0.66157907323456133231, 0.54063561857561015511, 0.27886806629206489783, 0.077562585629719432712, 0.0043678218067639239253, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8.026857613403984366e-06, 0.00028016915158263086755, 0.0029987443674941152358, 0.017947370921348515527, 0.071410333320899577192, 0.20176799613356366514, 0.41383987857855386583, 0.6154467549253210823, 0.65231295225138286042, 0.47044608242977714596, 0.21195012900662815736, 0.045727490940629646199, 0.00095767216067723433693, 0, 0, 0, 0, 0, 0, 0, 3.4493087511455702552e-09, 3.3684655772905958113e-07, 8.3400865772486489595e-06, 0.00011672374464387017944, 0.001056583561129178974, 0.0067076933166381781659, 0.030729882600253097258, 0.10383387100350169319, 0.2594160581947105304, 0.48008955662192837055, 0.64645432100283450882, 0.61990700734803594329, 0.39505102004440167951, 0.15152949559297854143, 0.022327498493473717928, 5.4255821339140527268e-05, 0, 0, 0, 0, 0, 0, 1.5550084505986725427e-12, 1.4829716211306275165e-08, 8.7432930709587782537e-07, 1.8221855962693547294e-05, 0.00022606146610042746276, 0.0018465551075490084856, 0.010668371345813800616, 0.044660809207147045274, 0.13839012473302086947, 0.31749140013695392737, 0.53873603574199457888, 0.65962064818889976081, 0.56521993555148342114, 0.310506638922921685, 0.095251921793756827439, 0.0074067894386825334357, 0, 0, 0, 0, 0, 0, 0, 9.1339471742565674011e-11, 5.7173996413972389293e-08, 2.2593599905185296879e-06, 4.0028808856421427135e-05, 0.00043513707847336695594, 0.0031885139595084076476, 0.016618589891805510966, 0.062812605113451408512, 0.1727378974109962384, 0.33696595086343833492, 0.43637044859132123609, 0.31354081400102012944, 0.068636818178064884499, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3.7695168114557225724e-09, 5.9285591015796308443e-07, 1.6911296921410870622e-05, 0.00025529307410796154469, 0.0024263360322963763681, 0.015741731604329466804, 0.070644470707028478307, 0.21311252564833091383, 0.3762972750744253414, 0.24384934178453185338, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.0868704401501409189e-12, 2.1860846716771802376e-07, 1.6330907178590211063e-05, 0.00037021035039809161273, 0.0048110469704648085865, 0.038471273482950811562, 0.18655513337806783891, 0.39552144655799137407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.6852398034939565224e-08, 3.1097414111410212796e-05, 0.0014848575331362907741, 0.028249998152729726558, 0.25456576340175340878, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00010485760000000057303, 0.030019840638976030833, 1, ]).reshape((20, 12, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=5 +df=None +intercept=TRUE +Boundary.knots=None +knots=np.array([]) +output=np.array([1, 0.99887226764047176708, 0.99718257698671308731, 0.99465232914808876519, 0.99086659019744105503, 0.98520960330607720845, 0.9767725953351565904, 0.96422555375161622671, 0.94564705949867622348, 0.91831730137969458383, 0.87851085191767241955, 0.82140061321171964348, 0.74134024099742168445, 0.63306797132011838336, 0.49472136419952228437, 0.33351966492579832035, 0.17295333506564730675, 0.053041675157364839843, 0.0041245206602366912829, 0, 0, 0.0011272234177996938269, 0.0028142442804627715303, 0.0053362072774053633667, 0.0090999196124958610377, 0.014702372431044495246, 0.023009568696928141274, 0.035255048800207078319, 0.053144756365466998271, 0.078922539871719557536, 0.11527760116980134697, 0.16482753559964863355, 0.22865514515079901625, 0.30306893078627178406, 0.37385911082806172478, 0.40954833229285447782, 0.36355794566479110452, 0.2119513600790149388, 0.041217298467029310494, 0, 0, 5.0882687398560041373e-07, 3.1769391294621280289e-06, 1.1451280924188917779e-05, 3.3428733100138665235e-05, 8.7761935886847988286e-05, 0.00021681208262686383053, 0.00051561316170019592855, 0.0011946804469067555735, 0.0027131220507094727483, 0.0060506596144855023106, 0.013230141811374926397, 0.028210083582453096551, 0.058035333309565624582, 0.11300958063559926603, 0.20116335451605230067, 0.30568795867586873172, 0.33877798094471850421, 0.16475763686175207146, 0, 0, 1.1484182443411814437e-10, 1.7931887260774516498e-09, 1.2286988490864389756e-08, 6.1400553206305291637e-08, 2.6193586874264870438e-07, 1.0214767558696939837e-06, 3.7704802796487805225e-06, 1.3428054504627923681e-05, 4.6634530984498030184e-05, 0.00015879269432593164958, 0.00053096908751411363639, 0.00174019442073816092, 0.0055566565395111476577, 0.017080184681265514479, 0.049404053208565550104, 0.12851476524402274948, 0.27074730808567093465, 0.32929231067852438031, 0, 0, 1.2959854631941128047e-14, 5.06072933143619642e-13, 6.5918427455453850986e-12, 5.6389033989814727996e-11, 3.9088927700060016774e-10, 2.406265255469648607e-09, 1.378603437152614992e-08, 7.5464802427343835863e-08, 4.0078909822273000137e-07, 2.0836670196190539855e-06, 1.0654767572225721294e-05, 5.3673655611779830157e-05, 0.00026601408260545672708, 0.0012907432586925205419, 0.0060666130749972404027, 0.027014549341864656923, 0.10818900424286860551, 0.32906949849914446382, 0, 0, 5.8500579526198340832e-19, 5.7129472193553077444e-17, 1.4145822896898457119e-15, 2.0714622186680568112e-14, 2.3333104795078233906e-13, 2.2673496764008742317e-12, 2.0162390952550372537e-11, 1.6964293385718098169e-10, 1.3777936465799164788e-09, 1.0936695210263550545e-08, 8.5522170452256458058e-08, 6.6219297623306537514e-07, 5.0939619277349284707e-06, 3.9016396858695978102e-05, 0.00029798198173219142288, 0.00227144600780565184, 0.017292671490362138825, 0.13153873483331313121, 1, ]).reshape((20, 6, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=5 +df=None +intercept=TRUE +Boundary.knots=None +knots=np.array([100, ]) +output=np.array([1, 0.97500126574733914087, 0.93844290960000364965, 0.88566924020111725824, 0.81098530154789516544, 0.70848516022771668155, 0.57441053105822748037, 0.41206430922482584212, 0.2392461015407435776, 0.092939125284492898893, 0.014299466806025581608, 4.7193863677059842883e-05, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.024987397851780435848, 0.061486796626462968118, 0.1140799960900419352, 0.1882939537142028219, 0.28966625638367565765, 0.42117968175620157378, 0.57798465087862005429, 0.73943782746930653005, 0.86397935690336380432, 0.90462871246453147034, 0.85976637084822715718, 0.77601114642224255924, 0.66267521310641597232, 0.51785842958629058064, 0.34911766989097126057, 0.18104199448456753663, 0.055522321426452851678, 0.0043174157141209739547, 0, 0, 1.1333836374491041766e-05, 7.0253868335539153452e-05, 0.00025049169236306427153, 0.00071939598049462782393, 0.0018428967293926601032, 0.0043879998552115674279, 0.0098727402942039785283, 0.021048289930652556295, 0.042207103219050953746, 0.078361329513138483494, 0.1323267251748408424, 0.20305646979998087653, 0.28625091024051202426, 0.36712456913477936604, 0.41237454577086030127, 0.37209382828918063923, 0.21926721332006066101, 0.042943027456719351509, 0, 0, 2.5642163564224008165e-09, 3.9893896948733327568e-08, 2.7186958324120860093e-07, 1.3475047468249140318e-06, 5.6780166980285093331e-06, 2.1734507210374597486e-05, 7.8000238621073664019e-05, 0.00026616938183067457386, 0.00086607259863206911138, 0.0026688434677071591963, 0.0076602480569788727188, 0.020032890189762748295, 0.047362176442216685768, 0.10112516340575794516, 0.19128545657973258787, 0.30258229747242648688, 0.34436724521558481626, 0.17045464690987927048, 0, 0, 2.8979008849349871451e-13, 1.1299684644739179399e-11, 1.4686295227238142049e-10, 1.2521970298985838129e-09, 8.6372943219355255736e-09, 5.2772400925513216102e-08, 2.9891245041530529781e-07, 1.607880484564848822e-06, 8.3111564072833673416e-06, 4.1402961295506068027e-05, 0.00019754788193526286806, 0.00088468396831814228969, 0.0036015013400145573161, 0.013149579882492583999, 0.042768561910798960635, 0.12037399719492403172, 0.26730426029673903798, 0.33672081019045274619, 0, 0, 1.309371682920953332e-17, 1.2786832841024935257e-15, 3.1661464010829005262e-14, 4.6363882090260461786e-13, 5.2224622287067364928e-12, 5.0748274386406234902e-11, 4.5127867086219768747e-10, 3.7969821085404869e-09, 3.0838053235562167103e-08, 2.44787301750460405e-07, 1.9141743408195724709e-06, 1.4809071760067401229e-05, 0.00011002044182894339316, 0.0007361307065949982114, 0.0043501410333869746858, 0.022648326644076191561, 0.10074752233050462968, 0.32871166293410319925, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5.4793570769921117731e-10, 1.7842901170031562027e-07, 6.1272840845677704696e-06, 0.00010362481425005589904, 0.0012595559148250148798, 0.012791437410658173385, 0.11685243679472454015, 1, ]).reshape((20, 7, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=5 +df=None +intercept=TRUE +Boundary.knots=None +knots=np.array([1000, ]) +output=np.array([1, 0.9975000012515636838, 0.99375938046297329631, 0.9881694981371595965, 0.97983186568317970355, 0.96743102855471574397, 0.94906548971852167096, 0.92204114544049331492, 0.88266217520230549898, 0.82612719043156179755, 0.74679100501527517775, 0.63932416597329111418, 0.50165120112244221406, 0.34054780971703357828, 0.17887753393501265586, 0.056398049910775530091, 0.0047824514208348522723, 6.9899702309353164834e-10, 0, 0, 0, 0.0024988701975066367374, 0.0062335737743966241481, 0.011805108206123089004, 0.020094017057672219906, 0.032374436158623724757, 0.050454096263104174225, 0.076816980711751164934, 0.11469423978741608017, 0.16787638509201657788, 0.23985925947403505254, 0.33155764168655321722, 0.4364690436594241274, 0.53267348082579712987, 0.57514542430970139186, 0.50463302930351572329, 0.30623588293439429897, 0.096587849561305616497, 0.0075106712808647091081, 0, 0, 1.1282962103271197581e-06, 7.0417854820895302466e-06, 2.536640667453833115e-05, 7.3981096505374880712e-05, 0.00019395448667024030114, 0.00047814948330325205252, 0.0011335173229715391711, 0.0026138368581788955919, 0.0058931764589364287604, 0.012998501527337540801, 0.027945386445582046098, 0.058044007669012950834, 0.1145680954987259581, 0.2086069927114643785, 0.33148565972609811414, 0.41061823564260202524, 0.3066625410662744966, 0.068889778730265194273, 0, 0, 2.5469057156714312774e-10, 3.976025713192789869e-09, 2.7235422387831816846e-08, 1.3603757883811768205e-07, 5.7993308882550318022e-07, 2.2591989366454093128e-06, 8.3259563410340815473e-06, 2.9580849000601624262e-05, 0.00010235971125482330811, 0.00034661758311907198181, 0.001149214388416119545, 0.0037170166582407206807, 0.011623043605661884797, 0.034525979049628140183, 0.094171296281739258482, 0.21954225794050497012, 0.36514412761590397949, 0.24346326935859208263, 0, 0, 2.8744101198050118059e-14, 1.1223436953991581798e-12, 1.4617253735361878953e-11, 1.2501806315302350017e-10, 8.6638386346496238246e-10, 5.3311050540562872207e-09, 3.0523721489433262118e-08, 1.6692682142232341016e-07, 8.8525020719146049419e-07, 4.5921420319874677743e-06, 2.3401813204582281116e-05, 0.0001172621098580812533, 0.00057627166059595505247, 0.0027575294458836020588, 0.012651024092369157759, 0.053782977897194939043, 0.19324936944781076487, 0.3997562713358867037, 0, 0, 1.2975755416333770318e-18, 1.2671636148763449243e-16, 3.1376225596317031531e-15, 4.5946189458816680778e-14, 5.1754130194391066624e-13, 5.0291082725267428713e-12, 4.4721309725082660758e-11, 3.762775062517599803e-10, 3.0560232936142684245e-09, 2.4258201074369941878e-08, 1.8969295269383146249e-07, 1.4687810219326831175e-06, 1.1298692185571222767e-05, 8.6540548310009559815e-05, 0.00066094068550206401882, 0.0050381941644688631871, 0.038356111609708157251, 0.27103704347500323646, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0093429658193878890871, 1, ]).reshape((20, 7, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=5 +df=None +intercept=TRUE +Boundary.knots=None +knots=np.array([10, 100, 1000, ]) +output=np.array([1, 0.75141884282545001739, 0.47347381451739223301, 0.21613090194838843749, 0.049696178730542467372, 0.0013661273532290147976, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.24594066521407775827, 0.51146600459087232515, 0.73649217207800155016, 0.8374180350990879651, 0.77783093616193677011, 0.63185158416405007298, 0.45327074014730833751, 0.26317071169481792703, 0.10223303781294215686, 0.015729413486628138208, 5.1913250044765826493e-05, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0026391300640233733565, 0.015039867450995366219, 0.047247102051768179176, 0.1123025082166889399, 0.21868817428784292911, 0.36168436874353226962, 0.52963938325215309533, 0.69654238826126158024, 0.81185888378284087885, 0.81901416673831617388, 0.71604356256126133751, 0.5618949499117826818, 0.38144450577487010179, 0.20035909960120826256, 0.06317094299551503922, 0.0053567803596460189172, 7.8294021104867289565e-10, 0, 0, 0, 1.3617399508643758347e-06, 2.0307441416267721758e-05, 0.00012974796415461092966, 0.00058265627417901637731, 0.0021107453507099383297, 0.0064420295146436082692, 0.01698600253976614155, 0.039859183304507203593, 0.084333549165298365979, 0.1600060050847842974, 0.26809274258076365438, 0.39566435336691235802, 0.51703688602850017553, 0.58200587206136744634, 0.52329606670761874554, 0.32126381870611603331, 0.10151738768556310688, 0.0078939921772932797328, 0, 0, 1.5649080494945798507e-10, 5.9986253804949622248e-09, 7.5940397022685528773e-08, 6.2142631098330448954e-07, 4.0139943226430085122e-06, 2.1989865743143280786e-05, 0.00010363219420155694861, 0.00042588199885955281988, 0.0015624557228769457226, 0.0051797373818038370402, 0.015437236122329209276, 0.040650688803865277221, 0.093964606272201794956, 0.18957613958735397564, 0.32176934741298385267, 0.41523761089925581569, 0.31715186300322989466, 0.072004316292680670131, 0, 0, 7.1504090682135632783e-15, 6.9828213556773098054e-13, 1.7290156975971226543e-11, 2.531906923450678459e-10, 2.8519588261786051741e-09, 2.7712025453436415246e-08, 2.4184791568371559048e-07, 1.8337667890099757592e-06, 1.2054075181315261422e-05, 7.0420380839424076883e-05, 0.00037180990877366712185, 0.0017643270358445378374, 0.0073398980933030329166, 0.026537861233464601213, 0.082516974679995302999, 0.20957251000715282352, 0.36763462897045218192, 0.25222621956325630421, 0, 0, 0, 0, 0, 0, 0, 5.430767431219823664e-15, 1.8655102027007631066e-11, 9.7376457669355941836e-10, 1.9440860511832082848e-08, 2.5692762827202482626e-07, 2.7355768273926624709e-06, 2.5679592827130744701e-05, 0.00021368415859150435886, 0.0015066158869563137275, 0.0090029382862195743431, 0.045606751586747915073, 0.18361012124256628764, 0.40566571262016642985, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.2887678100169456754e-09, 4.196725335132502196e-07, 1.441162964935832764e-05, 0.00024372991766721753461, 0.0029625284410813028553, 0.030085998315248142776, 0.25286679352721525005, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0093429658193878890871, 1, ]).reshape((20, 9, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=5 +df=12 +intercept=TRUE +Boundary.knots=np.array([0, 3000, ]) +knots=None +output=np.array([0.13756522087537645382, 0.03408911379396852015, 0.0012620658543943507734, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.63650820114425754603, 0.56442389527296787932, 0.36731014666049194295, 0.15313548110822144954, 0.027890905208072903215, 0.00025587978478329849409, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.21582542819545830204, 0.37161327360106727324, 0.54958413949399687048, 0.64871936385648787393, 0.56949455728677522703, 0.3353237146654387546, 0.11624293381549648252, 0.013034128145880629485, 2.2307127685738320293e-06, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.010030255096273907323, 0.029534067226298671427, 0.080270381333806692381, 0.19129075916133608803, 0.37605173703394079165, 0.57813180094222393901, 0.65912921049582962052, 0.52910502202296083585, 0.27213902033160508598, 0.075690939564343556745, 0.0042624228385304534922, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7.0831944077479075004e-05, 0.00033917363922361448356, 0.0015696484900234396707, 0.006826920796842389158, 0.026357789549328776435, 0.084918297819850163677, 0.21706326994359459448, 0.42522472470932526356, 0.61970296224817356112, 0.65157393079529135616, 0.46867117785961504017, 0.21110309109651023696, 0.045544745506395555024, 0.00095384491778118137267, 0, 0, 0, 0, 0, 0, 6.2744556242273010119e-08, 4.764664739647606222e-07, 3.6181672866699010542e-06, 2.7475075557388156146e-05, 0.00020499609216608624608, 0.0013694324583970120431, 0.0075463637977772560911, 0.032410006481736260142, 0.10630697223991346367, 0.26202672571617779962, 0.48196986016032394851, 0.64730135891295237371, 0.6200897527822700761, 0.39505484728729772792, 0.15152949559297854143, 0.022327498493473717928, 5.4255821339140527268e-05, 0, 0, 0, 0, 0, 0, 1.5550084505986725427e-12, 1.4829716211306275165e-08, 8.7432930709587782537e-07, 1.8221879880749471527e-05, 0.00022607643762169348975, 0.0018471467411283852555, 0.010678853506751016453, 0.044774794636566098149, 0.13922623229659780719, 0.32186074315609991547, 0.55535177436803673245, 0.70594649934249964485, 0.65842055649705455433, 0.44019721934864292079, 0.20692042038665983683, 0.050925719374514837046, 0.0018364038370179928007, 0, 0, 0, 0, 0, 0, 6.7421415818675005971e-11, 4.2202475147942958715e-08, 1.6677264111419149931e-06, 2.9548372537568077557e-05, 0.0003214228907650466577, 0.0023601436034748866921, 0.012366085974335782813, 0.047309807190604125093, 0.13367877749039860924, 0.27692812785680914756, 0.41099272250632723491, 0.40841144311061738925, 0.22284961609469711163, 0.025059128845635693372, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2.0448984495923750749e-09, 3.2161419941923913368e-07, 9.1740900392921949651e-06, 0.00013858698681402402734, 0.0013233320235020520645, 0.0087002635234140028586, 0.040418548886275447451, 0.13266384308046400009, 0.2919610966000151242, 0.36977070091947494834, 0.13378226109816304668, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4.2555387649176344133e-13, 8.5594084815015888324e-08, 6.3942127780347038856e-06, 0.00014495964162350503772, 0.001897132263692037548, 0.015703476623777332805, 0.085263653984348167225, 0.27486427411742569982, 0.34006034727733425171, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4.4090854418790210764e-09, 8.1360026955471610933e-06, 0.00038848261944930331932, 0.0074310477767932352905, 0.07805738431434718072, 0.38159617170452009294, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.2338141566056994185e-05, 0.0035323051795402063933, 0.11766568723732878654, ]).reshape((20, 12, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=5 +df=None +intercept=TRUE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([]) +output=np.array([0.9983344440741356296, 0.99750249875031249402, 0.99625562078283180778, 0.99438764201972595913, 0.99159092854883290613, 0.98740766028786153274, 0.98115924126864673127, 0.97184596123454425332, 0.95800877113085403103, 0.93754892830310510021, 0.90751599227918267054, 0.86391429083558635149, 0.801669064575886825, 0.71507663977921398502, 0.59936827269939108032, 0.45433823528182060159, 0.29067165046987419874, 0.13661155030676189193, 0.033621821670569602969, 0.0012124176758172098417, 0.0016644455553086624083, 0.002495003748750156472, 0.0037387626499230611904, 0.0055997301828166279672, 0.0083806908754831561242, 0.012528591196985617434, 0.018697687754151010031, 0.027833351892417868001, 0.041273795716988054272, 0.060850651795732749183, 0.088929278684076601413, 0.12824165844093327049, 0.18119239198615591513, 0.2480374111869024234, 0.32305865186741777872, 0.38825858275226748928, 0.40740939128236214328, 0.33403355026188807919, 0.1632256493056772062, 0.017159494075893101661, 1.1100003703292180217e-06, 2.4962518746875000594e-06, 5.6123532398144536609e-06, 1.2613583192428893271e-05, 2.8332643039885458129e-05, 6.3586947395334136954e-05, 0.00014252672253270057788, 0.00031885525421459126778, 0.00071127791904317637373, 0.0015797796625579053637, 0.0034857420363066235133, 0.0076146085944587566657, 0.016381164929213501424, 0.034414525059745272595, 0.069651262704549549154, 0.13271586265443335861, 0.22841224706537738287, 0.32670272008482859061, 0.31696810306481593145, 0.097144158424494309045, 3.7012349794238681896e-10, 1.2487503125000001559e-09, 4.2124242480468747114e-09, 1.4206263137512205132e-08, 4.7892153138227467571e-08, 1.6136291046154529314e-07, 5.4321868305356652586e-07, 1.8263821320052253243e-06, 6.1287830369107454558e-06, 2.0506795807293100125e-05, 6.8314944883560930534e-05, 0.00022606641535874693596, 0.00074049070575379688161, 0.0023874614910316710632, 0.0075083864312185822493, 0.022682692646808663012, 0.064029150684570476648, 0.15976638757864897178, 0.30776038811264622153, 0.27497860584540806395, 6.1707818930041155992e-14, 3.1234375000000000385e-13, 1.5808447265625000092e-12, 8.0000230407714837838e-12, 4.0477309670448300476e-11, 2.0474318975195293786e-10, 1.0351972331039468262e-09, 5.2306989582536832363e-09, 2.6404574434177521861e-08, 1.3309725534797475592e-07, 6.6943159388078163953e-07, 3.3557879908853077946e-06, 1.6736492419104248054e-05, 8.2813468459374991711e-05, 0.00040470096744437702128, 0.0019383686901439161829, 0.0089744140037595811904, 0.039065023078631577746, 0.14941007561236896439, 0.3891805482645412928, 4.1152263374485595055e-18, 3.1249999999999996265e-17, 2.3730468749999997491e-16, 1.802032470703124905e-15, 1.3684184074401855573e-14, 1.0391427281498912374e-13, 7.8909900918882334723e-13, 5.9922206010276265389e-12, 4.550342518905353542e-11, 3.4554163502937537769e-10, 2.6239567910043193503e-09, 1.9925671881689045749e-08, 1.5131057085157624606e-07, 1.1490146474041569126e-06, 8.7253299787253137094e-06, 6.625797452594535961e-05, 0.00050314649405639756945, 0.0038207686892407699206, 0.02901396223392209775, 0.22032477571384589954, ]).reshape((20, 6, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=5 +df=None +intercept=TRUE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([100, ]) +output=np.array([0.95099004990000002291, 0.92721650236562502823, 0.89244986942880866199, 0.84226263493375552738, 0.77123895238719930578, 0.67376233787836592448, 0.54625869959414907751, 0.39186905799172611076, 0.22752066204261220395, 0.088384183391962217735, 0.013598650651405662371, 4.4880894773220947292e-05, 0, 0, 0, 0, 0, 0, 0, 0, 0.048976959490485305615, 0.072709651432435309926, 0.10738526002140330595, 0.15737069698548675212, 0.22795032016720712109, 0.32446067835465053353, 0.44989711207706667428, 0.59997610680291524332, 0.75567735422921566979, 0.87844628783911327119, 0.92474207754597603781, 0.89365801028359981295, 0.82931282542333117913, 0.73973445494401424138, 0.62003614417178387619, 0.47000507098119359561, 0.30069481083090426887, 0.14132229342078814205, 0.034781194831623722663, 0.0012542251818798723622, 3.2979557543950620822e-05, 7.3809001036874996929e-05, 0.00016474549918236330078, 0.00036624856893145208737, 0.00080932434818232947688, 0.0017723123294799305975, 0.003828742087843573557, 0.008104291378262778317, 0.016639190251049165714, 0.032657698828719619599, 0.060108147688838667322, 0.10184799113601375464, 0.15884341152280503917, 0.23108234071251923525, 0.31281804868450863166, 0.38543973833058026157, 0.4110892044013776947, 0.34067876601502938838, 0.16765476842547211156, 0.017707951623962527032, 1.1050122962962964101e-08, 3.7191558750000007188e-08, 1.250033797265625178e-07, 4.1927333935913091575e-07, 1.401894586697731242e-06, 4.665382495865281394e-06, 1.5415847866808392633e-05, 5.0391939592239989756e-05, 0.00016203956276710770662, 0.00050812727751784608765, 0.0015332452896675867124, 0.004365181610267205789, 0.011468673667365519159, 0.027632876244132381638, 0.061266201119033726619, 0.12400124625180757032, 0.22211304163999795458, 0.32622078746654581405, 0.32211683874203467237, 0.099883337969340235674, 1.8476543209876543964e-12, 9.3431250000000011463e-12, 4.7218886718750000078e-11, 2.3843292297363282786e-10, 1.2024140499687195818e-09, 6.0518902752095459008e-09, 3.0369400855124124217e-08, 1.5170773682471650721e-07, 7.5254925311084902029e-07, 3.6922964379636862066e-06, 1.7800105408249686863e-05, 8.3338305189489776193e-05, 0.00037055336224994447902, 0.0015169299478213021069, 0.0056546686833628886926, 0.019188949419050076173, 0.058577982030935032975, 0.15402658068596292162, 0.30726533809094308536, 0.28101637370320353693, 1.2345679012345678054e-16, 9.3749999999999994959e-16, 7.1191406249999982613e-15, 5.4060974121093752673e-14, 4.1052552223205572084e-13, 3.1174281844496722735e-12, 2.3672970275664694964e-11, 1.7976661803082883009e-10, 1.3651027556716062823e-09, 1.0366249050881264123e-08, 7.8718703730129575545e-08, 5.9777015645067147174e-07, 4.5359107007994105463e-06, 3.3361176067584402466e-05, 0.00022366759792994563949, 0.0013435210788023243395, 0.0072639461407535297829, 0.035100831436999477275, 0.14396679069931464512, 0.39291034738734598175, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.1354749159583518215e-10, 3.6975445151343504115e-08, 1.2697433810604620809e-06, 2.1473938565867883887e-05, 0.00026101495603127997146, 0.0026507409746741200131, 0.024215069210611606804, 0.20722776413426768904, ]).reshape((20, 7, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=5 +df=None +intercept=TRUE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([1000, ]) +output=np.array([0.9950099900049993451, 0.99252246627530493761, 0.98880051122183698631, 0.98323852246469989336, 0.9749424948799998436, 0.96260353805275378214, 0.94432964343891578896, 0.91744015090894337483, 0.87825768212583654737, 0.82200480749416604542, 0.74306451043607213425, 0.63613393199503898146, 0.4991479566148370739, 0.33884847274276985729, 0.17798493325279582389, 0.056116623078022197235, 0.0047585869404442801556, 6.9550902096181903072e-10, 0, 0, 0.0049866811037051986949, 0.0074700487125113432946, 0.011182664341492391802, 0.016723679332538900905, 0.024972650503249212151, 0.037206183352661716113, 0.055244396744596628579, 0.081608715488401706306, 0.11962663350752600344, 0.17331618121340841565, 0.2466772227646655824, 0.34167053826082144363, 0.45378166194157465441, 0.56434225055466613608, 0.6320750091698927875, 0.59733241830569760999, 0.42886959529414492298, 0.2049173244168793484, 0.050432732505854400984, 0.0018186265137258147626, 3.3277811103950621097e-06, 7.4812668695624991679e-06, 1.6811804138396487754e-05, 3.7755607955489316522e-05, 8.4711061600122608767e-05, 0.00018979511914756760698, 0.00042433325892820140772, 0.00094567009442594711366, 0.002097376821719070146, 0.0046178870868948916628, 0.010055306643782090104, 0.021527218530989256778, 0.04489775700844654549, 0.089884991503020608694, 0.16855047321618027434, 0.28372166497555245668, 0.39667928927647067017, 0.39859166318439254173, 0.21962210770558857065, 0.024829927856976751616, 1.1100002962962965174e-09, 3.7443772500000006212e-09, 1.2627790523437500951e-08, 4.2570810898681638324e-08, 1.4343375976686856963e-07, 4.8286151921739802212e-07, 1.6234543349501860428e-06, 5.4478341089133651746e-06, 1.8228467705229433379e-05, 6.0725950389411787269e-05, 0.000200959732568890164, 0.00065830362619350942834, 0.0021228688895969845957, 0.0066792918381076149537, 0.020201657448734186562, 0.057212961493873837338, 0.14427872595983071147, 0.29075824853504678158, 0.36564110074442957021, 0.13330127370825312072, 1.8509876543209877828e-13, 9.3684375000000001865e-13, 4.7411103515625013439e-12, 2.3989256927490236273e-11, 1.2134982390689849712e-10, 6.1360608361896876588e-10, 3.1008571052567070342e-09, 1.5656143551154886378e-08, 7.8940702751398238619e-08, 3.9721851623374797589e-07, 1.9925510408963188817e-06, 9.9478099413657914188e-06, 4.930161383220328208e-05, 0.00024154631749370003959, 0.0011617509224607792256, 0.0054175582232760775836, 0.023904363046940359239, 0.094270457100450164023, 0.27882003179675446392, 0.34581727191398570209, 1.2345679012345680828e-17, 9.3750000000000019611e-17, 7.1191406250000002335e-16, 5.4060974121093743207e-15, 4.1052552223205574609e-14, 3.1174281844496730813e-13, 2.3672970275664701427e-12, 1.7976661803082880424e-11, 1.3651027556716061272e-10, 1.0366249050881260814e-09, 7.8718703730129572237e-09, 5.9777015645067147174e-08, 4.5393171255472860584e-07, 3.4470439422124707377e-06, 2.6175989936175949598e-05, 0.00019877392357783613304, 0.0015094394821691928168, 0.011462306067722308894, 0.084705097520176186876, 0.41086218643981919918, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00077892972719669731786, 0.083370713567239546071, ]).reshape((20, 7, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=5 +df=None +intercept=TRUE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([10, 100, 1000, ]) +output=np.array([0.59048999999999984833, 0.44370531250000000423, 0.27958155273437496069, 0.12762313629150390248, 0.029345096578598028197, 0.00080668454080820085113, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.40055561099999992258, 0.53723465540624992798, 0.68096479632714856933, 0.79404388738027953387, 0.82432650645400162848, 0.74772850370839760714, 0.60695411066016569102, 0.43541006443525137604, 0.25280073560290239332, 0.098204648213291390046, 0.015109611834895182725, 4.9867660859134372328e-05, 0, 0, 0, 0, 0, 0, 0, 0, 0.0089449327889999999397, 0.01902900664771874778, 0.039353322248692389207, 0.078015642723590794549, 0.14535820079903546964, 0.24864829948443537, 0.38546024005089984943, 0.54588573189455047441, 0.70480915137930777448, 0.81344804238272472308, 0.81717844525199323513, 0.71389962178539645432, 0.56021095018500233209, 0.38030131620961826755, 0.19975862317934431345, 0.062981619616186521049, 0.0053407260835513798575, 7.8059373845321992395e-10, 0, 0, 9.4545814444444459148e-06, 3.1017290343749996553e-05, 0.00010028811495410157556, 0.00031713361145809936415, 0.00096922483761113851879, 0.0028119072707210087531, 0.0075647083349296134064, 0.01861553313384527869, 0.042046394339120052308, 0.087124325583113268467, 0.16371060089498334911, 0.27411331174625735985, 0.40781324509205862938, 0.54286075051770132927, 0.63352683070691229172, 0.61289306201898841042, 0.44453962951650222157, 0.21269241367644950436, 0.052346279846925344859, 0.0018876298723944570646, 1.6294444444444447802e-09, 8.1548437499999982349e-09, 4.0568422851562507446e-08, 1.9994451278686527012e-07, 9.7096128099918361425e-07, 4.602189952521174856e-06, 2.0919648984453888767e-05, 8.8510989072612499115e-05, 0.0003426071500521665281, 0.0012159913347531664096, 0.0039613824662355322237, 0.011728070771626651625, 0.030981021316488138728, 0.072628957837475555115, 0.15091202659488145432, 0.27128094978421118944, 0.39491276471324787689, 0.40566968711467132902, 0.22597501897826155481, 0.025700635234072819607, 1.1111111111111111028e-13, 8.4374999999999991361e-13, 6.4072265625000016033e-12, 4.8654876708984379097e-11, 3.694729700088501736e-10, 2.8056853660047051398e-09, 2.1305018189503776537e-08, 1.5953977978988917004e-07, 1.1111370996233737328e-06, 6.9846696024166045466e-06, 3.9856249948076781855e-05, 0.00020802815256623063945, 0.00098445759075916142167, 0.0041227618062229087065, 0.015186511992247679614, 0.04905127538388008579, 0.1347633037922978394, 0.28642046903795781443, 0.37096041450757122337, 0.1373866644432741313, 0, 0, 0, 0, 0, 0, 2.1835286481805527197e-15, 7.5005881261891668233e-12, 3.9151793493690686266e-10, 7.8165151445884371071e-09, 1.0330194469679949402e-07, 1.0998832941312460716e-06, 1.0325449816590390154e-05, 8.6094485881001237893e-05, 0.00061191613127527461416, 0.0037238993946882535668, 0.01960252770274439893, 0.08667615291637777164, 0.27442290749348607903, 0.35255941616703945218, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3.6587525069769108936e-10, 1.1914310104321792976e-07, 4.09139533897260065e-06, 6.9193802045574309841e-05, 0.00084104819165634655664, 0.0085412764739499439509, 0.075516449446559150149, 0.39909494071597967357, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00077892972719669731786, 0.083370713567239546071, ]).reshape((20, 9, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=5 +df=12 +intercept=FALSE +Boundary.knots=None +knots=None +output=np.array([0, 0.66169375447141842717, 0.42704385876993139481, 0.10949465799552411671, 0.0045536628406788173459, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.16320829536765205092, 0.50699791406824767925, 0.63821768315482607647, 0.43263056231744068114, 0.15013545271065373288, 0.016177354520514077713, 1.5876171140511428811e-06, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0058674236731072158813, 0.063738396787633516682, 0.24043272488013067711, 0.50054000504763473955, 0.64199088129854386953, 0.51113227122624471654, 0.23070045750246975791, 0.045936684143309251815, 0.00066416458897031876996, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3.5532476724270158346e-05, 0.0011936972661650952464, 0.011779052740953399256, 0.061287867695344819263, 0.20002288232936923928, 0.43156920172035251326, 0.62168249332663905182, 0.58254996098081013312, 0.32664310035477628347, 0.092349295039142950681, 0.0054390297948912662632, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3.1496907292528123154e-08, 3.0758698527859495562e-06, 7.5879789673663857776e-05, 0.00098724833216487398006, 0.0078266015648352053879, 0.040722255850196634186, 0.14383543945950985621, 0.34844598770889789741, 0.57762867947116447453, 0.6345732251821071257, 0.43704729558185051452, 0.16650826117204259313, 0.023068804299786735412, 3.4807107343935620814e-05, 0, 0, 0, 0, 0, 0, 0, 0, 1.4388921206346279741e-09, 6.5376673591293467664e-07, 2.4182089760364024493e-05, 0.00039880176232783617072, 0.0037728522997899590664, 0.022917112728778440273, 0.09334968530661211239, 0.26084062164632215719, 0.49935247038577756928, 0.64262810933455249973, 0.53564397016856835076, 0.2604583835482605636, 0.059387695355091404958, 0.0015752311746957685552, 0, 0, 0, 0, 0, 0, 0, 0, 6.8376488468020759222e-12, 1.1492036416820246223e-07, 7.1697944771843335622e-06, 0.00015024167017123804383, 0.0017124892221411901899, 0.012184251164569406822, 0.05741986723560143363, 0.1846190190189749003, 0.40690335279758527154, 0.61033896958284106216, 0.60106063282500987732, 0.35935886624758728303, 0.11099693368003141214, 0.0086311215629592420023, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.2768033036904166236e-08, 1.8810563357318595251e-06, 5.2605966584901652059e-05, 0.00074031169779739149084, 0.0062001835283552559838, 0.03359211253079281978, 0.12126275319647328299, 0.28972724543117178708, 0.43422014732068858756, 0.34126033432252839139, 0.077899048558433395262, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.0012735173756063062e-09, 1.0253040817926208576e-06, 4.44269427274169616e-05, 0.0007905173401505205099, 0.0078092535818893079463, 0.047648780279836128182, 0.17901740350372433164, 0.37155904838956399505, 0.26547319923364387506, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3.3473917264272251468e-12, 1.2428631162803442157e-06, 9.5832983192035734268e-05, 0.0021733294132454694138, 0.025265394711489429919, 0.1581848201187764924, 0.40157681487049512459, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2.3166956453278957354e-06, 0.00056295704181467877848, 0.017992654275869164604, 0.22701602442886983924, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6.2092132305915514147e-06, 0.019403791345598601914, 1, ]).reshape((20, 12, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=5 +df=None +intercept=FALSE +Boundary.knots=None +knots=np.array([]) +output=np.array([0, 0.0011272234177996938269, 0.0028142442804627715303, 0.0053362072774053633667, 0.0090999196124958610377, 0.014702372431044495246, 0.023009568696928141274, 0.035255048800207078319, 0.053144756365466998271, 0.078922539871719557536, 0.11527760116980134697, 0.16482753559964863355, 0.22865514515079901625, 0.30306893078627178406, 0.37385911082806172478, 0.40954833229285447782, 0.36355794566479110452, 0.2119513600790149388, 0.041217298467029310494, 0, 0, 5.0882687398560041373e-07, 3.1769391294621280289e-06, 1.1451280924188917779e-05, 3.3428733100138665235e-05, 8.7761935886847988286e-05, 0.00021681208262686383053, 0.00051561316170019592855, 0.0011946804469067555735, 0.0027131220507094727483, 0.0060506596144855023106, 0.013230141811374926397, 0.028210083582453096551, 0.058035333309565624582, 0.11300958063559926603, 0.20116335451605230067, 0.30568795867586873172, 0.33877798094471850421, 0.16475763686175207146, 0, 0, 1.1484182443411814437e-10, 1.7931887260774516498e-09, 1.2286988490864389756e-08, 6.1400553206305291637e-08, 2.6193586874264870438e-07, 1.0214767558696939837e-06, 3.7704802796487805225e-06, 1.3428054504627923681e-05, 4.6634530984498030184e-05, 0.00015879269432593164958, 0.00053096908751411363639, 0.00174019442073816092, 0.0055566565395111476577, 0.017080184681265514479, 0.049404053208565550104, 0.12851476524402274948, 0.27074730808567093465, 0.32929231067852438031, 0, 0, 1.2959854631941128047e-14, 5.06072933143619642e-13, 6.5918427455453850986e-12, 5.6389033989814727996e-11, 3.9088927700060016774e-10, 2.406265255469648607e-09, 1.378603437152614992e-08, 7.5464802427343835863e-08, 4.0078909822273000137e-07, 2.0836670196190539855e-06, 1.0654767572225721294e-05, 5.3673655611779830157e-05, 0.00026601408260545672708, 0.0012907432586925205419, 0.0060666130749972404027, 0.027014549341864656923, 0.10818900424286860551, 0.32906949849914446382, 0, 0, 5.8500579526198340832e-19, 5.7129472193553077444e-17, 1.4145822896898457119e-15, 2.0714622186680568112e-14, 2.3333104795078233906e-13, 2.2673496764008742317e-12, 2.0162390952550372537e-11, 1.6964293385718098169e-10, 1.3777936465799164788e-09, 1.0936695210263550545e-08, 8.5522170452256458058e-08, 6.6219297623306537514e-07, 5.0939619277349284707e-06, 3.9016396858695978102e-05, 0.00029798198173219142288, 0.00227144600780565184, 0.017292671490362138825, 0.13153873483331313121, 1, ]).reshape((20, 5, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=5 +df=None +intercept=FALSE +Boundary.knots=None +knots=np.array([100, ]) +output=np.array([0, 0.024987397851780435848, 0.061486796626462968118, 0.1140799960900419352, 0.1882939537142028219, 0.28966625638367565765, 0.42117968175620157378, 0.57798465087862005429, 0.73943782746930653005, 0.86397935690336380432, 0.90462871246453147034, 0.85976637084822715718, 0.77601114642224255924, 0.66267521310641597232, 0.51785842958629058064, 0.34911766989097126057, 0.18104199448456753663, 0.055522321426452851678, 0.0043174157141209739547, 0, 0, 1.1333836374491041766e-05, 7.0253868335539153452e-05, 0.00025049169236306427153, 0.00071939598049462782393, 0.0018428967293926601032, 0.0043879998552115674279, 0.0098727402942039785283, 0.021048289930652556295, 0.042207103219050953746, 0.078361329513138483494, 0.1323267251748408424, 0.20305646979998087653, 0.28625091024051202426, 0.36712456913477936604, 0.41237454577086030127, 0.37209382828918063923, 0.21926721332006066101, 0.042943027456719351509, 0, 0, 2.5642163564224008165e-09, 3.9893896948733327568e-08, 2.7186958324120860093e-07, 1.3475047468249140318e-06, 5.6780166980285093331e-06, 2.1734507210374597486e-05, 7.8000238621073664019e-05, 0.00026616938183067457386, 0.00086607259863206911138, 0.0026688434677071591963, 0.0076602480569788727188, 0.020032890189762748295, 0.047362176442216685768, 0.10112516340575794516, 0.19128545657973258787, 0.30258229747242648688, 0.34436724521558481626, 0.17045464690987927048, 0, 0, 2.8979008849349871451e-13, 1.1299684644739179399e-11, 1.4686295227238142049e-10, 1.2521970298985838129e-09, 8.6372943219355255736e-09, 5.2772400925513216102e-08, 2.9891245041530529781e-07, 1.607880484564848822e-06, 8.3111564072833673416e-06, 4.1402961295506068027e-05, 0.00019754788193526286806, 0.00088468396831814228969, 0.0036015013400145573161, 0.013149579882492583999, 0.042768561910798960635, 0.12037399719492403172, 0.26730426029673903798, 0.33672081019045274619, 0, 0, 1.309371682920953332e-17, 1.2786832841024935257e-15, 3.1661464010829005262e-14, 4.6363882090260461786e-13, 5.2224622287067364928e-12, 5.0748274386406234902e-11, 4.5127867086219768747e-10, 3.7969821085404869e-09, 3.0838053235562167103e-08, 2.44787301750460405e-07, 1.9141743408195724709e-06, 1.4809071760067401229e-05, 0.00011002044182894339316, 0.0007361307065949982114, 0.0043501410333869746858, 0.022648326644076191561, 0.10074752233050462968, 0.32871166293410319925, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5.4793570769921117731e-10, 1.7842901170031562027e-07, 6.1272840845677704696e-06, 0.00010362481425005589904, 0.0012595559148250148798, 0.012791437410658173385, 0.11685243679472454015, 1, ]).reshape((20, 6, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=5 +df=None +intercept=FALSE +Boundary.knots=None +knots=np.array([1000, ]) +output=np.array([0, 0.0024988701975066367374, 0.0062335737743966241481, 0.011805108206123089004, 0.020094017057672219906, 0.032374436158623724757, 0.050454096263104174225, 0.076816980711751164934, 0.11469423978741608017, 0.16787638509201657788, 0.23985925947403505254, 0.33155764168655321722, 0.4364690436594241274, 0.53267348082579712987, 0.57514542430970139186, 0.50463302930351572329, 0.30623588293439429897, 0.096587849561305616497, 0.0075106712808647091081, 0, 0, 1.1282962103271197581e-06, 7.0417854820895302466e-06, 2.536640667453833115e-05, 7.3981096505374880712e-05, 0.00019395448667024030114, 0.00047814948330325205252, 0.0011335173229715391711, 0.0026138368581788955919, 0.0058931764589364287604, 0.012998501527337540801, 0.027945386445582046098, 0.058044007669012950834, 0.1145680954987259581, 0.2086069927114643785, 0.33148565972609811414, 0.41061823564260202524, 0.3066625410662744966, 0.068889778730265194273, 0, 0, 2.5469057156714312774e-10, 3.976025713192789869e-09, 2.7235422387831816846e-08, 1.3603757883811768205e-07, 5.7993308882550318022e-07, 2.2591989366454093128e-06, 8.3259563410340815473e-06, 2.9580849000601624262e-05, 0.00010235971125482330811, 0.00034661758311907198181, 0.001149214388416119545, 0.0037170166582407206807, 0.011623043605661884797, 0.034525979049628140183, 0.094171296281739258482, 0.21954225794050497012, 0.36514412761590397949, 0.24346326935859208263, 0, 0, 2.8744101198050118059e-14, 1.1223436953991581798e-12, 1.4617253735361878953e-11, 1.2501806315302350017e-10, 8.6638386346496238246e-10, 5.3311050540562872207e-09, 3.0523721489433262118e-08, 1.6692682142232341016e-07, 8.8525020719146049419e-07, 4.5921420319874677743e-06, 2.3401813204582281116e-05, 0.0001172621098580812533, 0.00057627166059595505247, 0.0027575294458836020588, 0.012651024092369157759, 0.053782977897194939043, 0.19324936944781076487, 0.3997562713358867037, 0, 0, 1.2975755416333770318e-18, 1.2671636148763449243e-16, 3.1376225596317031531e-15, 4.5946189458816680778e-14, 5.1754130194391066624e-13, 5.0291082725267428713e-12, 4.4721309725082660758e-11, 3.762775062517599803e-10, 3.0560232936142684245e-09, 2.4258201074369941878e-08, 1.8969295269383146249e-07, 1.4687810219326831175e-06, 1.1298692185571222767e-05, 8.6540548310009559815e-05, 0.00066094068550206401882, 0.0050381941644688631871, 0.038356111609708157251, 0.27103704347500323646, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0093429658193878890871, 1, ]).reshape((20, 6, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=5 +df=None +intercept=FALSE +Boundary.knots=None +knots=np.array([10, 100, 1000, ]) +output=np.array([0, 0.24594066521407775827, 0.51146600459087232515, 0.73649217207800155016, 0.8374180350990879651, 0.77783093616193677011, 0.63185158416405007298, 0.45327074014730833751, 0.26317071169481792703, 0.10223303781294215686, 0.015729413486628138208, 5.1913250044765826493e-05, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0026391300640233733565, 0.015039867450995366219, 0.047247102051768179176, 0.1123025082166889399, 0.21868817428784292911, 0.36168436874353226962, 0.52963938325215309533, 0.69654238826126158024, 0.81185888378284087885, 0.81901416673831617388, 0.71604356256126133751, 0.5618949499117826818, 0.38144450577487010179, 0.20035909960120826256, 0.06317094299551503922, 0.0053567803596460189172, 7.8294021104867289565e-10, 0, 0, 0, 1.3617399508643758347e-06, 2.0307441416267721758e-05, 0.00012974796415461092966, 0.00058265627417901637731, 0.0021107453507099383297, 0.0064420295146436082692, 0.01698600253976614155, 0.039859183304507203593, 0.084333549165298365979, 0.1600060050847842974, 0.26809274258076365438, 0.39566435336691235802, 0.51703688602850017553, 0.58200587206136744634, 0.52329606670761874554, 0.32126381870611603331, 0.10151738768556310688, 0.0078939921772932797328, 0, 0, 1.5649080494945798507e-10, 5.9986253804949622248e-09, 7.5940397022685528773e-08, 6.2142631098330448954e-07, 4.0139943226430085122e-06, 2.1989865743143280786e-05, 0.00010363219420155694861, 0.00042588199885955281988, 0.0015624557228769457226, 0.0051797373818038370402, 0.015437236122329209276, 0.040650688803865277221, 0.093964606272201794956, 0.18957613958735397564, 0.32176934741298385267, 0.41523761089925581569, 0.31715186300322989466, 0.072004316292680670131, 0, 0, 7.1504090682135632783e-15, 6.9828213556773098054e-13, 1.7290156975971226543e-11, 2.531906923450678459e-10, 2.8519588261786051741e-09, 2.7712025453436415246e-08, 2.4184791568371559048e-07, 1.8337667890099757592e-06, 1.2054075181315261422e-05, 7.0420380839424076883e-05, 0.00037180990877366712185, 0.0017643270358445378374, 0.0073398980933030329166, 0.026537861233464601213, 0.082516974679995302999, 0.20957251000715282352, 0.36763462897045218192, 0.25222621956325630421, 0, 0, 0, 0, 0, 0, 0, 5.430767431219823664e-15, 1.8655102027007631066e-11, 9.7376457669355941836e-10, 1.9440860511832082848e-08, 2.5692762827202482626e-07, 2.7355768273926624709e-06, 2.5679592827130744701e-05, 0.00021368415859150435886, 0.0015066158869563137275, 0.0090029382862195743431, 0.045606751586747915073, 0.18361012124256628764, 0.40566571262016642985, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.2887678100169456754e-09, 4.196725335132502196e-07, 1.441162964935832764e-05, 0.00024372991766721753461, 0.0029625284410813028553, 0.030085998315248142776, 0.25286679352721525005, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0093429658193878890871, 1, ]).reshape((20, 8, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=5 +df=12 +intercept=FALSE +Boundary.knots=np.array([0, 3000, ]) +knots=None +output=np.array([0.59169275909036811445, 0.45594291761992611356, 0.23025182795481774489, 0.058881690084655928519, 0.00244877119161214735, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.2905201731274964505, 0.4652923293619554701, 0.60774274744642686752, 0.58452788522997400911, 0.36691850516129698168, 0.12666647389296178949, 0.013648531489621140711, 1.3394428704094372146e-06, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.021589057498422929704, 0.061252310080865124409, 0.15611979121414976124, 0.33262545668279458466, 0.54628842278228206819, 0.6385151816856337037, 0.49255505710881447579, 0.221198927694986891, 0.044044707273317475205, 0.00063680989274803034839, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00027107258187882916, 0.00127840807191650788, 0.0057589114783163615832, 0.023748086219301876854, 0.082775728340449605813, 0.22525005798130448564, 0.44911867244320990977, 0.62614581126197998984, 0.57974912164267822234, 0.32404333353141845375, 0.091606580575315788018, 0.0053952866770240375319, 0, 0, 0, 0, 0, 0, 0, 0, 4.9568448953450556364e-07, 3.7641040924026516272e-06, 2.8583665451682636297e-05, 0.00021688034438166792803, 0.0015679187576233750197, 0.0095441043435020560953, 0.04427882227566239115, 0.1488738995058955239, 0.35313880391702157091, 0.58025580099074469675, 0.63531593964593435775, 0.4370910386997177155, 0.16650826117204259313, 0.023068804299786735412, 3.4807107343935620814e-05, 0, 0, 0, 0, 0, 0, 0, 0, 1.4388921206346279741e-09, 6.5376673591293467664e-07, 2.4182089760364024493e-05, 0.00039880176232783617072, 0.0037728522997899590664, 0.022917112728778440273, 0.09334968530661211239, 0.26084062164632215719, 0.49935247038577756928, 0.64262810933455249973, 0.53564397016856835076, 0.2604583835482605636, 0.059387695355091404958, 0.0015752311746957685552, 0, 0, 0, 0, 0, 0, 0, 0, 6.8376488468020759222e-12, 1.1492036416820246223e-07, 7.1697944771843335622e-06, 0.00015024502361066615209, 0.0017129832691462772674, 0.012198067843520864206, 0.057614376649993519208, 0.18625055189529041155, 0.41578120601587292837, 0.64273379913532080465, 0.68051701302793721204, 0.48636048533160558538, 0.22961899064651025704, 0.056512123157649481187, 0.0020378520142550187594, 0, 0, 0, 0, 0, 0, 0, 0, 9.4145936087959968535e-09, 1.3870093306447404973e-06, 3.87897484409095467e-05, 0.00054627415024945797078, 0.0045890968808638254312, 0.025078293403640077724, 0.092478958938429417502, 0.23258667138901650828, 0.39413899790146145197, 0.42298881551441958049, 0.23945155313138169473, 0.027468762021704565962, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5.4046605238618360691e-10, 5.5343723764345201347e-07, 2.3980715961026268597e-05, 0.00042724725529509507927, 0.004257128234965919765, 0.026669687498425763417, 0.10780673176995581031, 0.27416234388481963702, 0.37835275864003403701, 0.14369344182750692918, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.2897006858339270209e-12, 4.7885683674533647596e-07, 3.6923035679543052192e-05, 0.00083835438251815758755, 0.0099780154986416052382, 0.068735165020702704286, 0.25981214905110344704, 0.35274625004443893594, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5.7834701086365511565e-07, 0.00014053832363986818919, 0.0044940505180239382829, 0.063888867507214189279, 0.37188043953033556033, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6.344155240374716805e-07, 0.0019825485126170991519, 0.10217325456175885279, ]).reshape((20, 12, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=5 +df=None +intercept=FALSE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([]) +output=np.array([0.0016644455553086624083, 0.002495003748750156472, 0.0037387626499230611904, 0.0055997301828166279672, 0.0083806908754831561242, 0.012528591196985617434, 0.018697687754151010031, 0.027833351892417868001, 0.041273795716988054272, 0.060850651795732749183, 0.088929278684076601413, 0.12824165844093327049, 0.18119239198615591513, 0.2480374111869024234, 0.32305865186741777872, 0.38825858275226748928, 0.40740939128236214328, 0.33403355026188807919, 0.1632256493056772062, 0.017159494075893101661, 1.1100003703292180217e-06, 2.4962518746875000594e-06, 5.6123532398144536609e-06, 1.2613583192428893271e-05, 2.8332643039885458129e-05, 6.3586947395334136954e-05, 0.00014252672253270057788, 0.00031885525421459126778, 0.00071127791904317637373, 0.0015797796625579053637, 0.0034857420363066235133, 0.0076146085944587566657, 0.016381164929213501424, 0.034414525059745272595, 0.069651262704549549154, 0.13271586265443335861, 0.22841224706537738287, 0.32670272008482859061, 0.31696810306481593145, 0.097144158424494309045, 3.7012349794238681896e-10, 1.2487503125000001559e-09, 4.2124242480468747114e-09, 1.4206263137512205132e-08, 4.7892153138227467571e-08, 1.6136291046154529314e-07, 5.4321868305356652586e-07, 1.8263821320052253243e-06, 6.1287830369107454558e-06, 2.0506795807293100125e-05, 6.8314944883560930534e-05, 0.00022606641535874693596, 0.00074049070575379688161, 0.0023874614910316710632, 0.0075083864312185822493, 0.022682692646808663012, 0.064029150684570476648, 0.15976638757864897178, 0.30776038811264622153, 0.27497860584540806395, 6.1707818930041155992e-14, 3.1234375000000000385e-13, 1.5808447265625000092e-12, 8.0000230407714837838e-12, 4.0477309670448300476e-11, 2.0474318975195293786e-10, 1.0351972331039468262e-09, 5.2306989582536832363e-09, 2.6404574434177521861e-08, 1.3309725534797475592e-07, 6.6943159388078163953e-07, 3.3557879908853077946e-06, 1.6736492419104248054e-05, 8.2813468459374991711e-05, 0.00040470096744437702128, 0.0019383686901439161829, 0.0089744140037595811904, 0.039065023078631577746, 0.14941007561236896439, 0.3891805482645412928, 4.1152263374485595055e-18, 3.1249999999999996265e-17, 2.3730468749999997491e-16, 1.802032470703124905e-15, 1.3684184074401855573e-14, 1.0391427281498912374e-13, 7.8909900918882334723e-13, 5.9922206010276265389e-12, 4.550342518905353542e-11, 3.4554163502937537769e-10, 2.6239567910043193503e-09, 1.9925671881689045749e-08, 1.5131057085157624606e-07, 1.1490146474041569126e-06, 8.7253299787253137094e-06, 6.625797452594535961e-05, 0.00050314649405639756945, 0.0038207686892407699206, 0.02901396223392209775, 0.22032477571384589954, ]).reshape((20, 5, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=5 +df=None +intercept=FALSE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([100, ]) +output=np.array([0.048976959490485305615, 0.072709651432435309926, 0.10738526002140330595, 0.15737069698548675212, 0.22795032016720712109, 0.32446067835465053353, 0.44989711207706667428, 0.59997610680291524332, 0.75567735422921566979, 0.87844628783911327119, 0.92474207754597603781, 0.89365801028359981295, 0.82931282542333117913, 0.73973445494401424138, 0.62003614417178387619, 0.47000507098119359561, 0.30069481083090426887, 0.14132229342078814205, 0.034781194831623722663, 0.0012542251818798723622, 3.2979557543950620822e-05, 7.3809001036874996929e-05, 0.00016474549918236330078, 0.00036624856893145208737, 0.00080932434818232947688, 0.0017723123294799305975, 0.003828742087843573557, 0.008104291378262778317, 0.016639190251049165714, 0.032657698828719619599, 0.060108147688838667322, 0.10184799113601375464, 0.15884341152280503917, 0.23108234071251923525, 0.31281804868450863166, 0.38543973833058026157, 0.4110892044013776947, 0.34067876601502938838, 0.16765476842547211156, 0.017707951623962527032, 1.1050122962962964101e-08, 3.7191558750000007188e-08, 1.250033797265625178e-07, 4.1927333935913091575e-07, 1.401894586697731242e-06, 4.665382495865281394e-06, 1.5415847866808392633e-05, 5.0391939592239989756e-05, 0.00016203956276710770662, 0.00050812727751784608765, 0.0015332452896675867124, 0.004365181610267205789, 0.011468673667365519159, 0.027632876244132381638, 0.061266201119033726619, 0.12400124625180757032, 0.22211304163999795458, 0.32622078746654581405, 0.32211683874203467237, 0.099883337969340235674, 1.8476543209876543964e-12, 9.3431250000000011463e-12, 4.7218886718750000078e-11, 2.3843292297363282786e-10, 1.2024140499687195818e-09, 6.0518902752095459008e-09, 3.0369400855124124217e-08, 1.5170773682471650721e-07, 7.5254925311084902029e-07, 3.6922964379636862066e-06, 1.7800105408249686863e-05, 8.3338305189489776193e-05, 0.00037055336224994447902, 0.0015169299478213021069, 0.0056546686833628886926, 0.019188949419050076173, 0.058577982030935032975, 0.15402658068596292162, 0.30726533809094308536, 0.28101637370320353693, 1.2345679012345678054e-16, 9.3749999999999994959e-16, 7.1191406249999982613e-15, 5.4060974121093752673e-14, 4.1052552223205572084e-13, 3.1174281844496722735e-12, 2.3672970275664694964e-11, 1.7976661803082883009e-10, 1.3651027556716062823e-09, 1.0366249050881264123e-08, 7.8718703730129575545e-08, 5.9777015645067147174e-07, 4.5359107007994105463e-06, 3.3361176067584402466e-05, 0.00022366759792994563949, 0.0013435210788023243395, 0.0072639461407535297829, 0.035100831436999477275, 0.14396679069931464512, 0.39291034738734598175, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.1354749159583518215e-10, 3.6975445151343504115e-08, 1.2697433810604620809e-06, 2.1473938565867883887e-05, 0.00026101495603127997146, 0.0026507409746741200131, 0.024215069210611606804, 0.20722776413426768904, ]).reshape((20, 6, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=5 +df=None +intercept=FALSE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([1000, ]) +output=np.array([0.0049866811037051986949, 0.0074700487125113432946, 0.011182664341492391802, 0.016723679332538900905, 0.024972650503249212151, 0.037206183352661716113, 0.055244396744596628579, 0.081608715488401706306, 0.11962663350752600344, 0.17331618121340841565, 0.2466772227646655824, 0.34167053826082144363, 0.45378166194157465441, 0.56434225055466613608, 0.6320750091698927875, 0.59733241830569760999, 0.42886959529414492298, 0.2049173244168793484, 0.050432732505854400984, 0.0018186265137258147626, 3.3277811103950621097e-06, 7.4812668695624991679e-06, 1.6811804138396487754e-05, 3.7755607955489316522e-05, 8.4711061600122608767e-05, 0.00018979511914756760698, 0.00042433325892820140772, 0.00094567009442594711366, 0.002097376821719070146, 0.0046178870868948916628, 0.010055306643782090104, 0.021527218530989256778, 0.04489775700844654549, 0.089884991503020608694, 0.16855047321618027434, 0.28372166497555245668, 0.39667928927647067017, 0.39859166318439254173, 0.21962210770558857065, 0.024829927856976751616, 1.1100002962962965174e-09, 3.7443772500000006212e-09, 1.2627790523437500951e-08, 4.2570810898681638324e-08, 1.4343375976686856963e-07, 4.8286151921739802212e-07, 1.6234543349501860428e-06, 5.4478341089133651746e-06, 1.8228467705229433379e-05, 6.0725950389411787269e-05, 0.000200959732568890164, 0.00065830362619350942834, 0.0021228688895969845957, 0.0066792918381076149537, 0.020201657448734186562, 0.057212961493873837338, 0.14427872595983071147, 0.29075824853504678158, 0.36564110074442957021, 0.13330127370825312072, 1.8509876543209877828e-13, 9.3684375000000001865e-13, 4.7411103515625013439e-12, 2.3989256927490236273e-11, 1.2134982390689849712e-10, 6.1360608361896876588e-10, 3.1008571052567070342e-09, 1.5656143551154886378e-08, 7.8940702751398238619e-08, 3.9721851623374797589e-07, 1.9925510408963188817e-06, 9.9478099413657914188e-06, 4.930161383220328208e-05, 0.00024154631749370003959, 0.0011617509224607792256, 0.0054175582232760775836, 0.023904363046940359239, 0.094270457100450164023, 0.27882003179675446392, 0.34581727191398570209, 1.2345679012345680828e-17, 9.3750000000000019611e-17, 7.1191406250000002335e-16, 5.4060974121093743207e-15, 4.1052552223205574609e-14, 3.1174281844496730813e-13, 2.3672970275664701427e-12, 1.7976661803082880424e-11, 1.3651027556716061272e-10, 1.0366249050881260814e-09, 7.8718703730129572237e-09, 5.9777015645067147174e-08, 4.5393171255472860584e-07, 3.4470439422124707377e-06, 2.6175989936175949598e-05, 0.00019877392357783613304, 0.0015094394821691928168, 0.011462306067722308894, 0.084705097520176186876, 0.41086218643981919918, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00077892972719669731786, 0.083370713567239546071, ]).reshape((20, 6, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=5 +df=None +intercept=FALSE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([10, 100, 1000, ]) +output=np.array([0.40055561099999992258, 0.53723465540624992798, 0.68096479632714856933, 0.79404388738027953387, 0.82432650645400162848, 0.74772850370839760714, 0.60695411066016569102, 0.43541006443525137604, 0.25280073560290239332, 0.098204648213291390046, 0.015109611834895182725, 4.9867660859134372328e-05, 0, 0, 0, 0, 0, 0, 0, 0, 0.0089449327889999999397, 0.01902900664771874778, 0.039353322248692389207, 0.078015642723590794549, 0.14535820079903546964, 0.24864829948443537, 0.38546024005089984943, 0.54588573189455047441, 0.70480915137930777448, 0.81344804238272472308, 0.81717844525199323513, 0.71389962178539645432, 0.56021095018500233209, 0.38030131620961826755, 0.19975862317934431345, 0.062981619616186521049, 0.0053407260835513798575, 7.8059373845321992395e-10, 0, 0, 9.4545814444444459148e-06, 3.1017290343749996553e-05, 0.00010028811495410157556, 0.00031713361145809936415, 0.00096922483761113851879, 0.0028119072707210087531, 0.0075647083349296134064, 0.01861553313384527869, 0.042046394339120052308, 0.087124325583113268467, 0.16371060089498334911, 0.27411331174625735985, 0.40781324509205862938, 0.54286075051770132927, 0.63352683070691229172, 0.61289306201898841042, 0.44453962951650222157, 0.21269241367644950436, 0.052346279846925344859, 0.0018876298723944570646, 1.6294444444444447802e-09, 8.1548437499999982349e-09, 4.0568422851562507446e-08, 1.9994451278686527012e-07, 9.7096128099918361425e-07, 4.602189952521174856e-06, 2.0919648984453888767e-05, 8.8510989072612499115e-05, 0.0003426071500521665281, 0.0012159913347531664096, 0.0039613824662355322237, 0.011728070771626651625, 0.030981021316488138728, 0.072628957837475555115, 0.15091202659488145432, 0.27128094978421118944, 0.39491276471324787689, 0.40566968711467132902, 0.22597501897826155481, 0.025700635234072819607, 1.1111111111111111028e-13, 8.4374999999999991361e-13, 6.4072265625000016033e-12, 4.8654876708984379097e-11, 3.694729700088501736e-10, 2.8056853660047051398e-09, 2.1305018189503776537e-08, 1.5953977978988917004e-07, 1.1111370996233737328e-06, 6.9846696024166045466e-06, 3.9856249948076781855e-05, 0.00020802815256623063945, 0.00098445759075916142167, 0.0041227618062229087065, 0.015186511992247679614, 0.04905127538388008579, 0.1347633037922978394, 0.28642046903795781443, 0.37096041450757122337, 0.1373866644432741313, 0, 0, 0, 0, 0, 0, 2.1835286481805527197e-15, 7.5005881261891668233e-12, 3.9151793493690686266e-10, 7.8165151445884371071e-09, 1.0330194469679949402e-07, 1.0998832941312460716e-06, 1.0325449816590390154e-05, 8.6094485881001237893e-05, 0.00061191613127527461416, 0.0037238993946882535668, 0.01960252770274439893, 0.08667615291637777164, 0.27442290749348607903, 0.35255941616703945218, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3.6587525069769108936e-10, 1.1914310104321792976e-07, 4.09139533897260065e-06, 6.9193802045574309841e-05, 0.00084104819165634655664, 0.0085412764739499439509, 0.075516449446559150149, 0.39909494071597967357, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00077892972719669731786, 0.083370713567239546071, ]).reshape((20, 8, ), order="F") +--END TEST CASE-- +""" +R_bs_num_tests = 72 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/test_splines_crs_data.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/test_splines_crs_data.py new file mode 100644 index 0000000000000000000000000000000000000000..3b85f71d7e896de9b2f102b10dc1f76722146a63 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/test_splines_crs_data.py @@ -0,0 +1,325 @@ +# This file auto-generated by tools/get-R-crs-test-vectors.R +# Using: R version 3.0.3 (2014-03-06) and package 'mgcv' version 1.7.28 +import numpy as np + +R_crs_test_x = np.array( + [ + 1, + -1.5, + 2.25, + -3.375, + 5.0625, + -7.59375, + 11.390625, + -17.0859375, + 25.628906250000000000, + -38.443359375000000000, + 57.665039062500000000, + -86.497558593750000000, + 129.74633789062500000, + -194.6195068359375, + 291.92926025390625000, + -437.89389038085937500, + 656.84083557128906250, + -985.26125335693359375, + 1477.8918800354003906, + -2216.8378200531005859, + ] +) +R_crs_test_data = """ +--BEGIN TEST CASE-- +spline_type=cr +nb_knots=4 +knots=None +absorb_cons=FALSE +output=np.array([-1.693557754132211208e-05, -1.9836972061171899575e-05, -1.4954358368392469422e-05, -2.088026100812221311e-05, -9.5355264085171175196e-06, -1.8699295604068575353e-05, 4.9022718833308546933e-06, 1.7974067511175931267e-05, 3.744122291002612696e-05, 0.0002988262983956019303, 0.00010718085083579747424, 0.001935560671294481172, 0.00024699248283329116715, 0.010566342124751632037, 0.00048044994314723433668, 0.053454984128479515748, 0.00065729103443297996496, 0.25076507420610638643, 0, 1, 0.35560680685948470314, 0.46359416252769836131, 0.30168882277557279581, 0.54466866236250932598, 0.18063664369405590948, 0.72711735964503432239, -0.089776348720933471514, 1.1356863997659447652, -0.68566908660007752641, 2.0361466894716735432, -1.9628257407671605428, 3.9650378336575471394, -4.523225924226894179, 7.8266636243390204086, -8.7985820993738865781, 14.246329329102128014, -12.037110654561336887, 18.944322912930825709, 0, 0, 0.6444562685323340645, 0.53647236902629924504, 0.69836999393477805498, 0.45539628464397530205, 0.81940601333710849641, 0.27293213874197075341, 1.0897461189737138731, -0.13572091900106228457, 1.6852766572444068949, -1.0365718798973906356, 2.9606222279687766097, -2.967335129700412466, 5.5120421008950604147, -6.8380635660933348774, 9.743925990387539926, -13.301405831788731149, 12.784702352769150124, -18.197306344378148424, 0, 0, -4.6139814277377641984e-05, -4.6694581936484837246e-05, -4.3862351982477081188e-05, -4.4066745476440737986e-05, -3.3121504755945730075e-05, -3.0799091401098394798e-05, 2.5327475336172373395e-05, 1.6545167606241587368e-05, 0.00035498813276064257764, 0.00012636412732133810903, 0.0020963319475481821674, 0.00036173537157081639762, 0.010936830849001568516, 0.00083359962956235762136, 0.054175659043200374843, 0.0016215185581219158321, 0.25175101075775591086, 0.0022183572412113072327, 1, 0, ]).reshape((20, 4, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cr +nb_knots=7 +knots=None +absorb_cons=FALSE +output=np.array([-2.9605259404128104445e-07, 4.3004543792069181325e-07, -4.6506508782294522313e-07, 1.2225175036037286749e-06, -4.8490441759023038782e-07, 2.7062259965304665474e-06, 2.8104230735656565092e-07, -5.4449455566502238182e-06, 1.7542735683802410547e-06, -0.00011038827024139799939, 2.8120883750482203265e-06, -0.00053376130083573273665, -7.6784755538918750706e-07, 0.00061879177472234751789, -9.2078635815506674409e-06, 0.029574116402683980898, -1.6901017048743381161e-05, 0.21556638245963724576, 0, 1, 0.00010456869825724268133, -0.00015189629322606839636, 0.00016426557921581520349, -0.00043180524853199072667, 0.00017127302630398999017, -0.000955865732450367038, -9.9266916848531769006e-05, 0.0019305664182940607265, -0.00061962673904836988552, 0.042415216868389754579, -0.00099325736940550032363, 0.27732557133728741317, 0.00027121133522598855859, 1.1504608369631013076, 0.0032523082987030572759, 2.7821404636666882126, 0.0059696060348119403538, 4.1098324719022825136, 0, 0, -0.031642380707528651451, 0.046727930564370717681, -0.049706595580857972083, 0.14260551573254778845, -0.051827041873556585483, 0.44422176162356585838, 0.030038067097830360025, 1.2696071710389067455, 0.18749841492049976188, 2.6526069738107440621, 0.30055865997270758694, 3.4401400654673524038, -0.082068271523342908869, -0.89294447099362916909, -0.98414515128277502143, -10.707999025460104292, -1.8063966557448927208, -19.65451295888456329, 0, 0, 0.9404055233767310007, 1.0229997547271381109, 0.84839014691027592185, 0.9942253298077886603, 0.55270681506501917468, 0.71325376394101502875, -0.27008001161472772189, -0.36441609214674652861, -1.6858466263672904351, -2.2746949537899268101, -2.7024004611201863923, -3.6463202499480562579, 0.73789700429246496416, 0.99563659340566201816, 8.8487029815652924469, 11.939460983544531558, 16.241778413219694954, 21.914859168852931504, 0, 0, 0.091452250263845791256, -0.069826465452058242289, 0.20181123367547218472, -0.13689085681302756714, 0.50012121362724204499, -0.15708533369949770342, 1.2380919977577322655, 0.093217876961678852732, 2.4558884227495125785, 0.58186847095202909319, 3.1248015911458146832, 0.93273112726773044212, -0.80684053529361110524, -0.25468449792074498994, -9.6754590529148973843, -3.0541220021223365322, -17.759287695723489975, -5.6058354437652431201, 0, 0, -0.00032057317842933900735, 0.00025095691201626593508, -0.0006604553857512240455, 0.00049198690620599915858, -0.0011751018630891821651, 0.00056456602826813432217, 0.0020547291059278675364, -0.00033502584436379451204, 0.043190243671805170211, -0.002091240244288253107, 0.27856793393313283858, -0.0033522436217435750035, 1.1501216068412509763, 0.00091533825638770416853, 2.7780724886333088008, 0.010976540508122837117, 4.1023657110424904815, 0.02014742036749034293, 0, 0, 9.0759971803981566744e-07, -7.1050367876085636178e-07, 1.8698667331515860834e-06, -1.392902486538716717e-06, 3.3269224981118857968e-06, -1.5983868974364642471e-06, -5.7964722216058981582e-06, 9.4851778732840647118e-07, -0.00011258250904733756745, 5.9206732932833133743e-06, -0.00053727865043814320746, 9.4907982657877548258e-06, 0.00061975219556745361413, -2.5914854994384806915e-06, 0.029585633563949290115, -3.1076539587733474873e-05, 0.21558752218843252324, -5.7040932539508893209e-05, 1, 0, ]).reshape((20, 7, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cr +nb_knots=10 +knots=None +absorb_cons=FALSE +output=np.array([1.9320747025477182898e-08, 4.8242814281426965595e-08, -1.2568948282371909281e-08, -7.8978523641721503504e-08, -3.5770522726027550527e-08, -7.01473863118866388e-07, 2.1638270976696590321e-08, 2.2109425903379564006e-06, 8.5370349850805669926e-08, 3.744561791897189516e-05, -3.2925418782971613435e-08, -7.9813891850179092256e-05, -1.991767035296446912e-07, -0.0021868285157625511929, 3.7614188014338205365e-08, 0.0021874060835819046644, 4.688717754303082178e-07, 0.15874967738905676473, 0, 1, -1.4544731165165144453e-06, -3.6317372379498608116e-06, 9.4619516292459995175e-07, 5.9455330204143990165e-06, 2.6928184298539113977e-06, 5.2807216744776855019e-05, -1.6289371928530509096e-06, -0.00016644059132742171966, -6.4267121060004543239e-06, -0.002818920227187673988, 2.4786379329293728427e-06, 0.0060407977628119044478, 1.4994097295422416361e-05, 0.20920617714101982787, -2.8316102474873858596e-06, 1.0967921747761912865, -3.5296843934527352639e-05, 2.0750595382021144175, 0, 0, 9.7994633378747003421e-05, 0.00024468706579685965685, -6.3749578484895432179e-05, -0.00040057827261335182721, -0.00018142772925296013898, -0.0035578683345143034648, 0.00010974909140496827962, 0.011347453981486406438, 0.00043299755045772883848, 0.2521011214081396723, -0.00016699739084748591402, 1.1986460188118959191, -0.0010102222245463542399, 2.0307158061521746184, 0.00019077878093656664284, -0.33272379892704945226, 0.0023781128997935555708, -4.1474987648643217852, 0, 0, -0.0066281488228501295526, -0.016550113319571305159, 0.0043118860597063267057, 0.027486913394933615296, 0.012271386183288513286, 0.32813715189346348566, -0.007423195392682361074, 1.293350915313034033, -0.029287034456989179121, 1.9521712704316960263, 0.011295348749219022086, -0.66799495509124628967, 0.068329285161611297283, -4.0409215143626093791, -0.012903871453880378511, 0.76312128325689243535, -0.16085050450109564246, 9.5125283792626493806, 0, 0, 0.14341751361350341121, 0.77593360542645228861, -0.090432986778547594375, 1.1259563994195789238, -0.25736721450922656063, 1.1109363559631879603, 0.15568633342939960928, -0.56801737059939128027, 0.61423561827887318554, -2.241022016113413784, -0.23689682657495314544, 0.86431165517469521475, -1.4330669354534046889, 5.2285058979714911231, 0.27063229881828543277, -0.9873946118959923135, 3.3735101868301691219, -12.308160541801825616, 0, 0, 0.88922814381914494497, 0.26150528401135941792, 1.052718109833140403, -0.16738921270899279059, 0.90250428645253855109, -0.47638032258407536634, -0.44193283907468589033, 0.28817153685428037457, -1.7435755898887204118, 1.1369348754708179516, 0.6724577863061328431, -0.43849014288054521948, 4.0679186503944446684, -2.652571308655904847, -0.76821964733539216397, 0.50093366421426255286, -9.5760809678860194794, 6.2442835778727587837, 0, 0, -0.026500124336832579092, -0.021442252392463622551, 0.033954742484493150023, 0.014552615451508882013, 0.34654423116839672137, 0.041415928368598843579, 1.2822161222240113787, -0.025053284450302942821, 1.9082407187462107068, -0.09884374129233876316, -0.65105193196742539019, 0.038121802028613864521, -3.9384275866202003158, 0.23061133742043829487, 0.74376547607607035317, -0.043550566156846479138, 9.271252622511015673, -0.54287045269119871271, 0, 0, 0.00039179415524385585289, 0.00031701546211065640812, -0.0004962026403406965408, -0.0002151548273865228544, -0.0038300099283937543392, -0.00061231858622874310843, 0.011512077618593902564, 0.00037040318349176827237, 0.25275061773382700991, 0.0014613667327948419179, 1.1983955227256271048, -0.00056361619411026103298, 2.0292004728153583137, -0.0034095000078439544229, -0.33243763075564392029, 0.00064387838566091657681, -4.1439315955146351911, 0.0080261310368032780238, 0, 0, -5.8151558545865533576e-06, -4.7052624338916936783e-06, 7.3648257648012915326e-06, 3.1934086748705229843e-06, 5.6846444389557634026e-05, 9.088262200756952661e-06, -0.00016888399711670137003, -5.4976630258790269937e-06, -0.0028285602953466680576, -2.1690153357751540543e-05, 0.0060445157197113750028, 8.3654030236365385289e-06, 0.20922866828696309871, 5.0605078372050556115e-05, 1.0967879273608196478, -9.5566845852699449579e-06, 2.0750065929362113692, -0.00011912684827902968556, 0, 0, 7.7246635846578622837e-08, 6.2503173239414331853e-08, -9.7831946065279388105e-08, -4.2420200453005213882e-08, -7.5512964720790736305e-07, -1.2072551420034312034e-07, 2.2433999968030079565e-06, 7.3029164546350807041e-08, 3.7573673443748081119e-05, 2.8812493074646954793e-07, -7.9863279978354456061e-05, -1.1112328839252804556e-07, -0.0021871272808178477895, -6.7222137441255028355e-07, 0.0021874625048639208952, 1.2694788454839182361e-07, 0.15875038069671990049, 1.5824422420772902814e-06, 1, 0, ]).reshape((20, 10, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cr +nb_knots=12 +knots=None +absorb_cons=FALSE +output=np.array([-3.6802322454608713193e-09, -1.1576165417746612791e-08, 4.0903329323109361483e-09, 4.0685732923556337374e-08, 1.7703518712245050831e-09, 7.8790091688795366003e-08, -9.3409196093845724123e-09, -2.611905916838673793e-06, 3.0933985220706180644e-09, 5.5610182678566951338e-06, 1.6919855821268632348e-08, 0.00016301336905366541432, -1.4352199746873791695e-08, -0.00096630860312933643686, -2.1293612839737406843e-08, -0.0074687624866493825676, 3.8568109059678503697e-08, 0.11083787128447247783, 0, 1, 1.4460849968779115402e-07, 4.5486583496536781572e-07, -1.6072271234908852579e-07, -1.5986770411107210554e-06, -6.9562981611555798878e-08, -3.0959233519658970583e-06, 3.6703563262437939878e-07, 0.00010263042405151407538, -1.2154986136127495596e-07, -0.00021851080443170532329, -6.6483710865399255783e-07, -0.006405334542942880266, 5.6394540729725285131e-07, 0.039346935329722818042, 8.3669649095786947889e-07, 0.58363014399245827235, -1.5154685940796589346e-06, 1.5869193120902693739, 0, 0, -5.4865400297656400151e-06, -1.725790404504806206e-05, 6.09792368290666473e-06, 6.0654841172256407627e-05, 2.6392645247385444743e-06, 0.0001174613348200111455, -1.3925569348217424364e-05, -0.0038938646832389072101, 4.6116803743272812418e-06, 0.008333356501832860086, 2.5224350005560149737e-05, 0.3457041582444345118, -2.1396453586193263292e-05, 1.3943941859934374516, -3.1744806151200007029e-05, 1.0659241155872372087, 5.7497858861837635377e-05, -1.8607361322222011335, 0, 0, 0.00023256871331852414829, 0.00073154456479976239392, -0.00025848462913861898265, -0.0025710954976070178948, -0.00011187567233550075858, -0.0049790635547287236118, 0.00059029037024653681354, 0.20118319692573388702, -0.00019548432437836398673, 1.1583324452787904235, -0.0010692339057516754303, 1.5709796196933376589, 0.00090697336629712820011, -1.2050531219054301246, 0.0013456292455859321117, -1.7878746869280606191, -0.0024372743079464744345, 3.238292460253569427, 0, 0, -0.0096036016628270864243, -0.030208115694913360155, 0.010673763374229244122, 0.11304537553087100343, 0.0046197503419112585787, 0.84717528615215309529, -0.024375220124670693433, 1.6209052609300536041, 0.008072253382102512545, -0.43744451537192496904, 0.044152527520605257261, -2.3926752654369827233, -0.037452204143992279262, 2.0295771844456078625, -0.055565888790719414336, 3.0111781856549497682, 0.10064385386396751398, -5.4540039558593536029, 0, 0, 0.10357732090048776818, 0.85603572021517670976, -0.11294852267110891408, 1.0800087615333373581, -0.048885660842739625531, 0.2401585690492896441, 0.25793574452960393861, -1.2534276012546561319, -0.085419646489135220291, 0.4150930798449654624, -0.46721691129938069942, 2.2704203849822679473, 0.39631486857335096463, -1.9258749730998911964, 0.58799177288976445244, -2.8573206043806020915, -1.0650015567431445618, 5.1753290302415839719, 0, 0, 0.94933893888308096276, 0.20425894956750886844, 0.97636209569699528021, -0.2257137560392956932, 0.19529887869007700463, -0.097691991575737782694, -1.0167341121476407562, 0.51545291906204826482, 0.33670815416251220764, -0.17070067666802030137, 1.8416810448534708389, -0.93367563771983919096, -1.5621985497383736874, 0.79198660986818203433, -2.3177527963386914678, 1.1750293712615387243, 4.1980354999103974833, -2.1282748625244334306, 0, 0, -0.044595007867203530216, -0.03154770903003507182, 0.12905602059221518707, 0.036023951388023812969, 0.85410491166502156002, 0.015591657403950714977, 1.5843424307430495901, -0.082266367920763708299, -0.42533613529877184467, 0.027243855164596028628, -2.3264464741560830774, 0.14901478038204274412, 1.9733988782296159048, -0.12640118898597454966, 2.9278293524688816518, -0.18753487466867790889, -5.3030381750634045801, 0.33967300679089129645, 0, 0, 0.001079949373603220162, 0.00076398525832885994229, -0.0029588224413149436312, -0.00087238562334283919521, -0.0051468770632319233924, -0.000377580394132319148, 0.20206863248110379372, 0.0019922299995820589268, 1.1580392187922230463, -0.00065975959477697777422, 1.5693757688347129697, -0.0036086644319118939793, -1.2036926618559800062, 0.0030610351112528135301, -1.7858562430596849335, 0.0045414987038525046412, 3.234636548791644195, -0.0082258007893193495902, 0, 0, -2.5477139138140648842e-05, -1.8023214052146796125e-05, 6.9801726696616189999e-05, 2.058049242980996096e-05, 0.00012142023160711750383, 8.9075177709926672744e-06, -0.0039147530372612262053, -4.699879655023364312e-05, 0.0083402740223943259285, 1.5564421263354520723e-05, 0.34574199476944195153, 8.5132181268765064475e-05, 1.3943620913130563288, -7.2213030853402265731e-05, 1.0658764983780117941, -0.00010713872076029942911, -1.8606498854339041937, 0.00019405527365870157302, 0, 0, 6.7149986095353481289e-07, 4.7503707792034416037e-07, -1.8397611096343514486e-06, -5.4243915417817383743e-07, -3.2002678243831975437e-06, -2.3477506293900330442e-07, 0.00010318097750045069814, 1.2387452601072785849e-06, -0.00021869312922374677631, -4.1023078209430247345e-07, -0.00640633179860586148, -2.2438252417072174446e-06, 0.039347781247833550633, 1.9033157496282319598e-06, 0.58363139903719374324, 2.8238506569827991151e-06, 1.5869170388873774513, -5.1147065050188478719e-06, 0, 0, -1.7089420375974873326e-08, -1.2089516008577751082e-08, 4.6821232322022749866e-08, 1.3804873646549429766e-08, 8.1445619495631410706e-08, 5.9749375653827772664e-09, -2.6259172962527552498e-06, -3.1525603681672934994e-08, 5.5656583656398050473e-06, 1.0440220011988337053e-08, 0.00016303874883739764194, 5.7104513396781534087e-08, -0.00096633013142895208495, -4.8438674145699212406e-08, -0.0074687944270686538323, -7.1865943334113596723e-08, 0.11083792913663595425, 1.3016736807641509225e-07, 1, 0, ]).reshape((20, 12, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cr +nb_knots=4 +knots=np.array([-2500, -150, 300, 1500.0000000000000000, ]) +absorb_cons=FALSE +output=np.array([-0.0051418610449036764379, -0.0051207276560822079237, -0.0051517581620670691717, -0.0051036969019558836927, -0.0051724091286762859804, -0.0050616345732373531699, -0.0052108015793779615538, -0.0049476511776847470828, -0.00525764719160080711, -0.0045887810243909702562, -0.0051780211262217532009, -0.0032118234048454639452, -0.0042344880890217376918, 0.0033309098171163710467, -0.0002048781708894489937, 0.036873131791193267115, 0.0053670164361401782871, 0.19556964857406355929, 0.00027785197169554257113, 0.82912284340298503249, 0.65949448911253716332, 0.6654093842010145865, 0.65653556733089935005, 0.66984284447353759084, 0.64987461295218140744, 0.67980900603329297294, 0.63487206047522759533, 0.70218091452751663084, 0.60105778412747068451, 0.75218902517658670082, 0.52490094418674082544, 0.86229539201840321727, 0.35569403068909899446, 1.0895778496922625678, 0.014595118281322956924, 1.4713138143490975818, -0.3821845778229204238, 1.7530984807387750557, -0.019785804601727036839, 0.46986487896086814864, 0.35950128095327349431, 0.35338118891054576265, 0.36256112212690350116, 0.34879091185540550546, 0.36944502095300485456, 0.3384628569483467686, 0.38492806794448852781, 0.31523169436694697954, 0.41971361558839714867, 0.26307215994266325287, 0.49746707294522052312, 0.14713121281897215131, 0.66691371985704051006, -0.097089653687300894735, 0.9873402560545572193, -0.53105535871660392022, 1.2102463767433073727, -0.99135819513191647534, 0.044702741392222536398, -0.3124421698702265493, -0.013853909020907106964, -0.013669845455478047552, -0.013944931295735877447, -0.013530059426987159701, -0.014147224776509979491, -0.013210228408402318115, -0.014589326840338213628, -0.012464957716778975183, -0.015513752524267036478, -0.010672404094858929657, -0.017189996005739616169, -0.0062147814325298833885, -0.018373262457117778973, 0.004180894177922047858, -0.0017304961649907309174, 0.022868412576313085216, 0.16657118464347281384, 0.042690065819077735454, 0.97480521123780894399, 0.013454447506373390722, ]).reshape((20, 4, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cr +nb_knots=5 +knots=np.array([-400, -50, 10, 50, 100, ]) +absorb_cons=FALSE +output=np.array([-0.00093170433340244659687, -0.0012410506081968345274, -0.00078243418040293037045, -0.0014789118938009710238, -0.00046560203080319340248, -0.0020151841680895970881, 0.00010431589287147467922, -0.0030688678143442819739, 0.00055449747551044887423, -0.0028609656322684854333, -0.00014909864114985113439, 0.026923379556954812886, 0.00037005603844857983247, 0.24511712352852058072, 0.0023876748113693508323, 1.1555668732201982429, 0.0069273170504410850126, 3.402689781560706006, 0.017141512088352486159, 8.4587163253268489171, 0.084019186191167327671, 0.11446091282800011091, 0.069879045425061070418, 0.13908517998091646239, 0.040857714895860555715, 0.19963820957805075706, -0.009029120060764306635, 0.3576254481931359086, -0.047994837046959955285, 0.77395141822244861718, 0.012905315717303777676, 1.5659844614539342178, -0.032030405994604847775, 2.0431817208334850378, -0.20666651978408043244, -0.51809792415464139825, -0.59959777581040041294, -8.0018873070243543566, -1.4836931018696206674, -24.840413418481212204, 1.0495495283018867472, 1.0438716260482179266, 1.049399522569444354, 1.0346122703952109756, 1.0414030908228715244, 0.99920617535829048261, 0.98168936282733698651, 0.85586872666349445016, 0.66418975301951443946, 0.32605391435347208517, -0.11777757243608029392, -0.85263295720592457982, 0.29231857203837463555, -1.8526421434409372502, 1.8860972902309971477, 0.52133890068006216723, 5.472099406164398161, 8.051943344140203962, 13.540604167014549830, 24.995803341925523000, -0.15192966618287376268, -0.17994115928882439825, -0.13573193509615386065, -0.19726850771611939561, -0.093692687860718673609, -0.2254589026981791422, 0.031190848164371551277, -0.24103262443025505468, 0.43031985595064925487, -0.11127445668091072439, 1.0214738883945315706, 0.29750331491431342146, -1.0287095298822455103, 0.64642959712677627859, -6.6374375162553720386, -0.1819071733449817152, -19.257075485594906894, -2.8095088468476898669, -47.65126091660886232, -8.7216126122287835898, 0.019292656023222061468, 0.02284967102080309731, 0.017235801282051283617, 0.025049969233792938189, 0.011897484172789671297, 0.028629701929927506981, -0.0039554068238157324977, 0.030607317387968895062, -0.047069269398714280728, 0.014130089737258502702, 0.083547466965394667771, -0.037778198719277893136, 1.7680513078000272831, -0.082086298047844605263, 5.9556190709970859842, 0.023099323599362758808, 15.377646538190468561, 0.35676302817113519916, 36.577208339375580692, 1.1075063634576232108, ]).reshape((20, 5, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cr +nb_knots=7 +knots=np.array([-1000, -500, -250, 0, 250, 500, 1000, ]) +absorb_cons=FALSE +output=np.array([-4.3178765217391302305e-05, 6.5885993478260890537e-05, -9.6313081793478265121e-05, 0.00015008344269701090522, -0.00021248546106063178089, 0.00034663246069176721631, -0.00045706603540709121736, 0.00082099033067846731351, -0.00092573826895791448514, 0.0020071162494608137464, -0.0016063078222631245202, 0.0047785217809616390913, -0.0016924900384041397308, 0.0058508393862588175052, 0.00037271449492305578147, -0.023079518000319019372, -0.00039460853415255482939, 0.96024636175750266442, 0.0010388953913813049352, 4.2828168145345602014, 0.0006476814782608695956, -0.00098828990217391310055, 0.0014446962269021740039, -0.0022512516404551634157, 0.0031872819159094768759, -0.0051994869103765082446, 0.0068559905311063691277, -0.01231485496017700916, 0.013886074034368717928, -0.030106743741912203594, 0.024094617333946868887, -0.071677826714424588972, 0.02538735057606209683, -0.087762590793882266915, -0.0055907174238458371557, 0.77073211937350760703, 0.0059191280122883223325, 0.065812149128730040859, -0.015583430870719573377, -5.436090696106786524, -0.0031088710956521745793, 0.0047440075304347817733, -0.0069345418891304357392, 0.010808468249184780344, -0.015298953196365492127, 0.024985562378791605076, -0.032908754549310574589, 0.059430528454937264771, -0.066653155364969851604, 0.14814853819552065151, -0.11565416320294498453, 0.38547179702354089637, -0.12185928276509808144, 0.89303994817074205947, 0.026835443634460023205, 0.3158234170040984945, -0.028411814458983948584, -0.033037325841022327499, 0.07480046817945394666, 2.7299491962930431121, 0.99996527520000000333, 0.99992195380000004068, 0.99982468157500004047, 0.99960649719062499852, 0.99911787098710935773, 0.99802618626118166922, 0.9955959649107849474, 0.99021595070231704927, 0.97840786415926050967, 0.95284186025012007626, 0.89870074544754108281, 0.78829881686806935193, 0.57842205914062527761, 0.2362299420741153233, -0.10286920059876342171, -0.080364133358400105522, 0.1089119554261051559, 0.0088355638877152739563, -0.28673512802124018206, -0.73010269203186040077, 0.0031519622956521736561, -0.0046471747304347834143, 0.0071520025891304338586, -0.010320575886684784858, 0.016392005544802985134, -0.022542075546565051858, 0.038353001709637714323, -0.04736186631031753802, 0.093197128054721647961, -0.090485094976372942854, 0.23844273869784807229, -0.13266783181011393422, 0.6114558419262043909, -0.058789413728980027818, 0.96115953962745293016, 0.020964556528278284475, -0.40723600724543668194, -0.0023049297098387665911, 1.0721400439055068787, 0.19046157183439835214, -0.00065664547826086978963, 0.00096816140217391292219, -0.0014898486644021743334, 0.002150119976392662717, -0.0034132712039954154516, 0.0046962657388677176915, -0.0079705034644407205674, 0.0098670554813161497065, -0.019191613515453308236, 0.018851061453411026292, -0.047118889772279910766, 0.027639131627107058065, -0.098264441613631667294, 0.012247794526870834503, 0.1283332564542301879, -0.0043676159433913086874, 1.1341990151205716408, 0.00048019368954974300367, -2.1349300292885819985, -0.039679494132166315268, 4.3776365217391304853e-05, -6.4544093478260855155e-05, 9.93232442934782663e-05, -0.00014334133175951084961, 0.00022755141359969430562, -0.00031308438259118116136, 0.00053136689762938121937, -0.00065780369875441000935, 0.0012794409010302202311, -0.0012567374302274016227, 0.0031412593181519930102, -0.0018426087751404706099, 0.0065509627742421101121, -0.00081651963512472227127, -0.0082410361884569308111, 0.00029117439622608720607, 0.18701233167960798487, -3.2012912636649525446e-05, 2.2892691807041996022, 0.0026452996088110873087, ]).reshape((20, 7, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cr +nb_knots=4 +knots=None +absorb_cons=TRUE +output=np.array([0.17237877473947216256, 0.16160585322933293528, 0.17775653635702576283, 0.15351565450517737355, 0.18982763251278575445, 0.13530235680671015563, 0.21678099966619068795, 0.094474101590757947333, 0.27612342080317897608, 0.004254035614190725817, 0.4030409383688886571, -0.19022791859524765257, 0.65608982528520065625, -0.58588986559744449245, 1.0712259966408619327, -1.27728761497709975, 1.342827694119810289, -1.9788260499202323661, -0.052195429016186831173, -0.97077694213337639706, 0.68714996318883114768, 0.60683822144440202617, 0.72724727397328958745, 0.54653827251673237075, 0.81726443453130048766, 0.41083008335212661821, 1.0183156414681064916, 0.10689042936382432691, 1.4611707976831045386, -0.56312355687140791538, 2.4093551078217010364, -1.9991227596244038889, 4.3052173449842321418, -4.8778668329561920558, 7.4441765017641099433, -9.6842706472508055526, 9.6670625693150959989, -13.322034134461750554, 0.012161980255413960134, 0.22619930950229019673, -0.010768222248548299166, -0.01771835491152162767, -0.0072960943160139245939, -0.022933439873231927647, 0.00050471399250212036977, -0.034662450006663660107, 0.017964357449119585514, -0.060912800432191181732, 0.056636870493901259049, -0.11877531418126709151, 0.14054140101632672799, -0.24279484616490168425, 0.3140184596633784353, -0.49144965505677373763, 0.63173409697146676312, -0.90678479147331569887, 1.0347141866437283841, -1.2221561304860752983, 0.99694564370894334093, -0.056807630788862507887, ]).reshape((20, 3, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cr +nb_knots=7 +knots=None +absorb_cons=TRUE +output=np.array([-0.088612856492796668317, -0.10148345379387192777, -0.074820024844059834779, -0.097934158724637176974, -0.030963004348234846042, -0.058173986143542688598, 0.090101482080220576809, 0.10049075761090919823, 0.29596829876665797787, 0.41518677441788176541, 0.43034390532152527742, 0.83452635605264402496, -0.13348462782429343365, 0.98208889847295099962, -1.4362329672138189895, 0.92468785756571492129, -2.6216702734870915847, 0.6954743327776672368, -0.0022196047790754855691, -0.12327370541474826082, 0.24123862297275155964, 0.35840804363927752929, 0.18093342115646737778, 0.44250759269715284061, 0.043937153723061256327, 0.6202158021725746595, -0.24740540994207005365, 0.96645134975980595549, -0.72475992234705299833, 1.5060196314875564649, -1.0261673763863199405, 1.7262771004734287494, 0.32934388972170997034, -0.37505857126375657939, 3.4434877057227697428, -4.9947636565362447669, 6.275814996477087071, -9.1524782805583591028, 0.0068271591356862497413, 0.37917074789447108296, 0.35954055514606403365, 0.35954551446237459356, 0.35744096324407559351, 0.35584226884375003142, 0.34885947617865670223, 0.33862610062421411028, 0.32049681236018934261, 0.28089301373203690027, 0.25602145147051952323, 0.16597482970505655908, 0.12171945403305862998, 0.0018741765108557348514, -0.13785069799652086009, -0.10675519142579256715, -0.57612609827379823724, -0.22195090041542500647, -0.96232722728117126021, -0.44017455467682947701, -0.01453255272801050671, -0.80711739351329703229, 0.39138909874594340899, 0.2727563805116787754, 0.45531894883729062684, 0.19274617399836088683, 0.60538032158012156092, 0.036358318155975434538, 0.93314031181054180042, -0.23999550325584054211, 1.4531806967029836652, -0.67840171762003531608, 1.6665321594967388297, -0.95105942435581225514, -0.35463732068059222735, 0.31454920667339703044, -4.8088313747127671149, 3.2255742320619229524, -8.8757338424365990193, 5.937464168828833877, 0.0075040642903919140341, 0.41676510136746514057, -0.089133365834868971689, -0.10118952771068721874, -0.075725350737607874385, -0.097115177460207771643, -0.032342847263930989132, -0.056715061432944156861, 0.092352440078496370046, 0.098331113369192327256, 0.3400969886051333213, 0.37108103090272787083, 0.71036876576058238797, 0.55444750827998945386, 1.0162219858335352907, -0.16763759291903618243, 1.3370398275661443677, -1.8484727482821472488, 1.4719012302123679614, -3.3978810087925515049, -0.0022219907599747576801, -0.12340621941421109353, -0.013194863919370570376, -0.015072699772667915927, -0.011151244212216769591, -0.014503828881363881043, -0.0046275650331869689486, -0.0085121840139092009442, 0.013410603654954418931, 0.014660726583422474187, 0.044001710617309369722, 0.05545171716304433257, 0.063619527459568614436, 0.082887169332405197242, -0.019275003418586279108, -0.025046122964883565931, -0.18452246030655442, -0.27630735647963872159, -0.17524590664413686181, -0.50790642667837671009, 0.99966985744385294943, -0.01833564992966553106, ]).reshape((20, 6, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cr +nb_knots=10 +knots=None +absorb_cons=TRUE +output=np.array([0.017741203875868801626, 0.059666517581418020144, -0.0073055449468428850998, 0.071233532376632907601, -0.061951321114274808532, 0.023459686026844089879, -0.15952965061095217281, -0.21534242305337428225, -0.20894123625115404441, -0.40851053368902323637, 0.088769309083260417026, 0.1702312769628678002, 0.44867980227835829732, 1.1139500668975872433, -0.14345767930218020214, 0.86682083739859494553, -1.1837156997359956634, -0.21597943647408635037, -0.017918712309548733702, -0.23789999499399971938, -0.0050889918235734665428, -0.017199613011022536063, 0.002072270281447358229, -0.021223643286449593581, 0.017930549906902432111, -0.010400764195970725601, 0.046747049525783831991, 0.07425318574607586708, 0.061514150450350559007, 0.37070324197740467387, -0.026117581474140658115, 1.1506456698664466742, -0.13217536320689113327, 1.766217994670280067, 0.042129159012710096222, -0.26549271162309995287, 0.34842176083555986832, -3.4777238134306913686, 0.0052384550413758917964, 0.06954899473750200678, 0.040717410233940966313, 0.14267724274658066808, -0.01518518709909348792, 0.21755481940124130058, -0.15305036931474685913, 0.39059745188013861306, -0.43311720487012722591, 0.71916259556541839437, -0.58682103919738470843, 0.86959977149390199624, 0.24816600986825945729, -0.22985936815572685643, 1.2655729988498243266, -1.6266494012894197052, -0.39570727271363553834, 0.14945216327392790712, -3.3194533089504827394, 3.3989844591011317831, -0.047815351859148348679, -0.63482641896460045849, 0.12003828098968173654, 0.69730715192779646472, -0.080805333880490451404, 1.032100885251629574, -0.17573134714242774623, 1.0800934656851248761, 0.36589399540256600796, -0.28448323213545234633, 0.88954585755350989995, -1.7064483114238784278, -0.35386353683003346493, 0.6479603434190704947, -2.0242657690367202861, 4.0363385548625183574, 0.45966058247434787853, -0.6843648579769759932, 4.9332279555632334578, -9.2892931271418373029, 0.023611216265584832746, 0.31347722617275158852, 0.88792799224608875974, 0.25713275781065136893, 1.0532535169725301127, -0.17260864810915746426, 0.90704417033506612444, -0.47809553851771402488, -0.43024289925585679217, 0.30393926379684116368, -1.7282652053936073955, 1.1666632610962044403, 0.66595310521671158277, -0.45052173959023528171, 4.0350412627641443208, -2.7188693891544946091, -0.75770752213855696588, 0.51778556938925135444, -9.4893428981139695821, 6.4121669845342363914, 0.0013130525053329394382, 0.01743290360653331969, 0.018394340893766202016, 0.12954185558052447313, 0.015467038664664091788, 0.1947806488224434196, 0.18978123265431517952, 0.10064263984709266586, 0.87856041959654240792, -0.56951570226238645844, 1.3795704170465219462, -1.1253701882691806713, -0.4264441361865796698, 0.45357497790875550558, -2.8031655399252684013, 2.5198958573805381178, 0.38077992198436172444, -0.6254498513067092702, 6.2761716348405380828, -6.3399143661490446888, -0.045339936718340946575, -0.60196126440255459666, -0.004758953821358206937, -0.017005411359244829855, 0.0016248940817804027534, -0.020892741105429570719, 0.014155429774586492792, -0.0074074070841472963028, 0.057823550154750644192, 0.062836648910594553041, 0.313405031875580109, 0.11923488274498127149, 1.1726262403941665191, -0.048228614408167384819, 1.8989517069621104639, -0.26605941795394616456, -0.29079224977894058135, 0.067405260889645518541, -3.8003055548041984046, 0.6731217514912637423, 0.0052018569797349914138, 0.069063096056237921472, 0.017736305328008575982, 0.059663635167637223133, -0.0072989048214304030199, 0.071228621002306605203, -0.061895289364833461221, 0.02341525749747295701, -0.15969206961095888664, -0.21517495710840772727, -0.21175703601763257167, -0.40570100515546192455, 0.094808655216413129097, 0.16419386720169948379, 0.65787987528453284458, 0.90476706770574533145, 0.95333742847376501395, -0.22997392252730572415, 0.8913620730776831147, -2.2910886491383859465, -0.017918169107386142797, -0.23789278310346156919, 0.0060750632566522310557, 0.020430784619126868273, -0.0025017991326720841194, 0.024387881029101547703, -0.021213459590422957535, 0.0080142623794636578399, -0.054619250223539139721, -0.073674968074426458453, -0.071500525070803497285, -0.13890622902065649646, 0.030313398118739860038, 0.056217781624179681554, 0.1514331690285295462, 0.30977852573253761292, -0.046930667126897918084, -0.078740760116175548267, -0.2465351039505715991, -0.78443722293869766471, 0.99386473410822107066, -0.081455614651688740269, ]).reshape((20, 9, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cr +nb_knots=12 +knots=None +absorb_cons=TRUE +output=np.array([-0.10472685656120690745, -0.12767819762829035746, -0.076360123823526582232, -0.10958044510013424666, 0.0027880985603357523288, -0.00047490167664404706613, 0.06928482401745712782, 0.12032832514458154105, -0.15700287132688625635, -0.1737016309573724826, -0.34110464392275169354, -0.43703758617891158567, 0.21658232947898950482, 0.33207321984948795501, 0.31440967571649758305, 1.0125703207549268114, -0.77927839590651259982, 0.57499654812351752575, -0.03855715180341089815, -0.29753053676014623585, -0.045155067335396106842, -0.055061683622734447496, -0.032913973166337623377, -0.047180638471765484754, 0.0012046656812917998312, -8.5942102116568291834e-05, 0.029855775209106073798, 0.047937464934110683712, -0.067681928151560877271, -0.066458149628327731206, -0.14703046798660462935, 0.16005131398107033669, 0.09335066435731875778, 1.5205934362940900506, 0.13551522132064452997, 1.2508474777651827914, -0.33590194032153924963, -2.2969931440729616234, -0.016622640017795731193, -0.1282704446656750541, -0.15034574662694516478, -0.18284705677723475659, -0.11005017611978802627, -0.16012547886604538983, 0.0038970012572561371633, -0.0056574341249261998407, 0.10020869531895890137, 0.37404580513022472887, -0.22593678600553301905, 0.90889537861179725553, -0.49151450544890296079, 0.95180903084537338277, 0.31231202672612079496, -0.78416614637393700082, 0.4534081611517823962, -1.1711369929499528819, -1.1228952128467266647, 1.7833321983277987677, -0.05543814773678283625, -0.42779461349253811164, 0.021352229303511102015, 0.007531901115204664085, 0.033244696218130601051, 0.14543534382436593133, 0.0037956069961920194805, 0.8473147453077168878, -0.044854732714249959113, 1.5853682337831724869, 0.054480061579266131355, -0.38616534110945410774, 0.14497807394687750593, -2.2653864188032963867, -0.10147073278861845624, 1.9430514052120930746, -0.14850072666747962669, 2.8843894925937085816, 0.33098715709405579499, -5.1548937962780287947, 0.011396952652503542641, 0.087945848734329423735, -0.065952557774967432436, 0.64935218850878217989, -0.23655843353990058109, 0.90262481725902277141, -0.044372232611305732763, 0.23939481976571783117, 0.37009197410777977533, -1.0588087616813195435, -0.33957241343679639423, 0.13426223409097867711, -1.0193888969785738219, 1.5733219045695456817, 0.74691289987499476233, -1.4520157873552757, 1.0969502242749886722, -2.1629612193760392458, -2.3264786688505232348, 3.5372496286723378311, -0.062415510749811636826, -0.48163620876963536555, 0.8195140136919921714, 0.045981988292849676481, 0.88170239584467990923, -0.36155327574779005939, 0.19875523391830787756, -0.098276866020166997462, -0.93084557008965973512, 0.66449081424484612857, 0.14207954819710574834, -0.38575918922177282466, 1.418831177364036078, -1.467509312217160522, -1.2937127610296201841, 1.1548650229305499337, -1.9279955842607379157, 1.7067654635554521114, 3.232004184432778704, -3.3827058656451867158, -0.047797409383925140713, -0.36883400885657852131, -0.021262964105923369551, -0.0031022854611233788291, 0.1460681949195489493, 0.060436933823290558965, 0.85348373794725573838, 0.015696770625561979468, 1.5689066026927753761, -0.10905135306422376884, -0.39035761984884714826, 0.065894018981400556689, -2.2504521949512743539, 0.2449549909100549594, 1.9251468021185453861, -0.19161744080459083839, 2.8577824618961185088, -0.28309810920621092389, -5.1294237100882460467, 0.56511845971327800964, 0.0085901166188240788563, 0.066286587283785933233, -0.14931374206792483172, -0.18258953057237148343, -0.11261589846568037521, -0.15823359174408363481, -0.0011429154130191262681, -0.0010551192149562264085, 0.30156489541842562696, 0.17464289155956300159, 0.93257469826065064744, -0.24979099176207356092, 1.0795318316732362973, -0.62202008893514815213, -0.89266942187285236443, 0.42343196160757057278, -1.3343479845023715757, 0.62052301130682563368, 2.1155524024387766246, -1.4614021376163455201, -0.055370175087794709645, -0.42727009501042717554, -0.045179413406039932444, -0.055067758936182993612, -0.032853445083453579334, -0.047225270074522207597, 0.0013235626049733512782, -0.00019451554100623699175, 0.025957829199430799971, 0.051789330864583066338, -0.059352795367343585964, -0.074783156665720870726, 0.19867211632366271745, -0.18558562156573668589, 1.4877431595022336808, 0.12613921140813655342, 1.2014365403948221722, 0.18483406256944329149, -2.1966417328137768372, -0.43610504124242488455, -0.016624243563923207095, -0.1282828186071544585, -0.10472621487286955244, -0.1276780375015148794, -0.076361719159604879437, -0.10957926874689910557, 0.0027849647992298789088, -0.00047204001118300933926, 0.069387562012853995497, 0.1202268016798509892, -0.15722127080697423374, -0.17348334021941591576, -0.34750993698157911505, -0.4306340234217196361, 0.25592930937433366889, 0.29272786696227376391, 0.89803989341652912248, 0.42894253042841035128, 0.80764101265733667656, -1.0119267694495412968, -0.038557109538814519911, -0.29753021062070239555, -0.052405524507834276571, -0.063890551260129033184, -0.038210563318028127611, -0.054833362353974436643, 0.0013952838636999886825, -0.00023608614675063352537, 0.034667393120659889538, 0.060161039317539917459, -0.078558784282471219584, -0.086811135096279259948, -0.17052577031441601418, -0.21548879873646650807, 0.10741142530502149899, 0.14648050866337228304, 0.14986173697025292895, 0.21464206783358963371, -0.2791130852403586049, -0.50636714208926458802, 0.98070595851787800701, -0.14888461024604163208, ]).reshape((20, 11, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cr +nb_knots=4 +knots=np.array([-2500, -150, 300, 1500.0000000000000000, ]) +absorb_cons=TRUE +output=np.array([0.026705483244849264474, 0.029839625165101336945, 0.025137490946490849419, 0.032188537945938233698, 0.021607394654091297004, 0.037467894551815809911, 0.013655036980899055293, 0.049314030316796791942, -0.004274510570643489521, 0.07576300788030972122, -0.044664576703176542272, 0.1337724526334178321, -0.13422281221596993328, 0.251582066127820414, -0.31121876398729647617, 0.43612872129651875097, -0.47985225176217655152, 0.49291724756068344693, -0.081762536217311512776, -0.57008353784816034882, 0.10575886843256800118, 0.098523720643000009534, 0.10937645918695998448, 0.093097559739294566405, 0.11751580252413190708, 0.080890140328454290808, 0.13582591101899046948, 0.053438242334149517465, 0.17698108482519578355, -0.0081682818617542177903, 0.26907668054096511856, -0.14499960251139776268, 0.47046169477357585587, -0.43311804519238522593, 0.8566919676788534721, -0.94615480020651354653, 1.1710825622951557268, -1.4966789629626817693, 0.019850657594207062745, -0.7294516591807701511, -0.065495278981390098183, -0.065538150305470069257, -0.065472788689835886844, -0.065568482416232795607, -0.065419575517949940524, -0.065631137544391218719, -0.065286317209239316806, -0.065744866169428622937, -0.064914403751873434034, -0.065874953263984459273, -0.063671751390664124703, -0.065668915889071088898, -0.058354957302844213951, -0.064207225531959205567, -0.028319888642541334034, -0.061612158154530236032, 0.15860060924423530215, -0.060152247616144620401, 0.96974734313860999624, -0.071414854005294861605, ]).reshape((20, 3, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cr +nb_knots=5 +knots=np.array([-400, -50, 10, 50, 100, ]) +absorb_cons=TRUE +output=np.array([0.21482323419002713472, 0.24750397604597326739, 0.19883614002139288202, 0.27258973708238182221, 0.16379621347999451242, 0.33062932586024107451, 0.090229192760086424085, 0.46740970723200020442, -0.043673571594035724697, 0.78496238070321600055, -0.14225997541844798144, 1.352022453322457185, 0.3403195391608931919, 1.6947780812699095865, 1.6168904854104195756, -0.12774151466578054226, 4.4891751144718545774, -5.4563586958095688928, 10.951815529860082776, -17.445747353383097789, 0.78661625540292257064, 0.77643763922916775311, 0.79017886797586167624, 0.76625062041079372577, 0.79428060270008205013, 0.73589687070232667754, 0.78216715039058581915, 0.63518798334179016329, 0.65550344333732102342, 0.30392043723920803, 0.19412499069407199159, -0.42254129005404528208, -0.4561535986725677172, -1.1523051841355156366, -1.7794911913869626563, -0.26332862233794968043, -4.7570007749943510333, 2.9350973501194954629, -11.456397338110976492, 10.131555788148743247, 0.21540397689706236584, 0.19368025263260429947, 0.22641495625607274689, 0.1776489056064568528, 0.25155233513796670941, 0.14240007942952948028, 0.30993541465339075058, 0.067271686044363815382, 0.44245515455816608608, -0.080352654001592846433, 0.58572719290272645676, -0.30336068837952584465, 0.016951242449324648714, -0.3319833812262538153, -1.5163892893085060276, 0.9143206895602743467, -4.9664054857636248386, 4.3390336686705470726, -12.728941927787642996, 12.044637871668662399, -0.24478425848794690967, -0.24574753349402200797, -0.24311234670203171748, -0.24447893336440842948, -0.23629987575155153579, -0.23582487990744877004, -0.20434545124769434854, -0.19103328802457081315, -0.055793360625630179783, -0.0080996580588084746144, 0.39680666612040660368, 0.39418417396254185059, 1.016323619403686207, 0.62129681239849587904, 2.2740869262794469741, -0.76498115062552785037, 5.1040543667499091995, -4.782338947138994989, 11.471481107808449096, -13.821393989294298521, ]).reshape((20, 4, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cr +nb_knots=7 +knots=np.array([-1000, -500, -250, 0, 250, 500, 1000, ]) +absorb_cons=TRUE +output=np.array([0.18906235677058036426, 0.18778525841872689695, 0.18966313099776943574, 0.18676205783172145081, 0.19092371457093507137, 0.18426214279619892999, 0.19330747373751991369, 0.17770329603139525809, 0.19648166130871616564, 0.15897921699813499785, 0.19369977803300092445, 0.10544719310340035234, 0.15040730339948449323, 0.026126087939682636485, 0.014566423626603465513, 0.71038417591713942656, -0.0044258520659356658661, 0.37477303749040830061, 0.11191608928948779123, -3.5378245461949706652, -0.1717114269621455025, -0.1641796852631927095, -0.1753614922544594612, -0.15832977440814030579, -0.18329458477753993173, -0.14455385888762556368, -0.19975455127362412577, -0.11060689494904693553, -0.23004851008792162603, -0.021054716326888309186, -0.26742505651389464338, 0.22697177040482915955, -0.233733177660145508, 0.79112685520733139199, 0.0087978598061598800584, 0.36982567289124945731, -0.019154626403592486805, -0.30951045809435018263, -0.039292263384108856716, 1.0312889189371063914, 0.550395590305010729, 0.54949597448884435202, 0.55072323934346578689, 0.54860843215917232119, 0.55116651719216569472, 0.54595839995564021674, 0.5507105841767095944, 0.53682026836985941021, 0.54272290221675423272, 0.50167044456244525019, 0.49401178725604522057, 0.36566698512261336385, 0.28011631034896739001, -0.03551586186561946773, -0.15096545178713224877, 0.063629989613431983675, 0.133595751562454651, -0.72836523541381203994, -0.59095728594899554764, -5.2594893416580195122, -0.095090409079557833283, -0.1030766681400390461, -0.090988045895585706324, -0.10887508452680887128, -0.081496719465270400784, -0.12133034539926186579, -0.058865730473533696421, -0.14644031510302549237, -0.0020110794198277630838, -0.18907748512879404834, 0.15000794369741921042, -0.22502359947941463769, 0.5462684746707909822, -0.11817275982033918769, 0.95064928964895001329, 0.052430922211166117175, -0.40184197213040517838, -0.16340199015776293856, 1.0056597912908593617, -0.79932421729955860368, 0.03971313277885706039, 0.041414831889495302975, 0.038837883046586599289, 0.042648161751521966589, 0.036811186605924875459, 0.045290364726222026581, 0.031978640736114505305, 0.050580394866669355081, 0.019931365400903504337, 0.059364669508446515911, -0.010779243096346216579, 0.065589985310555209974, -0.071477633391997127954, 0.036649613012278252355, 0.13265213083724519683, -0.017297782300268411959, 1.1319824969476413035, 0.066678235503076957458, -2.1076119483122943699, 0.36704351417936742497, -0.098246537944137943277, -0.098542071754031859698, -0.098088618240313230068, -0.098745945231101361905, -0.097708943948828105852, -0.099149563571540588747, -0.096734808676916902992, -0.099784603436978008828, -0.093975228815392539139, -0.099897241328297553542, -0.085336692453571283412, -0.094243446676616243751, -0.058668216352278305947, -0.060228845196453252575, -0.018756415239227899883, 0.03177289587597233872, 0.19240899911984374326, -0.16120768980326213859, 2.2227564852817449648, -0.98762351160861328037, ]).reshape((20, 6, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cs +nb_knots=4 +knots=None +absorb_cons=FALSE +output=np.array([-1.693557754132211208e-05, -1.9836972061171899575e-05, -1.4954358368392469422e-05, -2.088026100812221311e-05, -9.5355264085171175196e-06, -1.8699295604068575353e-05, 4.9022718833308546933e-06, 1.7974067511175931267e-05, 3.744122291002612696e-05, 0.0002988262983956019303, 0.00010718085083579747424, 0.001935560671294481172, 0.00024699248283329116715, 0.010566342124751632037, 0.00048044994314723433668, 0.053454984128479515748, 0.00065729103443297996496, 0.25076507420610638643, 0, 1, 0.35560680685948470314, 0.46359416252769836131, 0.30168882277557279581, 0.54466866236250932598, 0.18063664369405590948, 0.72711735964503432239, -0.089776348720933471514, 1.1356863997659447652, -0.68566908660007752641, 2.0361466894716735432, -1.9628257407671605428, 3.9650378336575471394, -4.523225924226894179, 7.8266636243390204086, -8.7985820993738865781, 14.246329329102128014, -12.037110654561336887, 18.944322912930825709, 0, 0, 0.6444562685323340645, 0.53647236902629924504, 0.69836999393477805498, 0.45539628464397530205, 0.81940601333710849641, 0.27293213874197075341, 1.0897461189737138731, -0.13572091900106228457, 1.6852766572444068949, -1.0365718798973906356, 2.9606222279687766097, -2.967335129700412466, 5.5120421008950604147, -6.8380635660933348774, 9.743925990387539926, -13.301405831788731149, 12.784702352769150124, -18.197306344378148424, 0, 0, -4.6139814277377641984e-05, -4.6694581936484837246e-05, -4.3862351982477081188e-05, -4.4066745476440737986e-05, -3.3121504755945730075e-05, -3.0799091401098394798e-05, 2.5327475336172373395e-05, 1.6545167606241587368e-05, 0.00035498813276064257764, 0.00012636412732133810903, 0.0020963319475481821674, 0.00036173537157081639762, 0.010936830849001568516, 0.00083359962956235762136, 0.054175659043200374843, 0.0016215185581219158321, 0.25175101075775591086, 0.0022183572412113072327, 1, 0, ]).reshape((20, 4, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cs +nb_knots=7 +knots=None +absorb_cons=FALSE +output=np.array([-2.9605259404128104445e-07, 4.3004543792069181325e-07, -4.6506508782294522313e-07, 1.2225175036037286749e-06, -4.8490441759023038782e-07, 2.7062259965304665474e-06, 2.8104230735656565092e-07, -5.4449455566502238182e-06, 1.7542735683802410547e-06, -0.00011038827024139799939, 2.8120883750482203265e-06, -0.00053376130083573273665, -7.6784755538918750706e-07, 0.00061879177472234751789, -9.2078635815506674409e-06, 0.029574116402683980898, -1.6901017048743381161e-05, 0.21556638245963724576, 0, 1, 0.00010456869825724268133, -0.00015189629322606839636, 0.00016426557921581520349, -0.00043180524853199072667, 0.00017127302630398999017, -0.000955865732450367038, -9.9266916848531769006e-05, 0.0019305664182940607265, -0.00061962673904836988552, 0.042415216868389754579, -0.00099325736940550032363, 0.27732557133728741317, 0.00027121133522598855859, 1.1504608369631013076, 0.0032523082987030572759, 2.7821404636666882126, 0.0059696060348119403538, 4.1098324719022825136, 0, 0, -0.031642380707528651451, 0.046727930564370717681, -0.049706595580857972083, 0.14260551573254778845, -0.051827041873556585483, 0.44422176162356585838, 0.030038067097830360025, 1.2696071710389067455, 0.18749841492049976188, 2.6526069738107440621, 0.30055865997270758694, 3.4401400654673524038, -0.082068271523342908869, -0.89294447099362916909, -0.98414515128277502143, -10.707999025460104292, -1.8063966557448927208, -19.65451295888456329, 0, 0, 0.9404055233767310007, 1.0229997547271381109, 0.84839014691027592185, 0.9942253298077886603, 0.55270681506501917468, 0.71325376394101502875, -0.27008001161472772189, -0.36441609214674652861, -1.6858466263672904351, -2.2746949537899268101, -2.7024004611201863923, -3.6463202499480562579, 0.73789700429246496416, 0.99563659340566201816, 8.8487029815652924469, 11.939460983544531558, 16.241778413219694954, 21.914859168852931504, 0, 0, 0.091452250263845791256, -0.069826465452058242289, 0.20181123367547218472, -0.13689085681302756714, 0.50012121362724204499, -0.15708533369949770342, 1.2380919977577322655, 0.093217876961678852732, 2.4558884227495125785, 0.58186847095202909319, 3.1248015911458146832, 0.93273112726773044212, -0.80684053529361110524, -0.25468449792074498994, -9.6754590529148973843, -3.0541220021223365322, -17.759287695723489975, -5.6058354437652431201, 0, 0, -0.00032057317842933900735, 0.00025095691201626593508, -0.0006604553857512240455, 0.00049198690620599915858, -0.0011751018630891821651, 0.00056456602826813432217, 0.0020547291059278675364, -0.00033502584436379451204, 0.043190243671805170211, -0.002091240244288253107, 0.27856793393313283858, -0.0033522436217435750035, 1.1501216068412509763, 0.00091533825638770416853, 2.7780724886333088008, 0.010976540508122837117, 4.1023657110424904815, 0.02014742036749034293, 0, 0, 9.0759971803981566744e-07, -7.1050367876085636178e-07, 1.8698667331515860834e-06, -1.392902486538716717e-06, 3.3269224981118857968e-06, -1.5983868974364642471e-06, -5.7964722216058981582e-06, 9.4851778732840647118e-07, -0.00011258250904733756745, 5.9206732932833133743e-06, -0.00053727865043814320746, 9.4907982657877548258e-06, 0.00061975219556745361413, -2.5914854994384806915e-06, 0.029585633563949290115, -3.1076539587733474873e-05, 0.21558752218843252324, -5.7040932539508893209e-05, 1, 0, ]).reshape((20, 7, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cs +nb_knots=10 +knots=None +absorb_cons=FALSE +output=np.array([1.9320747025477182898e-08, 4.8242814281426965595e-08, -1.2568948282371909281e-08, -7.8978523641721503504e-08, -3.5770522726027550527e-08, -7.01473863118866388e-07, 2.1638270976696590321e-08, 2.2109425903379564006e-06, 8.5370349850805669926e-08, 3.744561791897189516e-05, -3.2925418782971613435e-08, -7.9813891850179092256e-05, -1.991767035296446912e-07, -0.0021868285157625511929, 3.7614188014338205365e-08, 0.0021874060835819046644, 4.688717754303082178e-07, 0.15874967738905676473, 0, 1, -1.4544731165165144453e-06, -3.6317372379498608116e-06, 9.4619516292459995175e-07, 5.9455330204143990165e-06, 2.6928184298539113977e-06, 5.2807216744776855019e-05, -1.6289371928530509096e-06, -0.00016644059132742171966, -6.4267121060004543239e-06, -0.002818920227187673988, 2.4786379329293728427e-06, 0.0060407977628119044478, 1.4994097295422416361e-05, 0.20920617714101982787, -2.8316102474873858596e-06, 1.0967921747761912865, -3.5296843934527352639e-05, 2.0750595382021144175, 0, 0, 9.7994633378747003421e-05, 0.00024468706579685965685, -6.3749578484895432179e-05, -0.00040057827261335182721, -0.00018142772925296013898, -0.0035578683345143034648, 0.00010974909140496827962, 0.011347453981486406438, 0.00043299755045772883848, 0.2521011214081396723, -0.00016699739084748591402, 1.1986460188118959191, -0.0010102222245463542399, 2.0307158061521746184, 0.00019077878093656664284, -0.33272379892704945226, 0.0023781128997935555708, -4.1474987648643217852, 0, 0, -0.0066281488228501295526, -0.016550113319571305159, 0.0043118860597063267057, 0.027486913394933615296, 0.012271386183288513286, 0.32813715189346348566, -0.007423195392682361074, 1.293350915313034033, -0.029287034456989179121, 1.9521712704316960263, 0.011295348749219022086, -0.66799495509124628967, 0.068329285161611297283, -4.0409215143626093791, -0.012903871453880378511, 0.76312128325689243535, -0.16085050450109564246, 9.5125283792626493806, 0, 0, 0.14341751361350341121, 0.77593360542645228861, -0.090432986778547594375, 1.1259563994195789238, -0.25736721450922656063, 1.1109363559631879603, 0.15568633342939960928, -0.56801737059939128027, 0.61423561827887318554, -2.241022016113413784, -0.23689682657495314544, 0.86431165517469521475, -1.4330669354534046889, 5.2285058979714911231, 0.27063229881828543277, -0.9873946118959923135, 3.3735101868301691219, -12.308160541801825616, 0, 0, 0.88922814381914494497, 0.26150528401135941792, 1.052718109833140403, -0.16738921270899279059, 0.90250428645253855109, -0.47638032258407536634, -0.44193283907468589033, 0.28817153685428037457, -1.7435755898887204118, 1.1369348754708179516, 0.6724577863061328431, -0.43849014288054521948, 4.0679186503944446684, -2.652571308655904847, -0.76821964733539216397, 0.50093366421426255286, -9.5760809678860194794, 6.2442835778727587837, 0, 0, -0.026500124336832579092, -0.021442252392463622551, 0.033954742484493150023, 0.014552615451508882013, 0.34654423116839672137, 0.041415928368598843579, 1.2822161222240113787, -0.025053284450302942821, 1.9082407187462107068, -0.09884374129233876316, -0.65105193196742539019, 0.038121802028613864521, -3.9384275866202003158, 0.23061133742043829487, 0.74376547607607035317, -0.043550566156846479138, 9.271252622511015673, -0.54287045269119871271, 0, 0, 0.00039179415524385585289, 0.00031701546211065640812, -0.0004962026403406965408, -0.0002151548273865228544, -0.0038300099283937543392, -0.00061231858622874310843, 0.011512077618593902564, 0.00037040318349176827237, 0.25275061773382700991, 0.0014613667327948419179, 1.1983955227256271048, -0.00056361619411026103298, 2.0292004728153583137, -0.0034095000078439544229, -0.33243763075564392029, 0.00064387838566091657681, -4.1439315955146351911, 0.0080261310368032780238, 0, 0, -5.8151558545865533576e-06, -4.7052624338916936783e-06, 7.3648257648012915326e-06, 3.1934086748705229843e-06, 5.6846444389557634026e-05, 9.088262200756952661e-06, -0.00016888399711670137003, -5.4976630258790269937e-06, -0.0028285602953466680576, -2.1690153357751540543e-05, 0.0060445157197113750028, 8.3654030236365385289e-06, 0.20922866828696309871, 5.0605078372050556115e-05, 1.0967879273608196478, -9.5566845852699449579e-06, 2.0750065929362113692, -0.00011912684827902968556, 0, 0, 7.7246635846578622837e-08, 6.2503173239414331853e-08, -9.7831946065279388105e-08, -4.2420200453005213882e-08, -7.5512964720790736305e-07, -1.2072551420034312034e-07, 2.2433999968030079565e-06, 7.3029164546350807041e-08, 3.7573673443748081119e-05, 2.8812493074646954793e-07, -7.9863279978354456061e-05, -1.1112328839252804556e-07, -0.0021871272808178477895, -6.7222137441255028355e-07, 0.0021874625048639208952, 1.2694788454839182361e-07, 0.15875038069671990049, 1.5824422420772902814e-06, 1, 0, ]).reshape((20, 10, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cs +nb_knots=12 +knots=None +absorb_cons=FALSE +output=np.array([-3.6802322454608713193e-09, -1.1576165417746612791e-08, 4.0903329323109361483e-09, 4.0685732923556337374e-08, 1.7703518712245050831e-09, 7.8790091688795366003e-08, -9.3409196093845724123e-09, -2.611905916838673793e-06, 3.0933985220706180644e-09, 5.5610182678566951338e-06, 1.6919855821268632348e-08, 0.00016301336905366541432, -1.4352199746873791695e-08, -0.00096630860312933643686, -2.1293612839737406843e-08, -0.0074687624866493825676, 3.8568109059678503697e-08, 0.11083787128447247783, 0, 1, 1.4460849968779115402e-07, 4.5486583496536781572e-07, -1.6072271234908852579e-07, -1.5986770411107210554e-06, -6.9562981611555798878e-08, -3.0959233519658970583e-06, 3.6703563262437939878e-07, 0.00010263042405151407538, -1.2154986136127495596e-07, -0.00021851080443170532329, -6.6483710865399255783e-07, -0.006405334542942880266, 5.6394540729725285131e-07, 0.039346935329722818042, 8.3669649095786947889e-07, 0.58363014399245827235, -1.5154685940796589346e-06, 1.5869193120902693739, 0, 0, -5.4865400297656400151e-06, -1.725790404504806206e-05, 6.09792368290666473e-06, 6.0654841172256407627e-05, 2.6392645247385444743e-06, 0.0001174613348200111455, -1.3925569348217424364e-05, -0.0038938646832389072101, 4.6116803743272812418e-06, 0.008333356501832860086, 2.5224350005560149737e-05, 0.3457041582444345118, -2.1396453586193263292e-05, 1.3943941859934374516, -3.1744806151200007029e-05, 1.0659241155872372087, 5.7497858861837635377e-05, -1.8607361322222011335, 0, 0, 0.00023256871331852414829, 0.00073154456479976239392, -0.00025848462913861898265, -0.0025710954976070178948, -0.00011187567233550075858, -0.0049790635547287236118, 0.00059029037024653681354, 0.20118319692573388702, -0.00019548432437836398673, 1.1583324452787904235, -0.0010692339057516754303, 1.5709796196933376589, 0.00090697336629712820011, -1.2050531219054301246, 0.0013456292455859321117, -1.7878746869280606191, -0.0024372743079464744345, 3.238292460253569427, 0, 0, -0.0096036016628270864243, -0.030208115694913360155, 0.010673763374229244122, 0.11304537553087100343, 0.0046197503419112585787, 0.84717528615215309529, -0.024375220124670693433, 1.6209052609300536041, 0.008072253382102512545, -0.43744451537192496904, 0.044152527520605257261, -2.3926752654369827233, -0.037452204143992279262, 2.0295771844456078625, -0.055565888790719414336, 3.0111781856549497682, 0.10064385386396751398, -5.4540039558593536029, 0, 0, 0.10357732090048776818, 0.85603572021517670976, -0.11294852267110891408, 1.0800087615333373581, -0.048885660842739625531, 0.2401585690492896441, 0.25793574452960393861, -1.2534276012546561319, -0.085419646489135220291, 0.4150930798449654624, -0.46721691129938069942, 2.2704203849822679473, 0.39631486857335096463, -1.9258749730998911964, 0.58799177288976445244, -2.8573206043806020915, -1.0650015567431445618, 5.1753290302415839719, 0, 0, 0.94933893888308096276, 0.20425894956750886844, 0.97636209569699528021, -0.2257137560392956932, 0.19529887869007700463, -0.097691991575737782694, -1.0167341121476407562, 0.51545291906204826482, 0.33670815416251220764, -0.17070067666802030137, 1.8416810448534708389, -0.93367563771983919096, -1.5621985497383736874, 0.79198660986818203433, -2.3177527963386914678, 1.1750293712615387243, 4.1980354999103974833, -2.1282748625244334306, 0, 0, -0.044595007867203530216, -0.03154770903003507182, 0.12905602059221518707, 0.036023951388023812969, 0.85410491166502156002, 0.015591657403950714977, 1.5843424307430495901, -0.082266367920763708299, -0.42533613529877184467, 0.027243855164596028628, -2.3264464741560830774, 0.14901478038204274412, 1.9733988782296159048, -0.12640118898597454966, 2.9278293524688816518, -0.18753487466867790889, -5.3030381750634045801, 0.33967300679089129645, 0, 0, 0.001079949373603220162, 0.00076398525832885994229, -0.0029588224413149436312, -0.00087238562334283919521, -0.0051468770632319233924, -0.000377580394132319148, 0.20206863248110379372, 0.0019922299995820589268, 1.1580392187922230463, -0.00065975959477697777422, 1.5693757688347129697, -0.0036086644319118939793, -1.2036926618559800062, 0.0030610351112528135301, -1.7858562430596849335, 0.0045414987038525046412, 3.234636548791644195, -0.0082258007893193495902, 0, 0, -2.5477139138140648842e-05, -1.8023214052146796125e-05, 6.9801726696616189999e-05, 2.058049242980996096e-05, 0.00012142023160711750383, 8.9075177709926672744e-06, -0.0039147530372612262053, -4.699879655023364312e-05, 0.0083402740223943259285, 1.5564421263354520723e-05, 0.34574199476944195153, 8.5132181268765064475e-05, 1.3943620913130563288, -7.2213030853402265731e-05, 1.0658764983780117941, -0.00010713872076029942911, -1.8606498854339041937, 0.00019405527365870157302, 0, 0, 6.7149986095353481289e-07, 4.7503707792034416037e-07, -1.8397611096343514486e-06, -5.4243915417817383743e-07, -3.2002678243831975437e-06, -2.3477506293900330442e-07, 0.00010318097750045069814, 1.2387452601072785849e-06, -0.00021869312922374677631, -4.1023078209430247345e-07, -0.00640633179860586148, -2.2438252417072174446e-06, 0.039347781247833550633, 1.9033157496282319598e-06, 0.58363139903719374324, 2.8238506569827991151e-06, 1.5869170388873774513, -5.1147065050188478719e-06, 0, 0, -1.7089420375974873326e-08, -1.2089516008577751082e-08, 4.6821232322022749866e-08, 1.3804873646549429766e-08, 8.1445619495631410706e-08, 5.9749375653827772664e-09, -2.6259172962527552498e-06, -3.1525603681672934994e-08, 5.5656583656398050473e-06, 1.0440220011988337053e-08, 0.00016303874883739764194, 5.7104513396781534087e-08, -0.00096633013142895208495, -4.8438674145699212406e-08, -0.0074687944270686538323, -7.1865943334113596723e-08, 0.11083792913663595425, 1.3016736807641509225e-07, 1, 0, ]).reshape((20, 12, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cs +nb_knots=4 +knots=np.array([-2500, -150, 300, 1500.0000000000000000, ]) +absorb_cons=FALSE +output=np.array([-0.0051418610449036764379, -0.0051207276560822079237, -0.0051517581620670691717, -0.0051036969019558836927, -0.0051724091286762859804, -0.0050616345732373531699, -0.0052108015793779615538, -0.0049476511776847470828, -0.00525764719160080711, -0.0045887810243909702562, -0.0051780211262217532009, -0.0032118234048454639452, -0.0042344880890217376918, 0.0033309098171163710467, -0.0002048781708894489937, 0.036873131791193267115, 0.0053670164361401782871, 0.19556964857406355929, 0.00027785197169554257113, 0.82912284340298503249, 0.65949448911253716332, 0.6654093842010145865, 0.65653556733089935005, 0.66984284447353759084, 0.64987461295218140744, 0.67980900603329297294, 0.63487206047522759533, 0.70218091452751663084, 0.60105778412747068451, 0.75218902517658670082, 0.52490094418674082544, 0.86229539201840321727, 0.35569403068909899446, 1.0895778496922625678, 0.014595118281322956924, 1.4713138143490975818, -0.3821845778229204238, 1.7530984807387750557, -0.019785804601727036839, 0.46986487896086814864, 0.35950128095327349431, 0.35338118891054576265, 0.36256112212690350116, 0.34879091185540550546, 0.36944502095300485456, 0.3384628569483467686, 0.38492806794448852781, 0.31523169436694697954, 0.41971361558839714867, 0.26307215994266325287, 0.49746707294522052312, 0.14713121281897215131, 0.66691371985704051006, -0.097089653687300894735, 0.9873402560545572193, -0.53105535871660392022, 1.2102463767433073727, -0.99135819513191647534, 0.044702741392222536398, -0.3124421698702265493, -0.013853909020907106964, -0.013669845455478047552, -0.013944931295735877447, -0.013530059426987159701, -0.014147224776509979491, -0.013210228408402318115, -0.014589326840338213628, -0.012464957716778975183, -0.015513752524267036478, -0.010672404094858929657, -0.017189996005739616169, -0.0062147814325298833885, -0.018373262457117778973, 0.004180894177922047858, -0.0017304961649907309174, 0.022868412576313085216, 0.16657118464347281384, 0.042690065819077735454, 0.97480521123780894399, 0.013454447506373390722, ]).reshape((20, 4, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cs +nb_knots=5 +knots=np.array([-400, -50, 10, 50, 100, ]) +absorb_cons=FALSE +output=np.array([-0.00093170433340244659687, -0.0012410506081968345274, -0.00078243418040293037045, -0.0014789118938009710238, -0.00046560203080319340248, -0.0020151841680895970881, 0.00010431589287147467922, -0.0030688678143442819739, 0.00055449747551044887423, -0.0028609656322684854333, -0.00014909864114985113439, 0.026923379556954812886, 0.00037005603844857983247, 0.24511712352852058072, 0.0023876748113693508323, 1.1555668732201982429, 0.0069273170504410850126, 3.402689781560706006, 0.017141512088352486159, 8.4587163253268489171, 0.084019186191167327671, 0.11446091282800011091, 0.069879045425061070418, 0.13908517998091646239, 0.040857714895860555715, 0.19963820957805075706, -0.009029120060764306635, 0.3576254481931359086, -0.047994837046959955285, 0.77395141822244861718, 0.012905315717303777676, 1.5659844614539342178, -0.032030405994604847775, 2.0431817208334850378, -0.20666651978408043244, -0.51809792415464139825, -0.59959777581040041294, -8.0018873070243543566, -1.4836931018696206674, -24.840413418481212204, 1.0495495283018867472, 1.0438716260482179266, 1.049399522569444354, 1.0346122703952109756, 1.0414030908228715244, 0.99920617535829048261, 0.98168936282733698651, 0.85586872666349445016, 0.66418975301951443946, 0.32605391435347208517, -0.11777757243608029392, -0.85263295720592457982, 0.29231857203837463555, -1.8526421434409372502, 1.8860972902309971477, 0.52133890068006216723, 5.472099406164398161, 8.051943344140203962, 13.540604167014549830, 24.995803341925523000, -0.15192966618287376268, -0.17994115928882439825, -0.13573193509615386065, -0.19726850771611939561, -0.093692687860718673609, -0.2254589026981791422, 0.031190848164371551277, -0.24103262443025505468, 0.43031985595064925487, -0.11127445668091072439, 1.0214738883945315706, 0.29750331491431342146, -1.0287095298822455103, 0.64642959712677627859, -6.6374375162553720386, -0.1819071733449817152, -19.257075485594906894, -2.8095088468476898669, -47.65126091660886232, -8.7216126122287835898, 0.019292656023222061468, 0.02284967102080309731, 0.017235801282051283617, 0.025049969233792938189, 0.011897484172789671297, 0.028629701929927506981, -0.0039554068238157324977, 0.030607317387968895062, -0.047069269398714280728, 0.014130089737258502702, 0.083547466965394667771, -0.037778198719277893136, 1.7680513078000272831, -0.082086298047844605263, 5.9556190709970859842, 0.023099323599362758808, 15.377646538190468561, 0.35676302817113519916, 36.577208339375580692, 1.1075063634576232108, ]).reshape((20, 5, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cs +nb_knots=7 +knots=np.array([-1000, -500, -250, 0, 250, 500, 1000, ]) +absorb_cons=FALSE +output=np.array([-4.3178765217391302305e-05, 6.5885993478260890537e-05, -9.6313081793478265121e-05, 0.00015008344269701090522, -0.00021248546106063178089, 0.00034663246069176721631, -0.00045706603540709121736, 0.00082099033067846731351, -0.00092573826895791448514, 0.0020071162494608137464, -0.0016063078222631245202, 0.0047785217809616390913, -0.0016924900384041397308, 0.0058508393862588175052, 0.00037271449492305578147, -0.023079518000319019372, -0.00039460853415255482939, 0.96024636175750266442, 0.0010388953913813049352, 4.2828168145345602014, 0.0006476814782608695956, -0.00098828990217391310055, 0.0014446962269021740039, -0.0022512516404551634157, 0.0031872819159094768759, -0.0051994869103765082446, 0.0068559905311063691277, -0.01231485496017700916, 0.013886074034368717928, -0.030106743741912203594, 0.024094617333946868887, -0.071677826714424588972, 0.02538735057606209683, -0.087762590793882266915, -0.0055907174238458371557, 0.77073211937350760703, 0.0059191280122883223325, 0.065812149128730040859, -0.015583430870719573377, -5.436090696106786524, -0.0031088710956521745793, 0.0047440075304347817733, -0.0069345418891304357392, 0.010808468249184780344, -0.015298953196365492127, 0.024985562378791605076, -0.032908754549310574589, 0.059430528454937264771, -0.066653155364969851604, 0.14814853819552065151, -0.11565416320294498453, 0.38547179702354089637, -0.12185928276509808144, 0.89303994817074205947, 0.026835443634460023205, 0.3158234170040984945, -0.028411814458983948584, -0.033037325841022327499, 0.07480046817945394666, 2.7299491962930431121, 0.99996527520000000333, 0.99992195380000004068, 0.99982468157500004047, 0.99960649719062499852, 0.99911787098710935773, 0.99802618626118166922, 0.9955959649107849474, 0.99021595070231704927, 0.97840786415926050967, 0.95284186025012007626, 0.89870074544754108281, 0.78829881686806935193, 0.57842205914062527761, 0.2362299420741153233, -0.10286920059876342171, -0.080364133358400105522, 0.1089119554261051559, 0.0088355638877152739563, -0.28673512802124018206, -0.73010269203186040077, 0.0031519622956521736561, -0.0046471747304347834143, 0.0071520025891304338586, -0.010320575886684784858, 0.016392005544802985134, -0.022542075546565051858, 0.038353001709637714323, -0.04736186631031753802, 0.093197128054721647961, -0.090485094976372942854, 0.23844273869784807229, -0.13266783181011393422, 0.6114558419262043909, -0.058789413728980027818, 0.96115953962745293016, 0.020964556528278284475, -0.40723600724543668194, -0.0023049297098387665911, 1.0721400439055068787, 0.19046157183439835214, -0.00065664547826086978963, 0.00096816140217391292219, -0.0014898486644021743334, 0.002150119976392662717, -0.0034132712039954154516, 0.0046962657388677176915, -0.0079705034644407205674, 0.0098670554813161497065, -0.019191613515453308236, 0.018851061453411026292, -0.047118889772279910766, 0.027639131627107058065, -0.098264441613631667294, 0.012247794526870834503, 0.1283332564542301879, -0.0043676159433913086874, 1.1341990151205716408, 0.00048019368954974300367, -2.1349300292885819985, -0.039679494132166315268, 4.3776365217391304853e-05, -6.4544093478260855155e-05, 9.93232442934782663e-05, -0.00014334133175951084961, 0.00022755141359969430562, -0.00031308438259118116136, 0.00053136689762938121937, -0.00065780369875441000935, 0.0012794409010302202311, -0.0012567374302274016227, 0.0031412593181519930102, -0.0018426087751404706099, 0.0065509627742421101121, -0.00081651963512472227127, -0.0082410361884569308111, 0.00029117439622608720607, 0.18701233167960798487, -3.2012912636649525446e-05, 2.2892691807041996022, 0.0026452996088110873087, ]).reshape((20, 7, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cs +nb_knots=4 +knots=None +absorb_cons=TRUE +output=np.array([0.17237877473947216256, 0.16160585322933293528, 0.17775653635702576283, 0.15351565450517737355, 0.18982763251278575445, 0.13530235680671015563, 0.21678099966619068795, 0.094474101590757947333, 0.27612342080317897608, 0.004254035614190725817, 0.4030409383688886571, -0.19022791859524765257, 0.65608982528520065625, -0.58588986559744449245, 1.0712259966408619327, -1.27728761497709975, 1.342827694119810289, -1.9788260499202323661, -0.052195429016186831173, -0.97077694213337639706, 0.68714996318883114768, 0.60683822144440202617, 0.72724727397328958745, 0.54653827251673237075, 0.81726443453130048766, 0.41083008335212661821, 1.0183156414681064916, 0.10689042936382432691, 1.4611707976831045386, -0.56312355687140791538, 2.4093551078217010364, -1.9991227596244038889, 4.3052173449842321418, -4.8778668329561920558, 7.4441765017641099433, -9.6842706472508055526, 9.6670625693150959989, -13.322034134461750554, 0.012161980255413960134, 0.22619930950229019673, -0.010768222248548299166, -0.01771835491152162767, -0.0072960943160139245939, -0.022933439873231927647, 0.00050471399250212036977, -0.034662450006663660107, 0.017964357449119585514, -0.060912800432191181732, 0.056636870493901259049, -0.11877531418126709151, 0.14054140101632672799, -0.24279484616490168425, 0.3140184596633784353, -0.49144965505677373763, 0.63173409697146676312, -0.90678479147331569887, 1.0347141866437283841, -1.2221561304860752983, 0.99694564370894334093, -0.056807630788862507887, ]).reshape((20, 3, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cs +nb_knots=7 +knots=None +absorb_cons=TRUE +output=np.array([-0.088612856492796668317, -0.10148345379387192777, -0.074820024844059834779, -0.097934158724637176974, -0.030963004348234846042, -0.058173986143542688598, 0.090101482080220576809, 0.10049075761090919823, 0.29596829876665797787, 0.41518677441788176541, 0.43034390532152527742, 0.83452635605264402496, -0.13348462782429343365, 0.98208889847295099962, -1.4362329672138189895, 0.92468785756571492129, -2.6216702734870915847, 0.6954743327776672368, -0.0022196047790754855691, -0.12327370541474826082, 0.24123862297275155964, 0.35840804363927752929, 0.18093342115646737778, 0.44250759269715284061, 0.043937153723061256327, 0.6202158021725746595, -0.24740540994207005365, 0.96645134975980595549, -0.72475992234705299833, 1.5060196314875564649, -1.0261673763863199405, 1.7262771004734287494, 0.32934388972170997034, -0.37505857126375657939, 3.4434877057227697428, -4.9947636565362447669, 6.275814996477087071, -9.1524782805583591028, 0.0068271591356862497413, 0.37917074789447108296, 0.35954055514606403365, 0.35954551446237459356, 0.35744096324407559351, 0.35584226884375003142, 0.34885947617865670223, 0.33862610062421411028, 0.32049681236018934261, 0.28089301373203690027, 0.25602145147051952323, 0.16597482970505655908, 0.12171945403305862998, 0.0018741765108557348514, -0.13785069799652086009, -0.10675519142579256715, -0.57612609827379823724, -0.22195090041542500647, -0.96232722728117126021, -0.44017455467682947701, -0.01453255272801050671, -0.80711739351329703229, 0.39138909874594340899, 0.2727563805116787754, 0.45531894883729062684, 0.19274617399836088683, 0.60538032158012156092, 0.036358318155975434538, 0.93314031181054180042, -0.23999550325584054211, 1.4531806967029836652, -0.67840171762003531608, 1.6665321594967388297, -0.95105942435581225514, -0.35463732068059222735, 0.31454920667339703044, -4.8088313747127671149, 3.2255742320619229524, -8.8757338424365990193, 5.937464168828833877, 0.0075040642903919140341, 0.41676510136746514057, -0.089133365834868971689, -0.10118952771068721874, -0.075725350737607874385, -0.097115177460207771643, -0.032342847263930989132, -0.056715061432944156861, 0.092352440078496370046, 0.098331113369192327256, 0.3400969886051333213, 0.37108103090272787083, 0.71036876576058238797, 0.55444750827998945386, 1.0162219858335352907, -0.16763759291903618243, 1.3370398275661443677, -1.8484727482821472488, 1.4719012302123679614, -3.3978810087925515049, -0.0022219907599747576801, -0.12340621941421109353, -0.013194863919370570376, -0.015072699772667915927, -0.011151244212216769591, -0.014503828881363881043, -0.0046275650331869689486, -0.0085121840139092009442, 0.013410603654954418931, 0.014660726583422474187, 0.044001710617309369722, 0.05545171716304433257, 0.063619527459568614436, 0.082887169332405197242, -0.019275003418586279108, -0.025046122964883565931, -0.18452246030655442, -0.27630735647963872159, -0.17524590664413686181, -0.50790642667837671009, 0.99966985744385294943, -0.01833564992966553106, ]).reshape((20, 6, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cs +nb_knots=10 +knots=None +absorb_cons=TRUE +output=np.array([0.017741203875868801626, 0.059666517581418020144, -0.0073055449468428850998, 0.071233532376632907601, -0.061951321114274808532, 0.023459686026844089879, -0.15952965061095217281, -0.21534242305337428225, -0.20894123625115404441, -0.40851053368902323637, 0.088769309083260417026, 0.1702312769628678002, 0.44867980227835829732, 1.1139500668975872433, -0.14345767930218020214, 0.86682083739859494553, -1.1837156997359956634, -0.21597943647408635037, -0.017918712309548733702, -0.23789999499399971938, -0.0050889918235734665428, -0.017199613011022536063, 0.002072270281447358229, -0.021223643286449593581, 0.017930549906902432111, -0.010400764195970725601, 0.046747049525783831991, 0.07425318574607586708, 0.061514150450350559007, 0.37070324197740467387, -0.026117581474140658115, 1.1506456698664466742, -0.13217536320689113327, 1.766217994670280067, 0.042129159012710096222, -0.26549271162309995287, 0.34842176083555986832, -3.4777238134306913686, 0.0052384550413758917964, 0.06954899473750200678, 0.040717410233940966313, 0.14267724274658066808, -0.01518518709909348792, 0.21755481940124130058, -0.15305036931474685913, 0.39059745188013861306, -0.43311720487012722591, 0.71916259556541839437, -0.58682103919738470843, 0.86959977149390199624, 0.24816600986825945729, -0.22985936815572685643, 1.2655729988498243266, -1.6266494012894197052, -0.39570727271363553834, 0.14945216327392790712, -3.3194533089504827394, 3.3989844591011317831, -0.047815351859148348679, -0.63482641896460045849, 0.12003828098968173654, 0.69730715192779646472, -0.080805333880490451404, 1.032100885251629574, -0.17573134714242774623, 1.0800934656851248761, 0.36589399540256600796, -0.28448323213545234633, 0.88954585755350989995, -1.7064483114238784278, -0.35386353683003346493, 0.6479603434190704947, -2.0242657690367202861, 4.0363385548625183574, 0.45966058247434787853, -0.6843648579769759932, 4.9332279555632334578, -9.2892931271418373029, 0.023611216265584832746, 0.31347722617275158852, 0.88792799224608875974, 0.25713275781065136893, 1.0532535169725301127, -0.17260864810915746426, 0.90704417033506612444, -0.47809553851771402488, -0.43024289925585679217, 0.30393926379684116368, -1.7282652053936073955, 1.1666632610962044403, 0.66595310521671158277, -0.45052173959023528171, 4.0350412627641443208, -2.7188693891544946091, -0.75770752213855696588, 0.51778556938925135444, -9.4893428981139695821, 6.4121669845342363914, 0.0013130525053329394382, 0.01743290360653331969, 0.018394340893766202016, 0.12954185558052447313, 0.015467038664664091788, 0.1947806488224434196, 0.18978123265431517952, 0.10064263984709266586, 0.87856041959654240792, -0.56951570226238645844, 1.3795704170465219462, -1.1253701882691806713, -0.4264441361865796698, 0.45357497790875550558, -2.8031655399252684013, 2.5198958573805381178, 0.38077992198436172444, -0.6254498513067092702, 6.2761716348405380828, -6.3399143661490446888, -0.045339936718340946575, -0.60196126440255459666, -0.004758953821358206937, -0.017005411359244829855, 0.0016248940817804027534, -0.020892741105429570719, 0.014155429774586492792, -0.0074074070841472963028, 0.057823550154750644192, 0.062836648910594553041, 0.313405031875580109, 0.11923488274498127149, 1.1726262403941665191, -0.048228614408167384819, 1.8989517069621104639, -0.26605941795394616456, -0.29079224977894058135, 0.067405260889645518541, -3.8003055548041984046, 0.6731217514912637423, 0.0052018569797349914138, 0.069063096056237921472, 0.017736305328008575982, 0.059663635167637223133, -0.0072989048214304030199, 0.071228621002306605203, -0.061895289364833461221, 0.02341525749747295701, -0.15969206961095888664, -0.21517495710840772727, -0.21175703601763257167, -0.40570100515546192455, 0.094808655216413129097, 0.16419386720169948379, 0.65787987528453284458, 0.90476706770574533145, 0.95333742847376501395, -0.22997392252730572415, 0.8913620730776831147, -2.2910886491383859465, -0.017918169107386142797, -0.23789278310346156919, 0.0060750632566522310557, 0.020430784619126868273, -0.0025017991326720841194, 0.024387881029101547703, -0.021213459590422957535, 0.0080142623794636578399, -0.054619250223539139721, -0.073674968074426458453, -0.071500525070803497285, -0.13890622902065649646, 0.030313398118739860038, 0.056217781624179681554, 0.1514331690285295462, 0.30977852573253761292, -0.046930667126897918084, -0.078740760116175548267, -0.2465351039505715991, -0.78443722293869766471, 0.99386473410822107066, -0.081455614651688740269, ]).reshape((20, 9, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cs +nb_knots=12 +knots=None +absorb_cons=TRUE +output=np.array([-0.10472685656120690745, -0.12767819762829035746, -0.076360123823526582232, -0.10958044510013424666, 0.0027880985603357523288, -0.00047490167664404706613, 0.06928482401745712782, 0.12032832514458154105, -0.15700287132688625635, -0.1737016309573724826, -0.34110464392275169354, -0.43703758617891158567, 0.21658232947898950482, 0.33207321984948795501, 0.31440967571649758305, 1.0125703207549268114, -0.77927839590651259982, 0.57499654812351752575, -0.03855715180341089815, -0.29753053676014623585, -0.045155067335396106842, -0.055061683622734447496, -0.032913973166337623377, -0.047180638471765484754, 0.0012046656812917998312, -8.5942102116568291834e-05, 0.029855775209106073798, 0.047937464934110683712, -0.067681928151560877271, -0.066458149628327731206, -0.14703046798660462935, 0.16005131398107033669, 0.09335066435731875778, 1.5205934362940900506, 0.13551522132064452997, 1.2508474777651827914, -0.33590194032153924963, -2.2969931440729616234, -0.016622640017795731193, -0.1282704446656750541, -0.15034574662694516478, -0.18284705677723475659, -0.11005017611978802627, -0.16012547886604538983, 0.0038970012572561371633, -0.0056574341249261998407, 0.10020869531895890137, 0.37404580513022472887, -0.22593678600553301905, 0.90889537861179725553, -0.49151450544890296079, 0.95180903084537338277, 0.31231202672612079496, -0.78416614637393700082, 0.4534081611517823962, -1.1711369929499528819, -1.1228952128467266647, 1.7833321983277987677, -0.05543814773678283625, -0.42779461349253811164, 0.021352229303511102015, 0.007531901115204664085, 0.033244696218130601051, 0.14543534382436593133, 0.0037956069961920194805, 0.8473147453077168878, -0.044854732714249959113, 1.5853682337831724869, 0.054480061579266131355, -0.38616534110945410774, 0.14497807394687750593, -2.2653864188032963867, -0.10147073278861845624, 1.9430514052120930746, -0.14850072666747962669, 2.8843894925937085816, 0.33098715709405579499, -5.1548937962780287947, 0.011396952652503542641, 0.087945848734329423735, -0.065952557774967432436, 0.64935218850878217989, -0.23655843353990058109, 0.90262481725902277141, -0.044372232611305732763, 0.23939481976571783117, 0.37009197410777977533, -1.0588087616813195435, -0.33957241343679639423, 0.13426223409097867711, -1.0193888969785738219, 1.5733219045695456817, 0.74691289987499476233, -1.4520157873552757, 1.0969502242749886722, -2.1629612193760392458, -2.3264786688505232348, 3.5372496286723378311, -0.062415510749811636826, -0.48163620876963536555, 0.8195140136919921714, 0.045981988292849676481, 0.88170239584467990923, -0.36155327574779005939, 0.19875523391830787756, -0.098276866020166997462, -0.93084557008965973512, 0.66449081424484612857, 0.14207954819710574834, -0.38575918922177282466, 1.418831177364036078, -1.467509312217160522, -1.2937127610296201841, 1.1548650229305499337, -1.9279955842607379157, 1.7067654635554521114, 3.232004184432778704, -3.3827058656451867158, -0.047797409383925140713, -0.36883400885657852131, -0.021262964105923369551, -0.0031022854611233788291, 0.1460681949195489493, 0.060436933823290558965, 0.85348373794725573838, 0.015696770625561979468, 1.5689066026927753761, -0.10905135306422376884, -0.39035761984884714826, 0.065894018981400556689, -2.2504521949512743539, 0.2449549909100549594, 1.9251468021185453861, -0.19161744080459083839, 2.8577824618961185088, -0.28309810920621092389, -5.1294237100882460467, 0.56511845971327800964, 0.0085901166188240788563, 0.066286587283785933233, -0.14931374206792483172, -0.18258953057237148343, -0.11261589846568037521, -0.15823359174408363481, -0.0011429154130191262681, -0.0010551192149562264085, 0.30156489541842562696, 0.17464289155956300159, 0.93257469826065064744, -0.24979099176207356092, 1.0795318316732362973, -0.62202008893514815213, -0.89266942187285236443, 0.42343196160757057278, -1.3343479845023715757, 0.62052301130682563368, 2.1155524024387766246, -1.4614021376163455201, -0.055370175087794709645, -0.42727009501042717554, -0.045179413406039932444, -0.055067758936182993612, -0.032853445083453579334, -0.047225270074522207597, 0.0013235626049733512782, -0.00019451554100623699175, 0.025957829199430799971, 0.051789330864583066338, -0.059352795367343585964, -0.074783156665720870726, 0.19867211632366271745, -0.18558562156573668589, 1.4877431595022336808, 0.12613921140813655342, 1.2014365403948221722, 0.18483406256944329149, -2.1966417328137768372, -0.43610504124242488455, -0.016624243563923207095, -0.1282828186071544585, -0.10472621487286955244, -0.1276780375015148794, -0.076361719159604879437, -0.10957926874689910557, 0.0027849647992298789088, -0.00047204001118300933926, 0.069387562012853995497, 0.1202268016798509892, -0.15722127080697423374, -0.17348334021941591576, -0.34750993698157911505, -0.4306340234217196361, 0.25592930937433366889, 0.29272786696227376391, 0.89803989341652912248, 0.42894253042841035128, 0.80764101265733667656, -1.0119267694495412968, -0.038557109538814519911, -0.29753021062070239555, -0.052405524507834276571, -0.063890551260129033184, -0.038210563318028127611, -0.054833362353974436643, 0.0013952838636999886825, -0.00023608614675063352537, 0.034667393120659889538, 0.060161039317539917459, -0.078558784282471219584, -0.086811135096279259948, -0.17052577031441601418, -0.21548879873646650807, 0.10741142530502149899, 0.14648050866337228304, 0.14986173697025292895, 0.21464206783358963371, -0.2791130852403586049, -0.50636714208926458802, 0.98070595851787800701, -0.14888461024604163208, ]).reshape((20, 11, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cs +nb_knots=4 +knots=np.array([-2500, -150, 300, 1500.0000000000000000, ]) +absorb_cons=TRUE +output=np.array([0.026705483244849264474, 0.029839625165101336945, 0.025137490946490849419, 0.032188537945938233698, 0.021607394654091297004, 0.037467894551815809911, 0.013655036980899055293, 0.049314030316796791942, -0.004274510570643489521, 0.07576300788030972122, -0.044664576703176542272, 0.1337724526334178321, -0.13422281221596993328, 0.251582066127820414, -0.31121876398729647617, 0.43612872129651875097, -0.47985225176217655152, 0.49291724756068344693, -0.081762536217311512776, -0.57008353784816034882, 0.10575886843256800118, 0.098523720643000009534, 0.10937645918695998448, 0.093097559739294566405, 0.11751580252413190708, 0.080890140328454290808, 0.13582591101899046948, 0.053438242334149517465, 0.17698108482519578355, -0.0081682818617542177903, 0.26907668054096511856, -0.14499960251139776268, 0.47046169477357585587, -0.43311804519238522593, 0.8566919676788534721, -0.94615480020651354653, 1.1710825622951557268, -1.4966789629626817693, 0.019850657594207062745, -0.7294516591807701511, -0.065495278981390098183, -0.065538150305470069257, -0.065472788689835886844, -0.065568482416232795607, -0.065419575517949940524, -0.065631137544391218719, -0.065286317209239316806, -0.065744866169428622937, -0.064914403751873434034, -0.065874953263984459273, -0.063671751390664124703, -0.065668915889071088898, -0.058354957302844213951, -0.064207225531959205567, -0.028319888642541334034, -0.061612158154530236032, 0.15860060924423530215, -0.060152247616144620401, 0.96974734313860999624, -0.071414854005294861605, ]).reshape((20, 3, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cs +nb_knots=5 +knots=np.array([-400, -50, 10, 50, 100, ]) +absorb_cons=TRUE +output=np.array([0.21482323419002713472, 0.24750397604597326739, 0.19883614002139288202, 0.27258973708238182221, 0.16379621347999451242, 0.33062932586024107451, 0.090229192760086424085, 0.46740970723200020442, -0.043673571594035724697, 0.78496238070321600055, -0.14225997541844798144, 1.352022453322457185, 0.3403195391608931919, 1.6947780812699095865, 1.6168904854104195756, -0.12774151466578054226, 4.4891751144718545774, -5.4563586958095688928, 10.951815529860082776, -17.445747353383097789, 0.78661625540292257064, 0.77643763922916775311, 0.79017886797586167624, 0.76625062041079372577, 0.79428060270008205013, 0.73589687070232667754, 0.78216715039058581915, 0.63518798334179016329, 0.65550344333732102342, 0.30392043723920803, 0.19412499069407199159, -0.42254129005404528208, -0.4561535986725677172, -1.1523051841355156366, -1.7794911913869626563, -0.26332862233794968043, -4.7570007749943510333, 2.9350973501194954629, -11.456397338110976492, 10.131555788148743247, 0.21540397689706236584, 0.19368025263260429947, 0.22641495625607274689, 0.1776489056064568528, 0.25155233513796670941, 0.14240007942952948028, 0.30993541465339075058, 0.067271686044363815382, 0.44245515455816608608, -0.080352654001592846433, 0.58572719290272645676, -0.30336068837952584465, 0.016951242449324648714, -0.3319833812262538153, -1.5163892893085060276, 0.9143206895602743467, -4.9664054857636248386, 4.3390336686705470726, -12.728941927787642996, 12.044637871668662399, -0.24478425848794690967, -0.24574753349402200797, -0.24311234670203171748, -0.24447893336440842948, -0.23629987575155153579, -0.23582487990744877004, -0.20434545124769434854, -0.19103328802457081315, -0.055793360625630179783, -0.0080996580588084746144, 0.39680666612040660368, 0.39418417396254185059, 1.016323619403686207, 0.62129681239849587904, 2.2740869262794469741, -0.76498115062552785037, 5.1040543667499091995, -4.782338947138994989, 11.471481107808449096, -13.821393989294298521, ]).reshape((20, 4, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cs +nb_knots=7 +knots=np.array([-1000, -500, -250, 0, 250, 500, 1000, ]) +absorb_cons=TRUE +output=np.array([0.18906235677058036426, 0.18778525841872689695, 0.18966313099776943574, 0.18676205783172145081, 0.19092371457093507137, 0.18426214279619892999, 0.19330747373751991369, 0.17770329603139525809, 0.19648166130871616564, 0.15897921699813499785, 0.19369977803300092445, 0.10544719310340035234, 0.15040730339948449323, 0.026126087939682636485, 0.014566423626603465513, 0.71038417591713942656, -0.0044258520659356658661, 0.37477303749040830061, 0.11191608928948779123, -3.5378245461949706652, -0.1717114269621455025, -0.1641796852631927095, -0.1753614922544594612, -0.15832977440814030579, -0.18329458477753993173, -0.14455385888762556368, -0.19975455127362412577, -0.11060689494904693553, -0.23004851008792162603, -0.021054716326888309186, -0.26742505651389464338, 0.22697177040482915955, -0.233733177660145508, 0.79112685520733139199, 0.0087978598061598800584, 0.36982567289124945731, -0.019154626403592486805, -0.30951045809435018263, -0.039292263384108856716, 1.0312889189371063914, 0.550395590305010729, 0.54949597448884435202, 0.55072323934346578689, 0.54860843215917232119, 0.55116651719216569472, 0.54595839995564021674, 0.5507105841767095944, 0.53682026836985941021, 0.54272290221675423272, 0.50167044456244525019, 0.49401178725604522057, 0.36566698512261336385, 0.28011631034896739001, -0.03551586186561946773, -0.15096545178713224877, 0.063629989613431983675, 0.133595751562454651, -0.72836523541381203994, -0.59095728594899554764, -5.2594893416580195122, -0.095090409079557833283, -0.1030766681400390461, -0.090988045895585706324, -0.10887508452680887128, -0.081496719465270400784, -0.12133034539926186579, -0.058865730473533696421, -0.14644031510302549237, -0.0020110794198277630838, -0.18907748512879404834, 0.15000794369741921042, -0.22502359947941463769, 0.5462684746707909822, -0.11817275982033918769, 0.95064928964895001329, 0.052430922211166117175, -0.40184197213040517838, -0.16340199015776293856, 1.0056597912908593617, -0.79932421729955860368, 0.03971313277885706039, 0.041414831889495302975, 0.038837883046586599289, 0.042648161751521966589, 0.036811186605924875459, 0.045290364726222026581, 0.031978640736114505305, 0.050580394866669355081, 0.019931365400903504337, 0.059364669508446515911, -0.010779243096346216579, 0.065589985310555209974, -0.071477633391997127954, 0.036649613012278252355, 0.13265213083724519683, -0.017297782300268411959, 1.1319824969476413035, 0.066678235503076957458, -2.1076119483122943699, 0.36704351417936742497, -0.098246537944137943277, -0.098542071754031859698, -0.098088618240313230068, -0.098745945231101361905, -0.097708943948828105852, -0.099149563571540588747, -0.096734808676916902992, -0.099784603436978008828, -0.093975228815392539139, -0.099897241328297553542, -0.085336692453571283412, -0.094243446676616243751, -0.058668216352278305947, -0.060228845196453252575, -0.018756415239227899883, 0.03177289587597233872, 0.19240899911984374326, -0.16120768980326213859, 2.2227564852817449648, -0.98762351160861328037, ]).reshape((20, 6, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cc +nb_knots=4 +knots=None +absorb_cons=FALSE +output=np.array([-0.00011851815295720334641, -0.00012663567739435794201, -0.00010982693555193819436, -0.00012486657068400786952, -7.8574573747497574675e-05, -9.7456835655811038625e-05, 5.4155250158153698734e-05, 7.2018696214385270055e-05, 0.00068058583050101088829, 0.00094879940917660596233, 0.0037183147633434721069, 0.0053485055580019882915, 0.0183840295424396033, 0.02677749980087675008, 0.086329741280370991818, 0.12474145818684392872, 0.3626441834851739654, 0.49882426586368627808, 1, 0.99999999999999977796, 0.35563445619191813574, 0.46362413648379807718, 0.30171426160013936624, 0.54469854427884600856, 0.18065455579032740907, 0.72714127654712401583, -0.089788280381099649929, 1.1356676987661198375, -0.68581279037676712296, 2.0358855654123400036, -1.9635811732571735178, 3.963516193961472478, -4.5268166706294525881, 7.818994828526680152, -8.8143777554827753562, 14.211587381298102173, -12.092085343347227067, 18.821721967074164894, 0, 1.1102230246251565404e-16, 0.64448406196103913413, 0.53650249919359616069, 0.69839556533541258254, 0.45542632229183804826, 0.81942401878342008281, 0.27295618028853169124, 1.0897341251309387022, -0.13573971746233581825, 1.685132204546259338, -1.0368343648215159192, 2.9598628584938277974, -2.9688646995194716283, 5.5084326410870145807, -6.8457723283275555559, 9.7280480142024003953, -13.336328839484941966, 12.72944115986205027, -18.320546232937854114, -5.5511151231257827021e-17, 1.1102230246251565404e-16, ]).reshape((20, 3, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cc +nb_knots=7 +knots=None +absorb_cons=FALSE +output=np.array([7.6647956129152551405e-07, -1.1550595444117308123e-07, 1.9331333022628060142e-06, 7.0074370880358996831e-07, 4.276544862176869743e-06, 3.9889844050692401989e-06, -8.8286906818606534835e-06, -1.1748087754222518581e-05, -0.00018052779655174404014, -0.00026002337472508241234, -0.00087512057847980513799, -0.0012887090681721327309, 0.0010150616469118238505, 0.0015068191039899082179, 0.047197284048099072407, 0.069183314412051222231, 0.31391535501834866295, 0.43677277426050831188, 1, 1, 0.00010414066623386542833, -0.00015235200709813872134, 0.00016280595673724983273, -0.00043421191677436572591, 0.00016730985750816495974, -0.00096382547591343699107, -9.0113367500726122014e-05, 0.0019506005877063976872, -0.00042706768120516621842, 0.042844970995241649092, -5.2132124969551940641e-05, 0.27943748664501288914, -0.00082303187571104372, 1.1480003233353344161, -0.045428857401670741378, 2.6726262314060083014, -0.26572750370216563498, 3.4985477308433670096, 2.2204460492503130808e-16, 0, -0.031639925468625686167, 0.046730544589411379675, -0.049698223025307776413, 0.14261932064706925316, -0.051804308700160631163, 0.44426741959012128191, 0.029985561329029603028, 1.2694922528331589184, 0.18639387492323189477, 2.6501418567322971853, 0.29516026175368154094, 3.4280258862936845432, -0.075791571757795037079, -0.87883069340180242079, -0.70490461473281773586, -10.07981330853315427, -0.24791206297674328596, -16.148116252431378825, -1.7763568394002504647e-15, 0, 0.9404004428081522704, 1.0229943455861092438, 0.84837282177641593073, 0.99419676362025177774, 0.5526597738396983317, 0.71315928497606728698, -0.26997136265236038044, -0.36417829458474493265, -1.6835610275209540454, -2.2695939445331143602, -2.6912296816355203433, -3.6212526616197560081, 0.7249087759092099903, 0.96643128272326350725, 8.270877054240102666, 10.639570935701080145, 13.016842606390081727, 14.65915427188926401, 0, 0, 0.091455790248830992617, -0.06982269652782702174, 0.20182330529950023856, -0.13687095276618752027, 0.50015399051603726122, -0.15701950364285152673, 1.2380162944797474811, 0.093052186884682086543, 2.454295887293517886, 0.57831424352675386835, 3.117018133244208844, 0.91526479748152955729, -0.79779073451863469213, -0.23433512959673663545, -9.2728475980951614588, -2.148398325632811634, -15.512250940383852438, -0.55028191775469181835, -3.5527136788005009294e-15, 0, -0.00032121473415268157747, 0.00025027386535885344336, -0.00066264314064781932364, 0.00048837967193203002999, -0.0011810420579453353648, 0.00055263556817129462322, 0.0020684489017660893928, -0.00030499763304578722534, 0.043478860781959838278, -0.001447103346453879405, 0.27997853934107919116, -0.00018679973229867273543, 1.1484815005960040679, -0.0027726021640539499913, 2.7051067319414512369, -0.15316884735317959354, 3.6951325456543355763, -0.89607660680706602285, 4.4408920985006261617e-16, 0, ]).reshape((20, 6, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cc +nb_knots=10 +knots=None +absorb_cons=FALSE +output=np.array([1.7052675937596968357e-07, 2.1554130872244172271e-07, -1.8766481785820174288e-07, -2.5625876315796275659e-07, -1.3028476697477565147e-06, -1.8631355726629473538e-06, 3.6693095004218680534e-06, 5.3764688723538902118e-06, 6.0796641288638842218e-05, 8.9528552951850039502e-05, -0.00012887069103758740009, -0.00019001548651089925079, -0.0035275680979317425995, -0.0052024266625657657193, 0.0035256702065387685724, 0.0051982990643293265631, 0.2362999429577772037, 0.33323526570676581526, 0.99999999999999988898, 1, -1.5536971506019493448e-06, -3.7723308315471718504e-06, 1.0498525832867015351e-06, 6.1264614941971342081e-06, 3.3796481270836038393e-06, 5.4203738638415076344e-05, -3.5129100336125819986e-06, -0.0001705894910869632658, -3.7468155003797335172e-05, -0.0028884082386604389286, 6.8182896976374759469e-05, 0.0061884953395126701681, 0.0018130647206160395782, 0.21325100724817980247, -0.0017981230343969457908, 1.0927529255884664838, -0.10407530163420519731, 1.8409714784490120998, 0, -2.2204460492503130808e-16, 9.8228540403516947542e-05, 0.00024501849587308256306, -6.3993936608566740908e-05, -0.0004010047866267046901, -0.00018304683587852169481, -0.0035611604429654220016, 0.00011419029847733929632, 0.011357234442518585049, 0.00050617348630547251507, 0.25226492984599047098, -0.00032188615231765204967, 1.1982978420717516066, -0.0052489266241784434189, 2.0211806750240537411, 0.004422931600446426692, -0.32320182404955488664, 0.24763812678503760445, -3.5956683328958609636, 2.2204460492503130808e-16, 0, -0.0066286721449819972773, -0.016550854830837284648, 0.0043124327641686751103, 0.027487867638282981186, 0.012275008624007566552, 0.3281445173550811556, -0.0074331317422015865878, 1.2933290334062270688, -0.029450751586844299557, 1.9518047804513476429, 0.011641882663420602406, -0.66721597637483753829, 0.077812573766972065181, -4.01958848618877429, -0.02237250215454568425, 0.74181768967199701592, -0.70957277332229884426, 8.2779135644074397504, -8.8817841970012523234e-16, -1.7763568394002504647e-15, 0.14341792272585895951, 0.77593418511036460483, -0.090433414170275921995, 1.1259556534302141984, -0.25737004638880062179, 1.110930597939268516, 0.15569410127086877327, -0.56800026419801152855, 0.61436360579663806813, -2.2407355088743035054, -0.23716773295804302601, 0.86370268070518285697, -1.4404805919834702266, 5.2118285879993342391, 0.2780344963834942007, -0.97074031271066019144, 3.8024793557257794419, -11.342987956092152046, 0, 0, 0.88922860214889154484, 0.26150593343291061998, 1.0527176310249597435, -0.16739004844301930142, 0.90250111388972187321, -0.47638677331480472343, -0.44192413673958003129, 0.28819070120487033648, -1.7434322051050550328, 1.1372558503535050711, 0.67215428910723273859, -0.43917237872741754501, 4.0596131096953849138, -2.6712549469068491703, -0.75992694414757844257, 0.51959152341465042468, -9.0955055761811927084, 7.3255691971501466497, 0, 0, -0.026500878677340050649, -0.021443321240789712384, 0.033955530529363592285, 0.01455399094161052842, 0.34654945272048409688, 0.041426545282572141415, 1.2822017995143766278, -0.025084826033741181028, 1.9080047293712101286, -0.099372016748206934422, -0.65055242209998476177, 0.039244657655196912849, -3.9247579397546936697, 0.26136174203674272798, 0.7301169577862545168, -0.074258542407508620897, 8.480299193362036192, -2.3225008358095564631, -8.8817841970012523234e-16, -1.7763568394002504647e-15, 0.00039214456274060853838, 0.00031751196529807511858, -0.00049656870424369891313, -0.0002157937723172946836, -0.0038324354523821676718, -0.00061725037261922916041, 0.011518730827296382035, 0.00038505493185519946639, 0.25286023990754330493, 0.0017067621188927551389, 1.1981634895781139161, -0.0010852069418095661169, 2.0228506259066678652, -0.017693728679951309379, -0.32609759852778003042, 0.014908398163377523105, -3.7765166040071465048, 0.83470297192668896358, 4.4408920985006261617e-16, 0, -5.9639851815191078669e-06, -4.9161432965675507926e-06, 7.5203048707079762948e-06, 3.4647891244179194819e-06, 5.7876642390457017258e-05, 1.1182950401982235801e-05, -0.00017170982870512408684, -1.1720731503335203019e-05, -0.0028751203560827250441, -0.0001259174615164541705, 0.0061430676556425214963, 0.00022990175893332354118, 0.21192565237063318295, 0.0061175761298287428119, 1.0940951118875659187, -0.0060681567350964193963, 1.9189536363142121189, -0.35123535284248763588, 0, -4.4408920985006261617e-16, ]).reshape((20, 9, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cc +nb_knots=12 +knots=None +absorb_cons=FALSE +output=np.array([-3.5802310279784754585e-08, -4.6262647978685225562e-08, 8.4108204760015214405e-08, 1.1691317515513621075e-07, 1.3383585568882782416e-07, 1.9334920179260735574e-07, -4.203667662871902566e-06, -6.1443325945584099136e-06, 8.870740522791627539e-06, 1.2991653852666520431e-05, 0.00025968489610813934136, 0.00038043548035123880531, -0.001538951033558028092, -0.002254678726504918268, -0.011894389332899407696, -0.017426311105119260403, 0.16787692522771835435, 0.2391755401848442153, 1, 1, 1.5979133269021421162e-07, 4.7768854385179628339e-07, -1.9425098428285929911e-07, -1.661723207394062299e-06, -1.2068855552733148196e-07, -3.2055922738442340194e-06, 1.9511133954906500148e-06, 0.00010616629891630242227, -3.4565252886977172405e-06, -0.00022600512710102375891, -9.8259384682155117077e-05, -0.0066248710130454744813, 0.00057889080026267934753, 0.040648127270414641243, 0.0044706215223907566636, 0.59368709533766184094, -0.057610288739808043768, 1.4572996890794969183, 0, 2.2204460492503130808e-16, -5.5109923531389489217e-06, -1.7294660575127571221e-05, 6.1519217837447675384e-06, 6.0756378562884462338e-05, 2.7216035102121806338e-06, 0.00011763795929723115457, -1.6476765274556428198e-05, -0.0038995592960682475339, 9.9827397529189624958e-06, 0.0083454262915318017102, 0.00018240275250513114397, 0.34605772709145571353, -0.00095280597828643811414, 1.3922985845928645965, -0.007230442437518780005, 1.0497271498165361425, 0.092837834238923916397, -1.6519805635559703383, 0, -4.4408920985006261617e-16, 0.00023261122232546074806, 0.00073160846398710190595, -0.00025857850183971374958, -0.0025712720147247018071, -0.00011201881409144995674, -0.0049793706065786738982, 0.00059472548275806631952, 0.20119309669405308072, -0.00020482161298259401474, 1.1583114626193435903, -0.0013424798341694420094, 1.5703649598779465535, 0.0025261771262702131455, -1.2014100351887648799, 0.013860165507571235721, -1.7597171609627610955, -0.16373073924917352917, 2.8753824912917806955, 0, 4.4408920985006261617e-16, -0.009603671354393113202, -0.030208220454698501978, 0.010673917274214628215, 0.11304566492258458221, 0.0046199850162510491813, 0.84717578954956962445, -0.024382491288093402493, 1.620889030714223189, 0.0080875614382544102482, -0.43741011526471584858, 0.044600501680212630007, -2.3916675588781384221, -0.040106814398597687155, 2.0236045109652547325, -0.076082896664545401899, 2.9650152140638748044, 0.36507708741878691638, -4.859029716718211489, 0, 0, 0.10357736791963742529, 0.85603579089397319191, -0.11294862650356479739, 1.0800085662880150039, -0.048885819171624864121, 0.24015822941969325321, 0.25794065020098305707, -1.2534166511355830931, -0.085429974450229081984, 0.41506987095643310681, -0.46751914821604279027, 2.269740510670964273, 0.39810586745371900896, -1.921845360279117898, 0.60183408291126982981, -2.8261756066203411741, -1.2434080193894079258, 4.7739148511542310871, 0, 0, 0.94933899366841034695, 0.20425903192036259926, 0.97636197471447405682, -0.22571398353340010878, 0.19529869420992360118, -0.097692387302149769068, -1.0167283962036961498, 0.5154656778185841004, 0.33669612032614604225, -0.17072771898201555274, 1.8413288872915176686, -0.93446780726201750245, -1.5601117305432461446, 0.7966817961552830063, -2.3016241440126483653, 1.2113186062078835636, 3.9901615392586013975, -2.5959908523544878989, -4.4408920985006261617e-16, -8.8817841970012523234e-16, -0.044595107940631317778, -0.031547859459583466046, 0.12905624158450940131, 0.036024366939322927106, 0.85410524864504355769, 0.015592380256197772501, 1.5843319897343188796, -0.082289673658138620671, -0.42531415373425501825, 0.02729325191154396979, -2.3258032067945428878, 0.15046179406667054002, 1.9695869973481714421, -0.13497763436486276412, 2.8983680069011104052, -0.25382247697616189264, -4.9233259421066879469, 1.1940247607627194615, 4.4408920985006261617e-16, 0, 0.0010800130290116449761, 0.00076408094461186495429, -0.0029589630116448285488, -0.00087264995012978460905, -0.0051470914118511394697, -0.00037804019106299111778, 0.20207527387121515527, 0.0020070544765826729347, 1.1580252366043886081, -0.00069118022426611653436, 1.5689665948166240383, -0.0045290910522769603844, -1.2012679739112754884, 0.0085164006815267589978, -1.7671162635968691301, 0.046706182018272840439, 2.9931065266471703623, -0.55166786071240503375, 0, 0, -2.5513815072961419693e-05, -1.8078345013767598096e-05, 6.9882718216176479414e-05, 2.0732787925975703258e-05, 0.00012154373149783886249, 9.1724360658872410822e-06, -0.0039185795650754015607, -5.5540121878291909925e-05, 0.0083483300512910106617, 3.366784700094217677e-05, 0.34597774598037167593, 0.00061544857656690001111, 1.3929650741667591873, -0.0032153965723222335815, 1.0550792027144637597, -0.024400898124765986463, -1.7214890573288510467, 0.31330563624629470532, 0, 0, 6.9427404324062452156e-07, 5.092710402106320213e-07, -1.8900533691006157141e-06, -6.37008124488906817e-07, -3.2769559589167800075e-06, -3.9927796023670766917e-07, 0.00010555708713181393625, 6.542541903472452638e-06, -0.00022369557760034113753, -1.1651681607648470274e-05, -0.0065527231879012725474, -0.00033154755847665279712, 0.040215268969781864383, 0.0019536854662268524074, 0.59033605648767484286, 0.015088206344919037616, 1.5005041340227291968, -0.19443397537829132382, -1.1102230246251565404e-16, 0, ]).reshape((20, 11, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cc +nb_knots=4 +knots=np.array([-2500, -150, 300, 1500.0000000000000000, ]) +absorb_cons=FALSE +output=np.array([-0.03303972668455883166, -0.032723631630874550069, -0.033194598680918049882, -0.032481019964223409313, -0.033535293013993730527, -0.031917861017270607316, -0.03426231263902488472, -0.030563998358814094963, -0.035695429397679306893, -0.027087023457207957261, -0.037865492526216820712, -0.017178820311233713308, -0.037086543898716496648, 0.014593291596970280055, -0.0029879266785189512179, 0.12551122978070125558, 0.23922654623041611499, 0.49782433286763683178, 0.98768627515810170081, 1.0869145050394330987, 0.66601437778113736776, 0.67187778857060287407, 0.663080503426190071, 0.67627141867934648101, 0.65647421427937902028, 0.68614414294517134252, 0.64158611076564242559, 0.70828643005086278084, 0.60798624557560698722, 0.7576791553065401752, 0.5320956270640739838, 0.865894348010412096, 0.36241579174811910935, 1.0862902782459773476, 0.015083764342983273232, 1.4407803230899152158, -0.4134231048981120149, 1.6325959428355898417, -0.025636829423459156496, 0.35643164379996317148, 0.36702534890342142226, 0.36084584306027167599, 0.37011409525472788173, 0.35620960128487694218, 0.37706107873461469637, 0.34577371807209933419, 0.39267620187338242443, 0.32227756830795128984, 0.42770918382207229191, 0.26940786815066769533, 0.50576986546214286466, 0.15128447230082164854, 0.6746707521505973526, -0.10088356984294755136, 0.98790416233553579595, -0.56629155287061583302, 1.1741965586676958999, -1.1304202757032262294, 0.037950554265357511197, -0.44334614883939615915, ]).reshape((20, 3, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cc +nb_knots=5 +knots=np.array([-400, -50, 10, 50, 100, ]) +absorb_cons=FALSE +output=np.array([0.015162953484350691347, 0.017003239050418700318, 0.01389317445221215086, 0.01781864311343593632, 0.010107471620559638215, 0.018108516505766211746, -0.0037108407090391832411, 0.013008750547323907898, -0.048928829481261350287, -0.0040236561643654800147, 0.092210640717886122042, 0.1378672467189187012, 1.5241189647343453828, 1.1908052000719462349, 1.3336312280306561462, 0.1631244792608173011, 1.8059790376981266213, -0.013880364847569600512, 0.0084813946159772030109, 1.4226717441894676242, 0.085563268199896264088, 0.11668451836115162346, 0.071115177265946433183, 0.14186260471454884002, 0.041497176936461224739, 0.20374514230967810668, -0.0090968367480324351104, 0.36464078885855299994, -0.046829263271134111135, 0.78133519562325359775, 0.0086505068072265829671, 1.4941773335338757178, 0.083794480856750619413, 1.5469438185966697397, 1.4536819883528222519, 0.01009019548322653316, 0.24373154263518609364, -0.026484165693594415025, 0.45865093019281244491, 1.3856971378298170716, 1.0470804297077640488, 1.0403159202859915133, 1.0474228585236060596, 1.0301709677530419551, 1.0403805448593048677, 0.99263889345454958679, 0.98179764669852209735, 0.84465069052528973792, 0.662325916413059268, 0.31424672127915465047, -0.11097382584830663144, -0.73780817614306393182, 0.10634636847011158522, -1.0591219159940026273, -0.97302313835893716742, -0.14685901225266156933, 0.065659678129581511286, 0.92642956346749238961, 0.738106497929031935, -0.90865791610827972846, -0.14780665139201115688, -0.17400367769756186487, -0.13243121024176468525, -0.18985221558102688411, -0.091985193416325716775, -0.21449255226999386359, 0.031010030758549505386, -0.22230022993116671515, 0.43343217633933617261, -0.091558260738042823723, 1.0101126783231939577, 0.10576359589026917973, -0.71425981406120730988, -0.67862710267461334723, -0.81429007802454078657, 0.97364433750861778538, -1.115370258462895503, 0.11393496707367145593, -0.20523882273782165231, -0.89971096591100430118, ]).reshape((20, 4, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cc +nb_knots=7 +knots=np.array([-1000, -500, -250, 0, 250, 500, 1000, ]) +absorb_cons=FALSE +output=np.array([1.0865454545429926135e-06, 2.4398181818138797716e-06, 5.4730227272719212013e-06, 1.2258383522732035908e-05, 2.7392640980115554039e-05, 6.0996505637431891467e-05, 0.0001350924767677991363, 0.00029670296713464952565, 0.00064309569467692253436, 0.0013643251258789318436, 0.0027908209016161266564, 0.0053380236469475778743, 0.0088335867924326759437, 0.0091533086384256254903, -0.014306039442788853755, -0.041433352007441685838, 0.31405170261824960631, 0.99790444618953877409, 0.027724626841434521496, 0.0068039590138881103284, 0.00064727402371540310524, -0.00098920483399211889264, 0.0014426438433794426357, -0.0022558485342761974701, 0.0031770096755419320253, -0.0052223605999905525765, 0.0068053308523184398438, -0.012426118572852515309, 0.013644913148864869917, -0.030618365664116811709, 0.023048059495840829414, -0.073679585582029943902, 0.022074755528899835111, -0.091195081533291866283, -0.0002259526328000187323, 0.78626962637629815855, -0.10027585488170688566, 0.03440373467483604647, 1.0473889505746853956, -0.065646799659779347946, -0.003108653786561336313, 0.0047444954940711828867, -0.0069334472845849707406, 0.010810919925889327445, -0.015293474668169363198, 0.024997761679919142108, -0.03288173605395704191, 0.059489869048364188431, -0.066524536226034367004, 0.14842140322069641289, -0.11509599902262178384, 0.38653940175293038939, -0.12009256540661154833, 0.89487060989842726055, 0.023974235745902267025, 0.30753674660261021145, 0.028225509751146779513, -0.016286171465612203635, -0.087188251557721807572, 0.95672514836045408071, 0.99996516654545464231, 0.99992170981818173647, 0.99982413427272720519, 0.99960527135227272844, 0.99911513172301125163, 0.99802008661061780703, 0.99558245566310810126, 0.99018628040560352499, 0.9783435545897927188, 0.95270542773753197352, 0.89842166335737938532, 0.7877650145033745499, 0.57753870046138200411, 0.23531461121027275052, -0.101438596654484528, -0.076220798157655950122, 0.080593293321039760624, 0.00045998670001021375875, 0.022032291428807804223, 0.12976646713984618664, 0.0031521796047431342204, -0.0046466867667984135259, 0.0071530971936759326843, -0.010318124209980239492, 0.01639748407299900651, -0.022529876245437452376, 0.03838002020499131639, -0.047302525716890531093, 0.093325747193657035417, -0.090212229951197098199, 0.23900090287817127299, -0.13160022708072441344, 0.61322255928469093789, -0.056958752001294875311, 0.958298331738895115, 0.012677886126789952859, -0.35059868303530600242, 0.01444622466557134513, -0.00094091415750929829898, -0.032059943389195363905, -0.00065705293280633844839, 0.00096724647035571764686, -0.0014919010479248961606, 0.0021455230825716264942, -0.0034235434443629607359, 0.0046733920492536690228, -0.008021163143228648984, 0.0097557918686406452924, -0.019432774400957149308, 0.018339439531206425116, -0.048165447610385929422, 0.025637372759501717012, -0.10157703666079390126, 0.0088153037874612247271, 0.13369802124527602194, 0.011169891059399323502, 1.0280040322265766584, -0.030928220764344298982, -0.0090167031296965738374, 0.004411168534786328102, ]).reshape((20, 6, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cc +nb_knots=4 +knots=None +absorb_cons=TRUE +output=np.array([0.19511874223105002413, 0.19328136140945711974, 0.19603076753463616333, 0.19189278126562986371, 0.19806475922765381936, 0.18874078982063985377, 0.20253543882853958236, 0.18155709647843842891, 0.21199988818367701549, 0.16514182390533327371, 0.23031856584684334832, 0.12705798198206638694, 0.25709528872115156028, 0.036195691844765578993, 0.25138520448010354125, -0.18708237186262471896, -0.013972372776853255599, -0.70106203022920721146, -0.96214970344564842986, -0.96214970344564820781, 0.68403334135296989249, 0.60311193997153489388, 0.72443479807328026165, 0.54235372240853074732, 0.81513433908152477247, 0.40561204773518105826, 1.0177088251859824908, 0.099342480096702004411, 1.4639211866974952692, -0.57590399808120096292, 2.4193104627273829266, -2.0236042389889199455, 4.3297301577097133674, -4.928177533945309996, 7.4943452610127803126, -9.7886574066511276015, 9.753529003891806326, -13.510350272896850754, 0.23706294230926167055, 0.23706294230926180933, ]).reshape((20, 2, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cc +nb_knots=7 +knots=None +absorb_cons=TRUE +output=np.array([-0.09996264143545301184, -0.11347888802625775984, -0.085118834474127241796, -0.10911447157987791412, -0.0376192915747680795, -0.064440162552667323848, 0.093968376147604365523, 0.11142321074687944193, 0.31776266530375074648, 0.45570604000055198179, 0.46380277431584160386, 0.89300636651257359055, -0.14510213799700033555, 0.96333821295332311418, -1.5132894536153895793, 0.82432258344543585249, -2.5988714669036583338, 0.92635413953045664393, -0.14134351039860873489, -0.14134351039860867938, 0.23834091756376188376, 0.35248629179932566835, 0.18039220953514537027, 0.43583938337484684489, 0.050144193047881382985, 0.61552699880967853829, -0.2237848683809608441, 0.97413442320198884161, -0.67208413897185625974, 1.5362399491838241161, -0.95632335803874857216, 1.7726129713790426123, 0.31347441526077174379, -0.38061109255151409636, 3.2553930274666940115, -5.093077784759170612, 6.0469258529758489473, -9.2083208514013143997, 0.38134573025237739063, 0.38134573025237838984, 0.36086943997122683525, 0.36667024194421360406, 0.35446911502732253441, 0.36478130178265055772, 0.33382084885464979873, 0.34553973621188488474, 0.27476295985860993421, 0.26982601949673939989, 0.15921647742368139067, 0.1214671481463027447, -0.0048407176404455702981, -0.067803846828875705133, -0.11067535403631012514, -0.10302868958722773141, -0.2301530127015978533, -0.064773144847515770617, -0.49542622407015213248, -0.23755670608026469015, -0.81858279646244769268, -0.81858279646244602734, 0.36026977248710895241, 0.23461157027634554906, 0.43091928395041323441, 0.1550818089508944897, 0.60166186948369282383, 0.013499889397706944794, 0.98534266394190206384, -0.20102910227880538274, 1.5995282267915371666, -0.53077336516331363736, 1.8709434423002264669, -0.7329934007992182643, -0.41020716027288028904, 0.26173115951276498814, -5.3296664149739436667, 2.8167844608879319956, -9.2446193976201840314, 6.3595195952585372723, 0.3796975489346396393, 0.37969754893464241485, -0.09342094101113124216, -0.10518600840242132988, -0.080006629364737152921, -0.10062511887211006423, -0.036336786815554571184, -0.058504221090871715016, 0.089578204326735660912, 0.10154568474713222825, 0.33951493212221051099, 0.38266890106103862434, 0.7115379830932434535, 0.57066292250314121226, 1.0142476918808467357, -0.17457778635418924607, 1.3394445526441309813, -1.8727860878377164955, 1.5244315420174636699, -3.2891836324660186364, -0.13150260109059599967, -0.13150260109059619396, ]).reshape((20, 5, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cc +nb_knots=10 +knots=None +absorb_cons=TRUE +output=np.array([-0.010422589164110178037, 0.0456424386898241774, -0.037865479111961315717, 0.067665213698612183824, -0.082737354894918610504, 0.028116719037984471558, -0.13142165397961641515, -0.22684145450558812485, -0.14183761903259869963, -0.4397636102098926858, 0.038753040222973357543, 0.16687260126443773101, 0.24596836576748323799, 1.1496535841573791714, -0.11141233683909176899, 0.852150817442395625, -0.69719802631935023918, -0.16780336922215680073, -0.27375964350090231658, -0.27375964350090231658, 0.00075686991514895495502, -0.0026399619145559983374, 0.002329286728553797009, -0.0046772664281081481261, 0.0050464211301084280908, -0.0053347974019967861828, 0.0084202195193733477691, 0.025683527700154588219, 0.0094683775407149051856, 0.27987678132954318944, -0.0027668876775316930683, 1.1881421141921484352, -0.020680289816708941064, 1.9619971627400687453, 0.011350885804312933758, -0.30799503353642232462, 0.28512530049421225264, -3.4687076070237505832, 0.017302448352367463119, 0.017302448352367227197, -0.031423668563904168238, 0.092056168183617143042, -0.085784223470207240925, 0.18847060597276241167, -0.18459182127963985609, 0.39491427056812172802, -0.32011917407772511046, 0.75400611255752592044, -0.36683893574186782205, 0.9123381072270769776, 0.10368560537272084043, -0.284896787114018335, 0.65873659367957215771, -1.7915854614656305799, -0.28317998595666565853, 0.16934785893573317539, -2.1208025768458700355, 3.4983918640596205485, -0.65136227602061025355, -0.65136227602061058661, 0.15390547566386716949, 0.72999661431747953078, -0.052325183145307693766, 1.0578646982284642952, -0.17410117772396246916, 1.0826889596002884364, 0.28795108435587113416, -0.33988255901594949249, 0.75706886705991383035, -1.8010717324191700683, -0.27609951573452540252, 0.70199292810649616126, -1.6861943363558831166, 4.2694489532922874631, 0.3883483777323971653, -0.72860244126989648361, 4.3993879828572435287, -9.3213910982477266032, 0.27550705134905656424, 0.27550705134905634219, 0.88473558816481134848, 0.28118622960754013906, 1.0363915332292370497, -0.13821893333931381531, 0.86682756892064050103, -0.46428766146855998675, -0.49858487332948592252, 0.19046189397427254475, -1.804569129824072693, 0.94889775503965156922, 0.68883320796217106796, -0.36989366480027330297, 4.1648803055867107403, -2.2675263648363670477, -0.80718694983894612172, 0.41585628137205921107, -9.3512295591515375293, 6.4594889011881138075, -0.11803106422832626565, -0.11803106422832615463, -0.04700419996957900387, 0.068365309897369067049, -0.04054662542658848956, 0.14767281664377382433, 0.18375758144525122795, 0.096639366434089990499, 1.0236374391375679949, -0.47105831760443933609, 1.6290138304390200386, -0.95892121020674836451, -0.57444021027476643848, 0.35538961856435591358, -3.4443839310068100623, 2.1037278825342364819, 0.51445168623435322264, -0.5476416666229180219, 7.3133339883682770832, -6.2747526284605275038, -0.5386203650629584061, -0.53862036506295885019, -0.00033055953514735743511, 0.0034830998631877898263, -0.0031226317036678898596, 0.0044763982618290778723, -0.0095705473805210890259, 0.0013288993039827501352, 0.0024048160547256620945, -0.015334684583203243846, 0.24302632748633656856, -0.02859075483432030676, 1.2008463040646732978, 0.01005831734477347951, 2.0397829199332155881, 0.047246265215163486817, -0.33369939987991892316, -0.0017774801323981149429, -3.8176499659498723815, 0.69539341686864553083, -0.018985370198741847308, -0.01898537019874227405, -0.0098485472403549607912, 0.043107558972873410985, -0.035757108373310586558, 0.063906922484069789148, -0.078090074289757671622, 0.026516000447580879984, -0.12429507538278902756, -0.2141005094608952608, -0.13680420974781898336, -0.41275099307476753596, 0.042680600816607877634, 0.15199473312943939662, 0.44252834874998403514, 0.8905421952388906659, 0.99056537832665858545, -0.23331489131404251069, 1.3587540460951703647, -2.2485068612054024406, -0.25856375708606771369, -0.25856375708606793573, ]).reshape((20, 8, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cc +nb_knots=12 +knots=None +absorb_cons=TRUE +output=np.array([-0.07766833740489995086, -0.10190625722373891637, -0.060810191651491825315, -0.095843436838280671175, -0.026956945198949221199, -0.02140480076346930674, -0.0044354303173668322216, 0.068142865158757101596, -0.10242235056407339444, -0.134962672377622106, -0.17923996606808398346, -0.32198261136183764508, 0.061769798735937714307, 0.22368036323142082011, 0.1062350870161039712, 0.86684951229524320748, -0.41431550373346520688, 0.82628193491032586593, -0.30550552892225468771, -0.30550552892225446566, -0.046843894383066776721, -0.061472670935691822725, -0.036665627178526026542, -0.057737114955866711274, -0.016253728913666141281, -0.012788703169830750381, -0.0026924622704371371611, 0.037130318979860681139, -0.061754253708923484423, -0.072908208132761248566, -0.10784991719446739011, 0.15587963325803569359, 0.035948683163131246732, 1.5026771080647596257, 0.054139137539069064065, 1.2144591386571002012, -0.12227506507632453225, -2.0325190387816292059, -0.18423666748038231011, -0.1842366674803827542, -0.10253186808225246696, -0.1341028859441055765, -0.080717296578839040078, -0.12938111733003612724, -0.035779041281597902258, -0.033296176820796892504, -0.0052764476269259964411, 0.29121358356235121922, -0.13571696227220694797, 0.9800391391797497187, -0.23836784885271891654, 1.1531098931327661283, 0.083488884262169646422, -0.95923704223174655059, 0.14850642088377782879, -1.3982914277816191895, -0.63569333679288853034, 2.040472414748102814, -0.40421944208659177367, -0.40421944208659132958, -0.014736324481430123495, -0.036942635828954392685, 0.0066553430184999587058, 0.1067120469886325973, 0.0028385673937536314362, 0.84576148428624664533, -0.024675731668667714308, 1.6253851750682712929, 0.0013193004864854235899, -0.44631406733607736914, 0.032762082318650569135, -2.4125076929166153761, -0.03606306801106605453, 2.0357000324722602791, -0.069357883037490283828, 2.9830669079191580728, 0.34150454252272821609, -4.9007299602670126859, -0.020189059463686463008, -0.020189059463686463008, -0.012482766482938594671, 0.70375642696389684172, -0.20381708316356489386, 0.93679207951689691392, -0.089167436412632875009, 0.2081777984642331214, 0.25130986547048167479, -1.1517493252694694927, -0.23847465841613846305, 0.21373269726886048869, -0.73521082895311973271, 1.7985010371260992112, 0.48954351921215394361, -1.6483400566813448673, 0.75390085346775681518, -2.4179886586261010173, -1.7764330770220631006, 3.8309842164304526158, -0.45651730144672891809, -0.45651730144672891809, 0.86855075539761661396, 0.098258969106073332234, 0.91310939823129155801, -0.32540547292490512588, 0.16725908432707276008, -0.11995362876401588492, -1.021344015679647832, 0.58623523352093998007, 0.23016332628828412021, -0.31087640693906454237, 1.6549915252178080127, -1.2624926460002787731, -1.4964629433416147819, 0.98706595992626866565, -2.1957720652086201163, 1.4954532454044999756, 3.619128405599101761, -3.2523549448400173034, -0.31777688966039602247, -0.31777688966039646656, -0.068946719872015810315, -0.063498950974957252269, 0.10999032024314105149, 0.0059748385118500793589, 0.84565340326272575577, 0.0088822808061620184272, 1.5829407256504981483, -0.060957945254261673707, -0.45742582387218383433, -0.014951096212291247606, -2.381969985853732652, 0.051586837169672689063, 1.9887723465897544362, -0.077591047241966609738, 2.9302744923046657455, -0.16817713282609225711, -5.0351646834625327642, 0.99618007435765298929, -0.095785966663044092018, -0.095785966663044536107, -0.092425948063627971774, -0.12192256208017497598, -0.076168790113220086191, -0.11625762092899732947, -0.037600709993932460162, -0.026143656852116337053, 0.19673306138614868321, 0.083917187234610293722, 1.0347219995539065351, -0.16290214117344051226, 1.3532959167438192161, -0.38419175563061558343, -1.1275995644118568251, 0.22887092989596394266, -1.6446009002954922185, 0.37556943100676937197, 2.5636651809434143345, -1.3113571002380715047, -0.36780147849154309903, -0.36780147849154309903, -0.052133443997911740886, -0.06838748447056271218, -0.040727650559123369789, -0.064279681235506633263, -0.017963836831353656442, -0.014349195077656596783, -0.0068956265034833194583, 0.045590399764175990049, -0.060364684525170013429, -0.090361397122777853408, 0.22579126263553786491, -0.21095860924503515021, 1.4340181609862545642, 0.11958124964793707956, 1.1233531600390498362, 0.15886424366674492537, -1.9608032079784090129, -0.11004527519600627861, -0.20496419199835186342, -0.20496419199835186342, -0.074397287283336693831, -0.097615070510572624074, -0.058251260498594206738, -0.091806644267701589812, -0.02582498595211388942, -0.020500802148151781035, -0.0041449721977959343849, 0.065178307797134571455, -0.098329868155822383602, -0.12907473963965984676, -0.17815101427258792088, -0.30240999889208236562, 0.098829510321402941342, 0.17727868088912610012, 0.68781535762400658474, 0.27674812243204571782, 1.1588192944220654379, -0.7988804231889805596, -0.29264110323919079182, -0.2926411032391906808, ]).reshape((20, 10, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cc +nb_knots=4 +knots=np.array([-2500, -150, 300, 1500.0000000000000000, ]) +absorb_cons=TRUE +output=np.array([0.12313452571054940565, 0.12624926449090670411, 0.12157389196350212868, 0.12857954187334583174, 0.11805461329003080762, 0.13380425540627891023, 0.11009731641023581816, 0.14546384037961754276, 0.092005873745000077424, 0.17117971635322848378, 0.050459076159657625937, 0.22605161337519041886, -0.04604552699950949235, 0.33036931836460758927, -0.26444093870479618014, 0.45978406857873022062, -0.66227507648797157014, 0.32946799433163242998, -0.92301557680450230237, -0.77049779143573060569, 0.15656827198639958199, 0.14932319431509266661, 0.16018937960169490897, 0.14388705697943621198, 0.1683330978621291607, 0.13164928933754893592, 0.18663507205881160744, 0.10408933274661898161, 0.22768017116328620464, 0.042040878816280137509, 0.31905484877266732102, -0.096761998947504118673, 0.51632342198274205902, -0.39392983963941236025, 0.87954141557829357279, -0.94659228313998333704, 1.0777246444382655444, -1.6356011142349877741, -0.30993435496630139525, -0.88022048471107694478, ]).reshape((20, 2, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cc +nb_knots=5 +knots=np.array([-400, -50, 10, 50, 100, ]) +absorb_cons=TRUE +output=np.array([-0.16508056690578271075, -0.14355192166054722702, -0.17398515944924686227, -0.12432844320614395983, -0.18919890928728577695, -0.072282554700368567557, -0.19674137112973341668, 0.081531091765042931763, -0.099155660656600808078, 0.52456028958996936407, 0.059704023721638257993, 1.2036951770569246367, -0.95698314791898375642, 0.59171921208541256032, 0.40429183055884826414, 0.021134682418438101997, -1.035862596202561825, -0.18547278101676506479, 0.17821896181573629314, 0.27778784312200943685, 0.84139218015539352091, 0.82675559954147825881, 0.84628382311749461575, 0.8117240601311839221, 0.85106220741071658686, 0.76611964233460772, 0.82780911632526033017, 0.61231966988832331467, 0.61938480406110207888, 0.10352707230517528558, -0.069077289581256251516, -0.9761893286926568436, -0.74775693930080122662, -1.843017028194991358, -1.8341942282567624822, -0.13779546922177127177, -0.98442590823258591115, 0.79595721424418131029, 0.50797292743971100837, -1.8178521254738027046, -0.057675412235671304206, -0.080422948680625480633, -0.044293406826563193335, -0.094130216309427472421, -0.0090271421596601793269, -0.11523330512953809668, 0.098486792744760950913, -0.12049430358370501193, 0.45224868955998115405, 0.00077770457813844623505, 0.99175389147792825106, 0.21022065027995529007, -0.33999735782244788762, -0.33512941632144105375, -0.43693056610772496029, 0.96967275251871798414, -0.65522965575463965049, 0.17110709302995569248, -0.10439580460326271238, -0.50130803865473083647, ]).reshape((20, 3, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cc +nb_knots=7 +knots=np.array([-1000, -500, -250, 0, 250, 500, 1000, ]) +absorb_cons=TRUE +output=np.array([-0.10421720382140421679, -0.10591736328552885105, -0.10337614089781445303, -0.10720759929942245969, -0.10150561917996400729, -0.11015275422250632442, -0.097405901413871925909, -0.11694382088021060273, -0.088713078413449955595, -0.13250065888393972036, -0.07161679548265666162, -0.1625759820148384438, -0.043015722854652924112, -0.13320201735142009336, 0.0004329669515455780238, 0.78255062519422247114, -0.15088551365188454523, -0.085517465675143913839, 1.0298684606084522741, -0.098098415425510815391, -0.16366514384894217948, -0.15590949502662956871, -0.16741997729436150499, -0.14987919244601818902, -0.17557153836450387074, -0.13565965107884025986, -0.1924380512291224421, -0.10053567798805967959, -0.22324338128005483117, -0.0075691069598905688642, -0.26003599357502127365, 0.25043141090853648922, -0.21975165836638141381, 0.83055439613540549271, 0.024983098021001227257, 0.30184263751436557488, -0.049262209087217581627, -0.19989579226301767978, -0.11401362112954462058, 0.90703894735829693197, 0.15993324209937159752, 0.15937966275042819708, 0.16015824098241202011, 0.15887423467611411221, 0.16053993466300625625, 0.15746013438548811525, 0.16078344852210443849, 0.15293225108971789106, 0.15839019763395165152, 0.13656272051085360797, 0.14009527925573453389, 0.075647694069404219919, 0.05612209740148604159, -0.10118796678857061577, -0.096160226916063087921, -0.10601238997400461161, -0.32482262945752882199, -0.96018597065328126217, -0.11831810372893719618, -0.13019185052168549821, -0.080994950879331353844, -0.088844916921682309807, -0.07695736745600667561, -0.094535285708752150868, -0.067603724064711254171, -0.10672989998407718393, -0.045242921897107997442, -0.13117139070034619652, 0.011189913886947294372, -0.17196634533664997835, 0.16303832653371333472, -0.20293397921406119977, 0.56099155513187193289, -0.090666668944769990279, 0.95882707315240156554, 0.0096936222066400009462, -0.39120974264100472073, -0.081782976118326314308, -0.015000002474441720413, -0.058100318570304822219, -0.06971270937892765085, -0.068130345111184043017, -0.070517467540312656071, -0.066967604576931502591, -0.072359448172744492145, -0.064425671443484225365, -0.076646642438798442964, -0.059071504956647494233, -0.086837852317636618493, -0.048752380149832678924, -0.11050441917873819742, -0.032902936957473871704, -0.1444406050066643632, -0.018847223960927635827, 0.13413193485813351691, 0.0087208437439542339786, 0.9946764147081772478, -0.10989907326032234691, -0.020554346388292375064, -0.016958962471346181872, ]).reshape((20, 5, ), order="F") +--END TEST CASE-- +""" +R_crs_num_tests = 42 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/test_state.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/test_state.py new file mode 100644 index 0000000000000000000000000000000000000000..2c5a8e850d15379d9674ae0bd06b7c322327f8e4 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/test_state.py @@ -0,0 +1,207 @@ +# This file is part of Patsy +# Copyright (C) 2012-2013 Nathaniel Smith +# See file LICENSE.txt for license information. + +import numpy as np + +from patsy.state import Center, Standardize, center +from patsy.util import atleast_2d_column_default + + +def check_stateful(cls, accepts_multicolumn, input, output, *args, **kwargs): + input = np.asarray(input) + output = np.asarray(output) + test_cases = [ + # List input, one chunk + ([input], output), + # Scalar input, many chunks + (input, output), + # List input, many chunks: + ([[n] for n in input], output), + # 0-d array input, many chunks: + ([np.array(n) for n in input], output), + # 1-d array input, one chunk: + ([np.array(input)], output), + # 1-d array input, many chunks: + ([np.array([n]) for n in input], output), + # 2-d but 1 column input, one chunk: + ([np.array(input)[:, None]], atleast_2d_column_default(output)), + # 2-d but 1 column input, many chunks: + ([np.array([[n]]) for n in input], atleast_2d_column_default(output)), + ] + if accepts_multicolumn: + # 2-d array input, one chunk: + test_cases += [ + ( + [np.column_stack((input, input[::-1]))], + np.column_stack((output, output[::-1])), + ), + # 2-d array input, many chunks: + ( + [np.array([[input[i], input[-i - 1]]]) for i in range(len(input))], + np.column_stack((output, output[::-1])), + ), + ] + from patsy.util import have_pandas + + if have_pandas: + import pandas + + pandas_type = (pandas.Series, pandas.DataFrame) + pandas_index = np.linspace(0, 1, num=len(input)) + # 1d and 2d here refer to the dimensionality of the input + if output.ndim == 1: + output_1d = pandas.Series(output, index=pandas_index) + else: + output_1d = pandas.DataFrame(output, index=pandas_index) + test_cases += [ + # Series input, one chunk + ([pandas.Series(input, index=pandas_index)], output_1d), + # Series input, many chunks + ( + [ + pandas.Series([x], index=[idx]) + for (x, idx) in zip(input, pandas_index) + ], + output_1d, + ), + ] + if accepts_multicolumn: + input_2d_2col = np.column_stack((input, input[::-1])) + output_2d_2col = np.column_stack((output, output[::-1])) + output_2col_dataframe = pandas.DataFrame(output_2d_2col, index=pandas_index) + test_cases += [ + # DataFrame input, one chunk + ( + [pandas.DataFrame(input_2d_2col, index=pandas_index)], + output_2col_dataframe, + ), + # DataFrame input, many chunks + ( + [ + pandas.DataFrame([input_2d_2col[i, :]], index=[pandas_index[i]]) + for i in range(len(input)) + ], + output_2col_dataframe, + ), + ] + for input_obj, output_obj in test_cases: + print(input_obj) + t = cls() + for input_chunk in input_obj: + t.memorize_chunk(input_chunk, *args, **kwargs) + t.memorize_finish() + all_outputs = [] + for input_chunk in input_obj: + output_chunk = t.transform(input_chunk, *args, **kwargs) + if input.ndim == output.ndim: + assert output_chunk.ndim == np.asarray(input_chunk).ndim + all_outputs.append(output_chunk) + if have_pandas and isinstance(all_outputs[0], pandas_type): + all_output1 = pandas.concat(all_outputs) + assert np.array_equal(all_output1.index, pandas_index) + elif all_outputs[0].ndim == 0: + all_output1 = np.array(all_outputs) + elif all_outputs[0].ndim == 1: + all_output1 = np.concatenate(all_outputs) + else: + all_output1 = np.vstack(all_outputs) + assert all_output1.shape[0] == len(input) + # output_obj_reshaped = np.asarray(output_obj).reshape(all_output1.shape) + # assert np.allclose(all_output1, output_obj_reshaped) + assert np.allclose(all_output1, output_obj) + if np.asarray(input_obj[0]).ndim == 0: + all_input = np.array(input_obj) + elif have_pandas and isinstance(input_obj[0], pandas_type): + # handles both Series and DataFrames + all_input = pandas.concat(input_obj) + elif np.asarray(input_obj[0]).ndim == 1: + # Don't use vstack, because that would turn this into a 1xn + # matrix: + all_input = np.concatenate(input_obj) + else: + all_input = np.vstack(input_obj) + all_output2 = t.transform(all_input, *args, **kwargs) + if have_pandas and isinstance(input_obj[0], pandas_type): + assert np.array_equal(all_output2.index, pandas_index) + if input.ndim == output.ndim: + assert all_output2.ndim == all_input.ndim + assert np.allclose(all_output2, output_obj) + + +def test_Center(): + check_stateful(Center, True, [1, 2, 3], [-1, 0, 1]) + check_stateful(Center, True, [1, 2, 1, 2], [-0.5, 0.5, -0.5, 0.5]) + check_stateful(Center, True, [1.3, -10.1, 7.0, 12.0], [-1.25, -12.65, 4.45, 9.45]) + + +def test_stateful_transform_wrapper(): + assert np.allclose(center([1, 2, 3]), [-1, 0, 1]) + assert np.allclose(center([1, 2, 1, 2]), [-0.5, 0.5, -0.5, 0.5]) + assert center([1.0, 2.0, 3.0]).dtype == np.dtype(float) + assert center(np.array([1.0, 2.0, 3.0], dtype=np.float32)).dtype == np.dtype( + np.float32 + ) + assert center([1, 2, 3]).dtype == np.dtype(float) + + from patsy.util import have_pandas + + if have_pandas: + import pandas + + s = pandas.Series([1, 2, 3], index=["a", "b", "c"]) + df = pandas.DataFrame( + [[1, 2], [2, 4], [3, 6]], columns=["x1", "x2"], index=[10, 20, 30] + ) + s_c = center(s) + assert isinstance(s_c, pandas.Series) + assert np.array_equal(s_c.index, ["a", "b", "c"]) + assert np.allclose(s_c, [-1, 0, 1]) + df_c = center(df) + assert isinstance(df_c, pandas.DataFrame) + assert np.array_equal(df_c.index, [10, 20, 30]) + assert np.array_equal(df_c.columns, ["x1", "x2"]) + assert np.allclose(df_c, [[-1, -2], [0, 0], [1, 2]]) + + +def test_Standardize(): + check_stateful(Standardize, True, [1, -1], [1, -1]) + check_stateful(Standardize, True, [12, 10], [1, -1]) + check_stateful( + Standardize, True, [12, 11, 10], [np.sqrt(3.0 / 2), 0, -np.sqrt(3.0 / 2)] + ) + + check_stateful( + Standardize, True, [12.0, 11.0, 10.0], [np.sqrt(3.0 / 2), 0, -np.sqrt(3.0 / 2)] + ) + + # XX: see the comment in Standardize.transform about why this doesn't + # work: + # check_stateful(Standardize, + # [12.0+0j, 11.0+0j, 10.0], + # [np.sqrt(3./2)+0j, 0, -np.sqrt(3./2)]) + + r20 = list(range(20)) + + check_stateful( + Standardize, True, [1, -1], [np.sqrt(2) / 2, -np.sqrt(2) / 2], ddof=1 + ) + + check_stateful( + Standardize, True, r20, list((np.arange(20) - 9.5) / 5.7662812973353983), ddof=0 + ) + check_stateful( + Standardize, True, r20, list((np.arange(20) - 9.5) / 5.9160797830996161), ddof=1 + ) + check_stateful( + Standardize, True, r20, list((np.arange(20) - 9.5)), rescale=False, ddof=1 + ) + check_stateful( + Standardize, + True, + r20, + list(np.arange(20) / 5.9160797830996161), + center=False, + ddof=1, + ) + check_stateful(Standardize, True, r20, r20, center=False, rescale=False, ddof=1) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/tokens.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/tokens.py new file mode 100644 index 0000000000000000000000000000000000000000..34d8efcccdd516d36ea6764460e0c0eff4a46ff6 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/tokens.py @@ -0,0 +1,203 @@ +# This file is part of Patsy +# Copyright (C) 2011 Nathaniel Smith +# See file LICENSE.txt for license information. + +# Utilities for dealing with Python code at the token level. +# +# Includes: +# a "pretty printer" that converts a sequence of tokens back into a +# readable, white-space normalized string. +# a utility function to replace calls to global functions with calls to +# other functions + +from io import StringIO + +import tokenize + +from patsy import PatsyError +from patsy.origin import Origin + +__all__ = ["python_tokenize", "pretty_untokenize", "normalize_token_spacing"] + + +# A convenience wrapper around tokenize.generate_tokens. yields tuples +# (tokenize type, token string, origin object) +def python_tokenize(code): + # Since formulas can only contain Python expressions, and Python + # expressions cannot meaningfully contain newlines, we'll just remove all + # the newlines up front to avoid any complications: + code = code.replace("\n", " ").strip() + it = tokenize.generate_tokens(StringIO(code).readline) + try: + for pytype, string, (_, start), (_, end), code in it: + if pytype == tokenize.ENDMARKER: + break + if pytype in (tokenize.NL, tokenize.NEWLINE): + assert string == "" + continue + origin = Origin(code, start, end) + if pytype == tokenize.ERRORTOKEN: + raise PatsyError( + "error tokenizing input (maybe an unclosed string?)", origin + ) + if pytype == tokenize.COMMENT: + raise PatsyError("comments are not allowed", origin) + yield (pytype, string, origin) + else: # pragma: no cover + raise ValueError("stream ended without ENDMARKER?!?") + except tokenize.TokenError as e: + # TokenError is raised iff the tokenizer thinks that there is + # some sort of multi-line construct in progress (e.g., an + # unclosed parentheses, which in Python lets a virtual line + # continue past the end of the physical line), and it hits the + # end of the source text. We have our own error handling for + # such cases, so just treat this as an end-of-stream. + # + if "unterminated string literal" in e.args[0]: + raise PatsyError( + "error tokenizing input ({})".format(e.args[0]), + Origin(code, 0, len(code)), + ) + + # Just in case someone adds some other error case: + assert "EOF in multi-line" in e.args[0] + return + + +def test_python_tokenize(): + code = "a + (foo * -1)" + tokens = list(python_tokenize(code)) + expected = [ + (tokenize.NAME, "a", Origin(code, 0, 1)), + (tokenize.OP, "+", Origin(code, 2, 3)), + (tokenize.OP, "(", Origin(code, 4, 5)), + (tokenize.NAME, "foo", Origin(code, 5, 8)), + (tokenize.OP, "*", Origin(code, 9, 10)), + (tokenize.OP, "-", Origin(code, 11, 12)), + (tokenize.NUMBER, "1", Origin(code, 12, 13)), + (tokenize.OP, ")", Origin(code, 13, 14)), + ] + assert tokens == expected + + code2 = "a + (b" + tokens2 = list(python_tokenize(code2)) + expected2 = [ + (tokenize.NAME, "a", Origin(code2, 0, 1)), + (tokenize.OP, "+", Origin(code2, 2, 3)), + (tokenize.OP, "(", Origin(code2, 4, 5)), + (tokenize.NAME, "b", Origin(code2, 5, 6)), + ] + assert tokens2 == expected2 + + import pytest + + pytest.raises(PatsyError, list, python_tokenize("a b # c")) + + import pytest + + pytest.raises(PatsyError, list, python_tokenize('a b "c')) + + +_python_space_both = list("+-*/%&^|<>") + [ + "==", + "<>", + "!=", + "<=", + ">=", + "<<", + ">>", + "**", + "//", +] +_python_space_before = _python_space_both + ["!", "~"] +_python_space_after = _python_space_both + [",", ":"] + + +def pretty_untokenize(typed_tokens): + text = [] + prev_was_space_delim = False + prev_wants_space = False + prev_was_open_paren_or_comma = False + prev_was_object_like = False + brackets = [] + for token_type, token in typed_tokens: + assert token_type not in (tokenize.INDENT, tokenize.DEDENT, tokenize.NL) + if token_type == tokenize.NEWLINE: + continue + if token_type == tokenize.ENDMARKER: + continue + if token_type in (tokenize.NAME, tokenize.NUMBER, tokenize.STRING): + if prev_wants_space or prev_was_space_delim: + text.append(" ") + text.append(token) + prev_wants_space = False + prev_was_space_delim = True + else: + if token in ("(", "[", "{"): + brackets.append(token) + elif brackets and token in (")", "]", "}"): + brackets.pop() + this_wants_space_before = token in _python_space_before + this_wants_space_after = token in _python_space_after + # Special case for slice syntax: foo[:10] + # Otherwise ":" is spaced after, like: "{1: ...}", "if a: ..." + if token == ":" and brackets and brackets[-1] == "[": + this_wants_space_after = False + # Special case for foo(*args), foo(a, *args): + if token in ("*", "**") and prev_was_open_paren_or_comma: + this_wants_space_before = False + this_wants_space_after = False + # Special case for "a = foo(b=1)": + if token == "=" and not brackets: + this_wants_space_before = True + this_wants_space_after = True + # Special case for unary -, +. Our heuristic is that if we see the + # + or - after something that looks like an object (a NAME, + # NUMBER, STRING, or close paren) then it is probably binary, + # otherwise it is probably unary. + if token in ("+", "-") and not prev_was_object_like: + this_wants_space_before = False + this_wants_space_after = False + if prev_wants_space or this_wants_space_before: + text.append(" ") + text.append(token) + prev_wants_space = this_wants_space_after + prev_was_space_delim = False + if ( + token_type in (tokenize.NAME, tokenize.NUMBER, tokenize.STRING) + or token == ")" + ): + prev_was_object_like = True + else: + prev_was_object_like = False + prev_was_open_paren_or_comma = token in ("(", ",") + return "".join(text) + + +def normalize_token_spacing(code): + tokens = [(t[0], t[1]) for t in tokenize.generate_tokens(StringIO(code).readline)] + return pretty_untokenize(tokens) + + +def test_pretty_untokenize_and_normalize_token_spacing(): + assert normalize_token_spacing("1 + 1") == "1 + 1" + assert normalize_token_spacing("1+1") == "1 + 1" + assert normalize_token_spacing("1*(2+3**2)") == "1 * (2 + 3 ** 2)" + assert normalize_token_spacing("a and b") == "a and b" + assert normalize_token_spacing("foo(a=bar.baz[1:])") == "foo(a=bar.baz[1:])" + assert normalize_token_spacing("""{"hi":foo[:]}""") == """{"hi": foo[:]}""" + assert normalize_token_spacing("""'a' "b" 'c'""") == """'a' "b" 'c'""" + assert normalize_token_spacing('"""a""" is 1 or 2==3') == '"""a""" is 1 or 2 == 3' + assert normalize_token_spacing("foo ( * args )") == "foo(*args)" + assert normalize_token_spacing("foo ( a * args )") == "foo(a * args)" + assert normalize_token_spacing("foo ( ** args )") == "foo(**args)" + assert normalize_token_spacing("foo ( a ** args )") == "foo(a ** args)" + assert normalize_token_spacing("foo (1, * args )") == "foo(1, *args)" + assert normalize_token_spacing("foo (1, a * args )") == "foo(1, a * args)" + assert normalize_token_spacing("foo (1, ** args )") == "foo(1, **args)" + assert normalize_token_spacing("foo (1, a ** args )") == "foo(1, a ** args)" + + assert normalize_token_spacing("a=foo(b = 1)") == "a = foo(b=1)" + + assert normalize_token_spacing("foo(+ 10, bar = - 1)") == "foo(+10, bar=-1)" + assert normalize_token_spacing("1 + +10 + -1 - 5") == "1 + +10 + -1 - 5" diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/user_util.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/user_util.py new file mode 100644 index 0000000000000000000000000000000000000000..080af84a76df62361652a82c392b5a9bcb8237ef --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/user_util.py @@ -0,0 +1,286 @@ +# This file is part of Patsy +# Copyright (C) 2012 Nathaniel Smith +# See file LICENSE.txt for license information. + +# Miscellaneous utilities that are useful to users (as compared to +# patsy.util, which is misc. utilities useful for implementing patsy). + +# These are made available in the patsy.* namespace +__all__ = ["balanced", "demo_data", "LookupFactor"] + +import itertools +import numpy as np +from patsy import PatsyError +from patsy.categorical import C +from patsy.util import no_pickling, assert_no_pickling + + +def balanced(**kwargs): + """balanced(factor_name=num_levels, [factor_name=num_levels, ..., repeat=1]) + + Create simple balanced factorial designs for testing. + + Given some factor names and the number of desired levels for each, + generates a balanced factorial design in the form of a data + dictionary. For example: + + .. ipython:: + + In [1]: balanced(a=2, b=3) + Out[1]: + {'a': ['a1', 'a1', 'a1', 'a2', 'a2', 'a2'], + 'b': ['b1', 'b2', 'b3', 'b1', 'b2', 'b3']} + + By default it produces exactly one instance of each combination of levels, + but if you want multiple replicates this can be accomplished via the + `repeat` argument: + + .. ipython:: + + In [2]: balanced(a=2, b=2, repeat=2) + Out[2]: + {'a': ['a1', 'a1', 'a2', 'a2', 'a1', 'a1', 'a2', 'a2'], + 'b': ['b1', 'b2', 'b1', 'b2', 'b1', 'b2', 'b1', 'b2']} + """ + repeat = kwargs.pop("repeat", 1) + levels = [] + names = sorted(kwargs) + for name in names: + level_count = kwargs[name] + levels.append(["%s%s" % (name, i) for i in range(1, level_count + 1)]) + # zip(*...) does an "unzip" + values = zip(*itertools.product(*levels)) + data = {} + for name, value in zip(names, values): + data[name] = list(value) * repeat + return data + + +def test_balanced(): + data = balanced(a=2, b=3) + assert data["a"] == ["a1", "a1", "a1", "a2", "a2", "a2"] + assert data["b"] == ["b1", "b2", "b3", "b1", "b2", "b3"] + data = balanced(a=2, b=3, repeat=2) + assert data["a"] == [ + "a1", + "a1", + "a1", + "a2", + "a2", + "a2", + "a1", + "a1", + "a1", + "a2", + "a2", + "a2", + ] + assert data["b"] == [ + "b1", + "b2", + "b3", + "b1", + "b2", + "b3", + "b1", + "b2", + "b3", + "b1", + "b2", + "b3", + ] + + +def demo_data(*names, **kwargs): + """demo_data(*names, nlevels=2, min_rows=5) + + Create simple categorical/numerical demo data. + + Pass in a set of variable names, and this function will return a simple + data set using those variable names. + + Names whose first letter falls in the range "a" through "m" will be made + categorical (with `nlevels` levels). Those that start with a "p" through + "z" are numerical. + + We attempt to produce a balanced design on the categorical variables, + repeating as necessary to generate at least `min_rows` data + points. Categorical variables are returned as a list of strings. + + Numerical data is generated by sampling from a normal distribution. A + fixed random seed is used, so that identical calls to demo_data() will + produce identical results. Numerical data is returned in a numpy array. + + Example: + + .. ipython: + + In [1]: patsy.demo_data("a", "b", "x", "y") + Out[1]: + {'a': ['a1', 'a1', 'a2', 'a2', 'a1', 'a1', 'a2', 'a2'], + 'b': ['b1', 'b2', 'b1', 'b2', 'b1', 'b2', 'b1', 'b2'], + 'x': array([ 1.76405235, 0.40015721, 0.97873798, 2.2408932 , + 1.86755799, -0.97727788, 0.95008842, -0.15135721]), + 'y': array([-0.10321885, 0.4105985 , 0.14404357, 1.45427351, + 0.76103773, 0.12167502, 0.44386323, 0.33367433])} + """ + nlevels = kwargs.pop("nlevels", 2) + min_rows = kwargs.pop("min_rows", 5) + if kwargs: + raise TypeError("unexpected keyword arguments %r" % (kwargs,)) + numerical = set() + categorical = {} + for name in names: + if name[0] in "abcdefghijklmn": + categorical[name] = nlevels + elif name[0] in "pqrstuvwxyz": + numerical.add(name) + else: + raise PatsyError("bad name %r" % (name,)) + balanced_design_size = np.prod(list(categorical.values()), dtype=int) + repeat = int(np.ceil(min_rows * 1.0 / balanced_design_size)) + num_rows = repeat * balanced_design_size + data = balanced(repeat=repeat, **categorical) + r = np.random.RandomState(0) + for name in sorted(numerical): + data[name] = r.normal(size=num_rows) + return data + + +def test_demo_data(): + d1 = demo_data("a", "b", "x") + assert sorted(d1.keys()) == ["a", "b", "x"] + assert d1["a"] == ["a1", "a1", "a2", "a2", "a1", "a1", "a2", "a2"] + assert d1["b"] == ["b1", "b2", "b1", "b2", "b1", "b2", "b1", "b2"] + assert d1["x"].dtype == np.dtype(float) + assert d1["x"].shape == (8,) + + d2 = demo_data("x", "y") + assert sorted(d2.keys()) == ["x", "y"] + assert len(d2["x"]) == len(d2["y"]) == 5 + + assert len(demo_data("x", min_rows=10)["x"]) == 10 + assert len(demo_data("a", "b", "x", min_rows=10)["x"]) == 12 + assert len(demo_data("a", "b", "x", min_rows=10, nlevels=3)["x"]) == 18 + + import pytest + + pytest.raises(PatsyError, demo_data, "a", "b", "__123") + pytest.raises(TypeError, demo_data, "a", "b", asdfasdf=123) + + +class LookupFactor(object): + """A simple factor class that simply looks up a named entry in the given + data. + + Useful for programatically constructing formulas, and as a simple example + of the factor protocol. For details see + :ref:`expert-model-specification`. + + Example:: + + dmatrix(ModelDesc([], [Term([LookupFactor("x")])]), {"x": [1, 2, 3]}) + + :arg varname: The name of this variable; used as a lookup key in the + passed in data dictionary/DataFrame/whatever. + :arg force_categorical: If True, then treat this factor as + categorical. (Equivalent to using :func:`C` in a regular formula, but + of course you can't do that with a :class:`LookupFactor`. + :arg contrast: If given, the contrast to use; see :func:`C`. (Requires + ``force_categorical=True``.) + :arg levels: If given, the categorical levels; see :func:`C`. (Requires + ``force_categorical=True``.) + :arg origin: Either ``None``, or the :class:`Origin` of this factor for use + in error reporting. + + .. versionadded:: 0.2.0 + The ``force_categorical`` and related arguments. + """ + + def __init__( + self, varname, force_categorical=False, contrast=None, levels=None, origin=None + ): + self._varname = varname + self._force_categorical = force_categorical + self._contrast = contrast + self._levels = levels + self.origin = origin + if not self._force_categorical: + if contrast is not None: + raise ValueError("contrast= requires force_categorical=True") + if levels is not None: + raise ValueError("levels= requires force_categorical=True") + + def name(self): + return self._varname + + def __repr__(self): + return "%s(%r)" % (self.__class__.__name__, self._varname) + + def __eq__(self, other): + return ( + isinstance(other, LookupFactor) + and self._varname == other._varname + and self._force_categorical == other._force_categorical + and self._contrast == other._contrast + and self._levels == other._levels + ) + + def __ne__(self, other): + return not self == other + + def __hash__(self): + return hash( + ( + LookupFactor, + self._varname, + self._force_categorical, + self._contrast, + self._levels, + ) + ) + + def memorize_passes_needed(self, state, eval_env): + return 0 + + def memorize_chunk(self, state, which_pass, data): # pragma: no cover + assert False + + def memorize_finish(self, state, which_pass): # pragma: no cover + assert False + + def eval(self, memorize_state, data): + value = data[self._varname] + if self._force_categorical: + value = C(value, contrast=self._contrast, levels=self._levels) + return value + + __getstate__ = no_pickling + + +def test_LookupFactor(): + l_a = LookupFactor("a") + assert l_a.name() == "a" + assert l_a == LookupFactor("a") + assert l_a != LookupFactor("b") + assert hash(l_a) == hash(LookupFactor("a")) + assert hash(l_a) != hash(LookupFactor("b")) + assert l_a.eval({}, {"a": 1}) == 1 + assert l_a.eval({}, {"a": 2}) == 2 + assert repr(l_a) == "LookupFactor('a')" + assert l_a.origin is None + l_with_origin = LookupFactor("b", origin="asdf") + assert l_with_origin.origin == "asdf" + + l_c = LookupFactor("c", force_categorical=True, contrast="CONTRAST", levels=(1, 2)) + box = l_c.eval({}, {"c": [1, 1, 2]}) + assert box.data == [1, 1, 2] + assert box.contrast == "CONTRAST" + assert box.levels == (1, 2) + + import pytest + + pytest.raises(ValueError, LookupFactor, "nc", contrast="CONTRAST") + pytest.raises(ValueError, LookupFactor, "nc", levels=(1, 2)) + + assert_no_pickling(LookupFactor("a")) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/util.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/util.py new file mode 100644 index 0000000000000000000000000000000000000000..d666d38fdac2d656911cfa17c2e0d6c82b601495 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/util.py @@ -0,0 +1,865 @@ +# This file is part of Patsy +# Copyright (C) 2011-2013 Nathaniel Smith +# See file LICENSE.txt for license information. + +# Some generic utilities. + +__all__ = [ + "atleast_2d_column_default", + "uniqueify_list", + "widest_float", + "widest_complex", + "wide_dtype_for", + "widen", + "repr_pretty_delegate", + "repr_pretty_impl", + "SortAnythingKey", + "safe_scalar_isnan", + "safe_isnan", + "iterable", + "have_pandas", + "have_pandas_categorical", + "have_pandas_categorical_dtype", + "pandas_Categorical_from_codes", + "pandas_Categorical_categories", + "pandas_Categorical_codes", + "safe_is_pandas_categorical_dtype", + "safe_is_pandas_categorical", + "safe_issubdtype", + "no_pickling", + "assert_no_pickling", + "safe_string_eq", +] + +import sys +from io import StringIO +import numpy as np + +from .compat import optional_dep_ok + +try: + import pandas +except ImportError: + PANDAS3 = have_pandas = False +else: + have_pandas = True + import packaging.version + + pandas_version = packaging.version.parse(pandas.__version__) + PANDAS3 = pandas_version >= packaging.version.parse("3.0.0.dev0") + +# Pandas versions < 0.9.0 don't have Categorical +# Can drop this guard whenever we drop support for such older versions of +# pandas. +have_pandas_categorical = have_pandas and hasattr(pandas, "Categorical") +have_pandas_string_dtype = have_pandas and hasattr(pandas, "StringDtype") +if not have_pandas: + _pandas_is_categorical_dtype = None +else: + if hasattr(pandas, "CategoricalDtype"): # pandas >= 0.25 + _pandas_is_categorical_dtype = lambda x: isinstance( + getattr(x, "dtype", x), pandas.CategoricalDtype + ) + elif hasattr(pandas, "api"): # pandas >= 0.19 + _pandas_is_categorical_dtype = getattr( + pandas.api.types, "is_categorical_dtype", None + ) + else: # pandas <=0.18 + _pandas_is_categorical_dtype = getattr( + pandas.core.common, "is_categorical_dtype", None + ) +have_pandas_categorical_dtype = _pandas_is_categorical_dtype is not None + + +def safe_is_pandas_string_dtype(x): + return have_pandas_string_dtype and isinstance(x, pandas.StringDtype) + + +# The handling of the `copy` keyword has been changed since numpy>=2. +# https://numpy.org/devdocs/numpy_2_0_migration_guide.html#adapting-to-changes-in-the-copy-keyword +# If numpy<2 support is dropped, this try-clause can be removed. +try: + np.array([1]).__array__(copy=None) + copy_if_needed = None +except TypeError: + copy_if_needed = False + + +# Passes through Series and DataFrames, call np.asarray() on everything else +def asarray_or_pandas(a, copy=copy_if_needed, dtype=None, subok=False): + if have_pandas: + if isinstance(a, (pandas.Series, pandas.DataFrame)): + # The .name attribute on Series is discarded when passing through + # the constructor: + # https://github.com/pydata/pandas/issues/1578 + extra_args = {} + if hasattr(a, "name"): + extra_args["name"] = a.name + return a.__class__(a, copy=copy, dtype=dtype, **extra_args) + return np.array(a, copy=copy, dtype=dtype, subok=subok) + + +def test_asarray_or_pandas(): + import warnings + + assert type(asarray_or_pandas([1, 2, 3])) is np.ndarray + with warnings.catch_warnings() as w: + warnings.filterwarnings( + "ignore", "the matrix subclass", PendingDeprecationWarning + ) + assert type(asarray_or_pandas(np.matrix([[1, 2, 3]]))) is np.ndarray + assert type(asarray_or_pandas(np.matrix([[1, 2, 3]]), subok=True)) is np.matrix + assert w is None + a = np.array([1, 2, 3]) + assert asarray_or_pandas(a) is a + a_copy = asarray_or_pandas(a, copy=True) + assert np.array_equal(a, a_copy) + a_copy[0] = 100 + assert not np.array_equal(a, a_copy) + assert np.allclose(asarray_or_pandas([1, 2, 3], dtype=float), [1.0, 2.0, 3.0]) + assert asarray_or_pandas([1, 2, 3], dtype=float).dtype == np.dtype(float) + a_view = asarray_or_pandas(a, dtype=a.dtype) + a_view[0] = 99 + assert a[0] == 99 + global have_pandas + if have_pandas: + s = pandas.Series([1, 2, 3], name="A", index=[10, 20, 30]) + s_view1 = asarray_or_pandas(s) + assert s_view1.name == "A" + assert np.array_equal(s_view1.index, [10, 20, 30]) + s_view1[10] = 101 + # pandas 3 uses copy-on-write, so no longer valid + if not PANDAS3: + assert s[10] == 101 + s_copy = asarray_or_pandas(s, copy=True) + assert s_copy.name == "A" + assert np.array_equal(s_copy.index, [10, 20, 30]) + assert np.array_equal(s_copy, s) + s_copy[10] = 100 + assert not np.array_equal(s_copy, s) + assert asarray_or_pandas(s, dtype=float).dtype == np.dtype(float) + s_view2 = asarray_or_pandas(s, dtype=s.dtype) + assert s_view2.name == "A" + assert np.array_equal(s_view2.index, [10, 20, 30]) + s_view2[10] = 99 + # pandas 3 uses copy-on-write, so no longer valid + if not PANDAS3: + assert s[10] == 99 + + df = pandas.DataFrame([[1, 2, 3]], columns=["A", "B", "C"], index=[10]) + df_view1 = asarray_or_pandas(df) + df_view1.loc[10, "A"] = 101 + assert np.array_equal(df_view1.columns, ["A", "B", "C"]) + assert np.array_equal(df_view1.index, [10]) + # pandas 3 uses copy-on-write, so no longer valid + if not PANDAS3: + assert df.loc[10, "A"] == 101 + df_copy = asarray_or_pandas(df, copy=True) + assert np.array_equal(df_copy, df) + assert np.array_equal(df_copy.columns, ["A", "B", "C"]) + assert np.array_equal(df_copy.index, [10]) + df_copy.loc[10, "A"] = 100 + assert not np.array_equal(df_copy, df) + df_converted = asarray_or_pandas(df, dtype=float) + assert df_converted["A"].dtype == np.dtype(float) + assert np.allclose(df_converted, df) + assert np.array_equal(df_converted.columns, ["A", "B", "C"]) + assert np.array_equal(df_converted.index, [10]) + df_view2 = asarray_or_pandas(df, dtype=df["A"].dtype) + assert np.array_equal(df_view2.columns, ["A", "B", "C"]) + assert np.array_equal(df_view2.index, [10]) + # This actually makes a copy, not a view, because of a pandas bug: + # https://github.com/pydata/pandas/issues/1572 + assert np.array_equal(df, df_view2) + # df_view2[0][0] = 99 + # assert df[0][0] == 99 + + had_pandas = have_pandas + try: + have_pandas = False + assert type(asarray_or_pandas(pandas.Series([1, 2, 3]))) is np.ndarray + assert type(asarray_or_pandas(pandas.DataFrame([[1, 2, 3]]))) is np.ndarray + finally: + have_pandas = had_pandas + + +# Like np.atleast_2d, but this converts lower-dimensional arrays into columns, +# instead of rows. It also converts ndarray subclasses into basic ndarrays, +# which makes it easier to guarantee correctness. However, there are many +# places in the code where we want to preserve pandas indexing information if +# present, so there is also an option +def atleast_2d_column_default(a, preserve_pandas=False): + if preserve_pandas and have_pandas: + if isinstance(a, pandas.Series): + return pandas.DataFrame(a) + elif isinstance(a, pandas.DataFrame): + return a + # fall through + a = np.asarray(a) + a = np.atleast_1d(a) + if a.ndim <= 1: + a = a.reshape((-1, 1)) + assert a.ndim >= 2 + return a + + +def test_atleast_2d_column_default(): + import warnings + + assert np.all(atleast_2d_column_default([1, 2, 3]) == [[1], [2], [3]]) + + assert atleast_2d_column_default(1).shape == (1, 1) + assert atleast_2d_column_default([1]).shape == (1, 1) + assert atleast_2d_column_default([[1]]).shape == (1, 1) + assert atleast_2d_column_default([[[1]]]).shape == (1, 1, 1) + + assert atleast_2d_column_default([1, 2, 3]).shape == (3, 1) + assert atleast_2d_column_default([[1], [2], [3]]).shape == (3, 1) + + with warnings.catch_warnings() as w: + warnings.filterwarnings( + "ignore", "the matrix subclass", PendingDeprecationWarning + ) + assert type(atleast_2d_column_default(np.matrix(1))) == np.ndarray + assert w is None + + global have_pandas + if have_pandas: + assert type(atleast_2d_column_default(pandas.Series([1, 2]))) == np.ndarray + assert ( + type(atleast_2d_column_default(pandas.DataFrame([[1], [2]]))) == np.ndarray + ) + assert ( + type(atleast_2d_column_default(pandas.Series([1, 2]), preserve_pandas=True)) + == pandas.DataFrame + ) + assert ( + type( + atleast_2d_column_default( + pandas.DataFrame([[1], [2]]), preserve_pandas=True + ) + ) + == pandas.DataFrame + ) + s = pandas.Series([10, 11, 12], name="hi", index=["a", "b", "c"]) + df = atleast_2d_column_default(s, preserve_pandas=True) + assert isinstance(df, pandas.DataFrame) + assert np.all(df.columns == ["hi"]) + assert np.all(df.index == ["a", "b", "c"]) + with warnings.catch_warnings() as w: + warnings.filterwarnings( + "ignore", "the matrix subclass", PendingDeprecationWarning + ) + assert ( + type(atleast_2d_column_default(np.matrix(1), preserve_pandas=True)) + == np.ndarray + ) + assert w is None + assert ( + type(atleast_2d_column_default([1, 2, 3], preserve_pandas=True)) == np.ndarray + ) + + if have_pandas: + had_pandas = have_pandas + try: + have_pandas = False + assert ( + type( + atleast_2d_column_default( + pandas.Series([1, 2]), preserve_pandas=True + ) + ) + == np.ndarray + ) + assert ( + type( + atleast_2d_column_default( + pandas.DataFrame([[1], [2]]), preserve_pandas=True + ) + ) + == np.ndarray + ) + finally: + have_pandas = had_pandas + + +# A version of .reshape() that knows how to down-convert a 1-column +# pandas.DataFrame into a pandas.Series. Useful for code that wants to be +# agnostic between 1d and 2d data, with the pattern: +# new_a = atleast_2d_column_default(a, preserve_pandas=True) +# # do stuff to new_a, which can assume it's always 2 dimensional +# return pandas_friendly_reshape(new_a, a.shape) +def pandas_friendly_reshape(a, new_shape): + if not have_pandas: + return a.reshape(new_shape) + if not isinstance(a, pandas.DataFrame): + return a.reshape(new_shape) + # we have a DataFrame. Only supported reshapes are no-op, and + # single-column DataFrame -> Series. + if new_shape == a.shape: + return a + if len(new_shape) == 1 and a.shape[1] == 1: + if new_shape[0] != a.shape[0]: + raise ValueError("arrays have incompatible sizes") + return a[a.columns[0]] + raise ValueError( + "cannot reshape a DataFrame with shape %s to shape %s" % (a.shape, new_shape) + ) + + +def test_pandas_friendly_reshape(): + import pytest + + global have_pandas + assert np.allclose( + pandas_friendly_reshape(np.arange(10).reshape(5, 2), (2, 5)), + np.arange(10).reshape(2, 5), + ) + if have_pandas: + df = pandas.DataFrame({"x": [1, 2, 3]}, index=["a", "b", "c"]) + noop = pandas_friendly_reshape(df, (3, 1)) + assert isinstance(noop, pandas.DataFrame) + assert np.array_equal(noop.index, ["a", "b", "c"]) + assert np.array_equal(noop.columns, ["x"]) + squozen = pandas_friendly_reshape(df, (3,)) + assert isinstance(squozen, pandas.Series) + assert np.array_equal(squozen.index, ["a", "b", "c"]) + assert squozen.name == "x" + + pytest.raises(ValueError, pandas_friendly_reshape, df, (4,)) + pytest.raises(ValueError, pandas_friendly_reshape, df, (1, 3)) + pytest.raises(ValueError, pandas_friendly_reshape, df, (3, 3)) + + had_pandas = have_pandas + try: + have_pandas = False + # this will try to do a reshape directly, and DataFrames *have* no + # reshape method + pytest.raises(AttributeError, pandas_friendly_reshape, df, (3,)) + finally: + have_pandas = had_pandas + + +def uniqueify_list(seq): + seq_new = [] + seen = set() + for obj in seq: + if obj not in seen: + seq_new.append(obj) + seen.add(obj) + return seq_new + + +def test_to_uniqueify_list(): + assert uniqueify_list([1, 2, 3]) == [1, 2, 3] + assert uniqueify_list([1, 3, 3, 2, 3, 1]) == [1, 3, 2] + assert uniqueify_list([3, 2, 1, 4, 1, 2, 3]) == [3, 2, 1, 4] + + +for float_type in ("float128", "float96", "float64"): + if hasattr(np, float_type): + widest_float = getattr(np, float_type) + break +else: # pragma: no cover + assert False +for complex_type in ("complex256", "complex196", "complex128"): + if hasattr(np, complex_type): + widest_complex = getattr(np, complex_type) + break +else: # pragma: no cover + assert False + + +def wide_dtype_for(arr): + arr = np.asarray(arr) + if safe_issubdtype(arr.dtype, np.integer) or safe_issubdtype( + arr.dtype, np.floating + ): + return widest_float + elif safe_issubdtype(arr.dtype, np.complexfloating): + return widest_complex + raise ValueError("cannot widen a non-numeric type %r" % (arr.dtype,)) + + +def widen(arr): + return np.asarray(arr, dtype=wide_dtype_for(arr)) + + +def test_wide_dtype_for_and_widen(): + assert np.allclose(widen([1, 2, 3]), [1, 2, 3]) + assert widen([1, 2, 3]).dtype == widest_float + assert np.allclose(widen([1.0, 2.0, 3.0]), [1, 2, 3]) + assert widen([1.0, 2.0, 3.0]).dtype == widest_float + assert np.allclose(widen([1 + 0j, 2, 3]), [1, 2, 3]) + assert widen([1 + 0j, 2, 3]).dtype == widest_complex + import pytest + + pytest.raises(ValueError, widen, ["hi"]) + + +class PushbackAdapter(object): + def __init__(self, it): + self._it = it + self._pushed = [] + + def __iter__(self): + return self + + def push_back(self, obj): + self._pushed.append(obj) + + def next(self): + if self._pushed: + return self._pushed.pop() + else: + # May raise StopIteration + return next(self._it) + + __next__ = next + + def peek(self): + try: + obj = next(self) + except StopIteration: + raise ValueError("no more data") + self.push_back(obj) + return obj + + def has_more(self): + try: + self.peek() + except ValueError: + return False + else: + return True + + +def test_PushbackAdapter(): + it = PushbackAdapter(iter([1, 2, 3, 4])) + assert it.has_more() + assert next(it) == 1 + it.push_back(0) + assert next(it) == 0 + assert next(it) == 2 + assert it.peek() == 3 + it.push_back(10) + assert it.peek() == 10 + it.push_back(20) + assert it.peek() == 20 + assert it.has_more() + assert list(it) == [20, 10, 3, 4] + assert not it.has_more() + + +# The IPython pretty-printer gives very nice output that is difficult to get +# otherwise, e.g., look how much more readable this is than if it were all +# smooshed onto one line: +# +# ModelDesc(input_code='y ~ x*asdf', +# lhs_terms=[Term([EvalFactor('y')])], +# rhs_terms=[Term([]), +# Term([EvalFactor('x')]), +# Term([EvalFactor('asdf')]), +# Term([EvalFactor('x'), EvalFactor('asdf')])], +# ) +# +# But, we don't want to assume it always exists; nor do we want to be +# re-writing every repr function twice, once for regular repr and once for +# the pretty printer. So, here's an ugly fallback implementation that can be +# used unconditionally to implement __repr__ in terms of _pretty_repr_. +# +# Pretty printer docs: +# http://ipython.org/ipython-doc/dev/api/generated/IPython.lib.pretty.html + + +class _MiniPPrinter(object): + def __init__(self): + self._out = StringIO() + self.indentation = 0 + + def text(self, text): + self._out.write(text) + + def breakable(self, sep=" "): + self._out.write(sep) + + def begin_group(self, _, text): + self.text(text) + + def end_group(self, _, text): + self.text(text) + + def pretty(self, obj): + if hasattr(obj, "_repr_pretty_"): + obj._repr_pretty_(self, False) + else: + self.text(repr(obj)) + + def getvalue(self): + return self._out.getvalue() + + +def _mini_pretty(obj): + printer = _MiniPPrinter() + printer.pretty(obj) + return printer.getvalue() + + +def repr_pretty_delegate(obj): + # If IPython is already loaded, then might as well use it. (Most commonly + # this will occur if we are in an IPython session, but somehow someone has + # called repr() directly. This can happen for example if printing an + # container like a namedtuple that IPython lacks special code for + # pretty-printing.) But, if IPython is not already imported, we do not + # attempt to import it. This makes patsy itself faster to import (as of + # Nov. 2012 I measured the extra overhead from loading IPython as ~4 + # seconds on a cold cache), it prevents IPython from automatically + # spawning a bunch of child processes (!) which may not be what you want + # if you are not otherwise using IPython, and it avoids annoying the + # pandas people who have some hack to tell whether you are using IPython + # in their test suite (see patsy bug #12). + if optional_dep_ok and "IPython" in sys.modules: + from IPython.lib.pretty import pretty + + return pretty(obj) + else: + return _mini_pretty(obj) + + +def repr_pretty_impl(p, obj, args, kwargs=[]): + name = obj.__class__.__name__ + p.begin_group(len(name) + 1, "%s(" % (name,)) + started = [False] + + def new_item(): + if started[0]: + p.text(",") + p.breakable() + started[0] = True + + for arg in args: + new_item() + p.pretty(arg) + for label, value in kwargs: + new_item() + p.begin_group(len(label) + 1, "%s=" % (label,)) + p.pretty(value) + p.end_group(len(label) + 1, "") + p.end_group(len(name) + 1, ")") + + +def test_repr_pretty(): + assert repr_pretty_delegate("asdf") == "'asdf'" + printer = _MiniPPrinter() + + class MyClass(object): + pass + + repr_pretty_impl(printer, MyClass(), ["a", 1], [("foo", "bar"), ("asdf", "asdf")]) + assert printer.getvalue() == "MyClass('a', 1, foo='bar', asdf='asdf')" + + +# In Python 3, objects of different types are not generally comparable, so a +# list of heterogeneous types cannot be sorted. This implements a Python 2 +# style comparison for arbitrary types. (It works on Python 2 too, but just +# gives you the built-in ordering.) To understand why this is tricky, consider +# this example: +# a = 1 # type 'int' +# b = 1.5 # type 'float' +# class gggg: +# pass +# c = gggg() +# sorted([a, b, c]) +# The fallback ordering sorts by class name, so according to the fallback +# ordering, we have b < c < a. But, of course, a and b are comparable (even +# though they're of different types), so we also have a < b. This is +# inconsistent. There is no general solution to this problem (which I guess is +# why Python 3 stopped trying), but the worst offender is all the different +# "numeric" classes (int, float, complex, decimal, rational...), so as a +# special-case, we sort all numeric objects to the start of the list. +# (In Python 2, there is also a similar special case for str and unicode, but +# we don't have to worry about that for Python 3.) +class SortAnythingKey(object): + def __init__(self, obj): + self.obj = obj + + def _python_lt(self, other_obj): + # On Py2, < never raises an error, so this is just <. (Actually it + # does raise a TypeError for comparing complex to numeric, but not for + # comparisons of complex to other types. Sigh. Whatever.) + # On Py3, this returns a bool if available, and otherwise returns + # NotImplemented + try: + return self.obj < other_obj + except TypeError: + return NotImplemented + + def __lt__(self, other): + assert isinstance(other, SortAnythingKey) + result = self._python_lt(other.obj) + if result is not NotImplemented: + return result + # Okay, that didn't work, time to fall back. + # If one of these is a number, then it is smaller. + if self._python_lt(0) is not NotImplemented: + return True + if other._python_lt(0) is not NotImplemented: + return False + # Also check ==, since it may well be defined for otherwise + # unorderable objects, and if so then we should be consistent with + # it: + if self.obj == other.obj: + return False + # Otherwise, we break ties based on class name and memory position + return (self.obj.__class__.__name__, id(self.obj)) < ( + other.obj.__class__.__name__, + id(other.obj), + ) + + +def test_SortAnythingKey(): + assert sorted([20, 10, 0, 15], key=SortAnythingKey) == [0, 10, 15, 20] + assert sorted([10, -1.5], key=SortAnythingKey) == [-1.5, 10] + assert sorted([10, "a", 20.5, "b"], key=SortAnythingKey) == [10, 20.5, "a", "b"] + + class a(object): + pass + + class b(object): + pass + + class z(object): + pass + + a_obj = a() + b_obj = b() + z_obj = z() + o_obj = object() + assert sorted([z_obj, a_obj, 1, b_obj, o_obj], key=SortAnythingKey) == [ + 1, + a_obj, + b_obj, + o_obj, + z_obj, + ] + + +# NaN checking functions that work on arbitrary objects, on old Python +# versions (math.isnan is only in 2.6+), etc. +def safe_scalar_isnan(x): + try: + return np.isnan(float(x)) + except (TypeError, ValueError, NotImplementedError): + return False + + +safe_isnan = np.vectorize(safe_scalar_isnan, otypes=[bool]) + + +def test_safe_scalar_isnan(): + assert not safe_scalar_isnan(True) + assert not safe_scalar_isnan(None) + assert not safe_scalar_isnan("sadf") + assert not safe_scalar_isnan((1, 2, 3)) + assert not safe_scalar_isnan(np.asarray([1, 2, 3])) + assert not safe_scalar_isnan([np.nan]) + assert safe_scalar_isnan(np.nan) + assert safe_scalar_isnan(np.float32(np.nan)) + assert safe_scalar_isnan(float(np.nan)) + + +def test_safe_isnan(): + assert np.array_equal( + safe_isnan([1, True, None, np.nan, "asdf"]), [False, False, False, True, False] + ) + assert safe_isnan(np.nan).ndim == 0 + assert safe_isnan(np.nan) + assert not safe_isnan(None) + # raw isnan raises a *different* error for strings than for objects: + assert not safe_isnan("asdf") + + +def iterable(obj): + try: + iter(obj) + except Exception: + return False + return True + + +def test_iterable(): + assert iterable("asdf") + assert iterable([]) + assert iterable({"a": 1}) + assert not iterable(1) + assert not iterable(iterable) + + +##### Handling Pandas's categorical stuff is horrible and hateful + +# Basically they decided that they didn't like how numpy does things, so their +# categorical stuff is *kinda* like how numpy would do it (e.g. they have a +# special ".dtype" attribute to mark categorical data), so by default you'll +# find yourself using the same code paths to handle pandas categorical data +# and other non-categorical data. BUT, all the idioms for detecting +# categorical data blow up with errors if you try them with real numpy dtypes, +# and all numpy's idioms for detecting non-categorical types blow up with +# errors if you try them with pandas categorical stuff. So basically they have +# just poisoned all code that touches dtypes; the old numpy stuff is unsafe, +# and you must use special code like below. +# +# Also there are hoops to jump through to handle both the old style +# (Categorical objects) and new-style (Series with dtype="category"). + + +# Needed to support pandas < 0.15 +def pandas_Categorical_from_codes(codes, categories): + assert have_pandas_categorical + + # Old versions of pandas sometimes fail to coerce this to an array and + # just return it directly from .labels (?!). + codes = np.asarray(codes) + if hasattr(pandas.Categorical, "from_codes"): + return pandas.Categorical.from_codes(codes, categories) + else: + return pandas.Categorical(codes, categories) + + +def test_pandas_Categorical_from_codes(): + if not have_pandas_categorical: + return + c = pandas_Categorical_from_codes([1, 1, 0, -1], ["a", "b"]) + assert np.all(np.asarray(c)[:-1] == ["b", "b", "a"]) + assert np.isnan(np.asarray(c)[-1]) + + +# Needed to support pandas < 0.15 +def pandas_Categorical_categories(cat): + # In 0.15+, a categorical Series has a .cat attribute which is similar to + # a Categorical object, and Categorical objects are what have .categories + # and .codes attributes. + if hasattr(cat, "cat"): + cat = cat.cat + if hasattr(cat, "categories"): + return cat.categories + else: + return cat.levels + + +# Needed to support pandas < 0.15 +def pandas_Categorical_codes(cat): + # In 0.15+, a categorical Series has a .cat attribute which is a + # Categorical object, and Categorical objects are what have .categories / + # .codes attributes. + if hasattr(cat, "cat"): + cat = cat.cat + if hasattr(cat, "codes"): + return cat.codes + else: + return cat.labels + + +def test_pandas_Categorical_accessors(): + if not have_pandas_categorical: + return + c = pandas_Categorical_from_codes([1, 1, 0, -1], ["a", "b"]) + assert np.all(pandas_Categorical_categories(c) == ["a", "b"]) + assert np.all(pandas_Categorical_codes(c) == [1, 1, 0, -1]) + + if have_pandas_categorical_dtype: + s = pandas.Series(c) + assert np.all(pandas_Categorical_categories(s) == ["a", "b"]) + assert np.all(pandas_Categorical_codes(s) == [1, 1, 0, -1]) + + +# Needed to support pandas >= 0.15 (!) +def safe_is_pandas_categorical_dtype(dt): + if not have_pandas_categorical_dtype: + return False + return _pandas_is_categorical_dtype(dt) + + +# Needed to support pandas >= 0.15 (!) +def safe_is_pandas_categorical(data): + if not have_pandas_categorical: + return False + if isinstance(data, pandas.Categorical): + return True + if hasattr(data, "dtype"): + return safe_is_pandas_categorical_dtype(data.dtype) + return False + + +def test_safe_is_pandas_categorical(): + assert not safe_is_pandas_categorical(np.arange(10)) + + if have_pandas_categorical: + c_obj = pandas.Categorical(["a", "b"]) + assert safe_is_pandas_categorical(c_obj) + + if have_pandas_categorical_dtype: + s_obj = pandas.Series(["a", "b"], dtype="category") + assert safe_is_pandas_categorical(s_obj) + + +# Needed to support pandas >= 0.15 (!) +# Calling np.issubdtype on a pandas categorical will blow up -- the officially +# recommended solution is to replace every piece of code like +# np.issubdtype(foo.dtype, bool) +# with code like +# isinstance(foo.dtype, np.dtype) and np.issubdtype(foo.dtype, bool) +# or +# not pandas.is_categorical_dtype(foo.dtype) and issubdtype(foo.dtype, bool) +# We do the latter (with extra hoops) because the isinstance check is not +# safe. See +# https://github.com/pydata/pandas/issues/9581 +# https://github.com/pydata/pandas/issues/9581#issuecomment-77099564 +def safe_issubdtype(dt1, dt2): + # The second condition is needed to support pandas >= 3 (!) + if safe_is_pandas_categorical_dtype(dt1) or safe_is_pandas_string_dtype(dt1): + return False + return np.issubdtype(dt1, dt2) + + +def test_safe_issubdtype(): + assert safe_issubdtype(int, np.integer) + assert safe_issubdtype(np.dtype(float), np.floating) + assert not safe_issubdtype(int, np.floating) + assert not safe_issubdtype(np.dtype(float), np.integer) + + if have_pandas_categorical_dtype: + bad_dtype = pandas.Series(["a", "b"], dtype="category") + assert not safe_issubdtype(bad_dtype, np.integer) + + +def no_pickling(*args, **kwargs): + raise NotImplementedError( + "Sorry, pickling not yet supported. " + "See https://github.com/pydata/patsy/issues/26 if you want to " + "help." + ) + + +def assert_no_pickling(obj): + import pickle + import pytest + + pytest.raises(NotImplementedError, pickle.dumps, obj) + + +# Use like: +# if safe_string_eq(constraints, "center"): +# ... +# where 'constraints' might be a string or an array. (If it's an array, then +# we can't use == becaues it might broadcast and ugh.) +def safe_string_eq(obj, value): + if isinstance(obj, str): + return obj == value + else: + return False + + +def test_safe_string_eq(): + assert safe_string_eq("foo", "foo") + assert not safe_string_eq("foo", "bar") + assert not safe_string_eq(np.empty((2, 2)), "foo") diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/version.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/version.py new file mode 100644 index 0000000000000000000000000000000000000000..48a94bcbb0a2d76363fc715ac6cfffdbdcf5811e --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/patsy/version.py @@ -0,0 +1,20 @@ +# This file is part of Patsy +# Copyright (C) 2011-2014 Nathaniel Smith +# See file LICENSE.txt for license information. + +# This file must be kept very simple, because it is consumed from several +# places -- it is imported by patsy/__init__.py, execfile'd by setup.py, etc. + +# We use a simple scheme: +# 1.0.2 -> 1.0.2+dev -> 1.1.0 -> 1.1.0+dev +# where the +dev versions are never released into the wild, they're just what +# we stick into the VCS in between releases. +# +# This is compatible with PEP 440: +# http://legacy.python.org/dev/peps/pep-0440/ +# via the use of the "local suffix" "+dev", which is disallowed on index +# servers and causes 1.0.2+dev to sort after plain 1.0.2, which is what we +# want. (Contrast with the special suffix 1.0.2.dev, which sorts *before* +# 1.0.2.) + +__version__ = "1.0.2" diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft-0.19.1.dist-info/INSTALLER b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft-0.19.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft-0.19.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft-0.19.1.dist-info/METADATA b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft-0.19.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..2ac9179c83b3bad267adfe073e04452e6993abb0 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft-0.19.1.dist-info/METADATA @@ -0,0 +1,270 @@ +Metadata-Version: 2.4 +Name: peft +Version: 0.19.1 +Summary: Parameter-Efficient Fine-Tuning (PEFT) +Home-page: https://github.com/huggingface/peft +Author: The HuggingFace team +Author-email: benjamin@huggingface.co +License: Apache +Keywords: deep 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: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +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 :: Scientific/Engineering :: Artificial Intelligence +Requires-Python: >=3.10.0 +Description-Content-Type: text/markdown +License-File: LICENSE +Requires-Dist: numpy>=1.17 +Requires-Dist: packaging>=20.0 +Requires-Dist: psutil +Requires-Dist: pyyaml +Requires-Dist: torch>=1.13.0 +Requires-Dist: transformers +Requires-Dist: tqdm +Requires-Dist: accelerate>=0.21.0 +Requires-Dist: safetensors +Requires-Dist: huggingface_hub>=0.25.0 +Provides-Extra: quality +Requires-Dist: black; extra == "quality" +Requires-Dist: hf-doc-builder; extra == "quality" +Requires-Dist: ruff~=0.12.8; extra == "quality" +Provides-Extra: docs-specific +Requires-Dist: black; extra == "docs-specific" +Requires-Dist: requests; extra == "docs-specific" +Requires-Dist: hf-doc-builder; extra == "docs-specific" +Provides-Extra: dev +Requires-Dist: black; extra == "dev" +Requires-Dist: hf-doc-builder; extra == "dev" +Requires-Dist: ruff~=0.12.8; extra == "dev" +Requires-Dist: black; extra == "dev" +Requires-Dist: requests; extra == "dev" +Requires-Dist: hf-doc-builder; extra == "dev" +Provides-Extra: test +Requires-Dist: black; extra == "test" +Requires-Dist: hf-doc-builder; extra == "test" +Requires-Dist: ruff~=0.12.8; extra == "test" +Requires-Dist: black; extra == "test" +Requires-Dist: requests; extra == "test" +Requires-Dist: hf-doc-builder; extra == "test" +Requires-Dist: pytest; extra == "test" +Requires-Dist: pytest-cov; extra == "test" +Requires-Dist: pytest-xdist; extra == "test" +Requires-Dist: parameterized; extra == "test" +Requires-Dist: datasets; extra == "test" +Requires-Dist: diffusers; extra == "test" +Requires-Dist: scipy; extra == "test" +Requires-Dist: scikit-learn; extra == "test" +Requires-Dist: protobuf; extra == "test" +Requires-Dist: sentencepiece; extra == "test" +Requires-Dist: torchvision; extra == "test" +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: description-content-type +Dynamic: home-page +Dynamic: keywords +Dynamic: license +Dynamic: license-file +Dynamic: provides-extra +Dynamic: requires-dist +Dynamic: requires-python +Dynamic: summary + + + +

🤗 PEFT

+

+

State-of-the-art Parameter-Efficient Fine-Tuning (PEFT) methods

+

+ +Fine-tuning large pretrained models is often prohibitively costly due to their scale. Parameter-Efficient Fine-Tuning (PEFT) methods enable efficient adaptation of large pretrained models to various downstream applications by only fine-tuning a small number of (extra) model parameters instead of all the model's parameters. This significantly decreases the computational and storage costs. Recent state-of-the-art PEFT techniques achieve performance comparable to fully fine-tuned models. + +PEFT is integrated with Transformers for easy model training and inference, Diffusers for conveniently managing different adapters, and Accelerate for distributed training and inference for really big models. + +> [!TIP] +> Visit the [PEFT](https://huggingface.co/PEFT) organization to read about the PEFT methods implemented in the library and to see notebooks demonstrating how to apply these methods to a variety of downstream tasks. Click the "Watch repos" button on the organization page to be notified of newly implemented methods and notebooks! + +Check the PEFT Adapters API Reference section for a list of supported PEFT methods, and read the [Adapters](https://huggingface.co/docs/peft/en/conceptual_guides/adapter), [Soft prompts](https://huggingface.co/docs/peft/en/conceptual_guides/prompting), and [IA3](https://huggingface.co/docs/peft/en/conceptual_guides/ia3) conceptual guides to learn more about how these methods work. + +## Quickstart + +Install PEFT from pip: + +```bash +pip install peft +``` + +Prepare a model for training with a PEFT method such as LoRA by wrapping the base model and PEFT configuration with `get_peft_model`. For the bigscience/mt0-large model, you're only training 0.19% of the parameters! + +```python +from transformers import AutoModelForCausalLM +from peft import LoraConfig, TaskType, get_peft_model + +device = torch.accelerator.current_accelerator().type if hasattr(torch, "accelerator") else "cuda" +model_id = "Qwen/Qwen2.5-3B-Instruct" +model = AutoModelForCausalLM.from_pretrained(model_id, device_map=device) +peft_config = LoraConfig( + r=16, + lora_alpha=32, + task_type=TaskType.CAUSAL_LM, + # target_modules=["q_proj", "v_proj", ...] # optionally indicate target modules +) +model = get_peft_model(model, peft_config) +model.print_trainable_parameters() +# prints: trainable params: 3,686,400 || all params: 3,089,625,088 || trainable%: 0.1193 + +# now perform training on your dataset, e.g. using transformers Trainer, then save the model +model.save_pretrained("qwen2.5-3b-lora") +``` + +To load a PEFT model for inference: + +```python +from transformers import AutoModelForCausalLM, AutoTokenizer +from peft import PeftModel + +device = torch.accelerator.current_accelerator().type if hasattr(torch, "accelerator") else "cuda" +model_id = "Qwen/Qwen2.5-3B-Instruct" +tokenizer = AutoTokenizer.from_pretrained(model_id) +model = AutoModelForCausalLM.from_pretrained(model_id, device_map=device) +model = PeftModel.from_pretrained(model, "qwen2.5-3b-lora") + +inputs = tokenizer("Preheat the oven to 350 degrees and place the cookie dough", return_tensors="pt") +outputs = model.generate(**inputs.to(device), max_new_tokens=50) +print(tokenizer.decode(outputs[0], skip_special_tokens=True)) + +# prints something like: Preheat the oven to 350 degrees and place the cookie dough in a baking dish [...] +``` + +## Why you should use PEFT + +There are many benefits of using PEFT but the main one is the huge savings in compute and storage, making PEFT applicable to many different use cases. + +### High performance on consumer hardware + +Consider the memory requirements for training the following models on the [ought/raft/twitter_complaints](https://huggingface.co/datasets/ought/raft/viewer/twitter_complaints) dataset with an A100 80GB GPU with more than 64GB of CPU RAM. + +| Model | Full Finetuning | PEFT-LoRA PyTorch | PEFT-LoRA DeepSpeed with CPU Offloading | +| --------- | ---- | ---- | ---- | +| bigscience/T0_3B (3B params) | 47.14GB GPU / 2.96GB CPU | 14.4GB GPU / 2.96GB CPU | 9.8GB GPU / 17.8GB CPU | +| bigscience/mt0-xxl (12B params) | OOM GPU | 56GB GPU / 3GB CPU | 22GB GPU / 52GB CPU | +| bigscience/bloomz-7b1 (7B params) | OOM GPU | 32GB GPU / 3.8GB CPU | 18.1GB GPU / 35GB CPU | + +With LoRA you can fully finetune a 12B parameter model that would've otherwise run out of memory on the 80GB GPU, and comfortably fit and train a 3B parameter model. When you look at the 3B parameter model's performance, it is comparable to a fully finetuned model at a fraction of the GPU memory. + +| Submission Name | Accuracy | +| --------- | ---- | +| Human baseline (crowdsourced) | 0.897 | +| Flan-T5 | 0.892 | +| lora-t0-3b | 0.863 | + +> [!TIP] +> The bigscience/T0_3B model performance isn't optimized in the table above. You can squeeze even more performance out of it by playing around with the input instruction templates, LoRA hyperparameters, and other training related hyperparameters. The final checkpoint size of this model is just 19MB compared to 11GB of the full bigscience/T0_3B model. Learn more about the advantages of finetuning with PEFT in this [blog post](https://www.philschmid.de/fine-tune-flan-t5-peft). + +### Quantization + +Quantization is another method for reducing the memory requirements of a model by representing the data in a lower precision. It can be combined with PEFT methods to make it even easier to train and load LLMs for inference. + +* Learn how to finetune [meta-llama/Llama-2-7b-hf](https://huggingface.co/meta-llama/Llama-2-7b-hf) with QLoRA and the [TRL](https://huggingface.co/docs/trl/index) library on a 16GB GPU in the [Finetune LLMs on your own consumer hardware using tools from PyTorch and Hugging Face ecosystem](https://pytorch.org/blog/finetune-llms/) blog post. +* Learn how to finetune a [openai/whisper-large-v2](https://huggingface.co/openai/whisper-large-v2) model for multilingual automatic speech recognition with LoRA and 8-bit quantization in this [notebook](https://colab.research.google.com/drive/1DOkD_5OUjFa0r5Ik3SgywJLJtEo2qLxO?usp=sharing) (see this [notebook](https://colab.research.google.com/drive/1vhF8yueFqha3Y3CpTHN6q9EVcII9EYzs?usp=sharing) instead for an example of streaming a dataset). + +### Save compute and storage + +PEFT can help you save storage by avoiding full finetuning of models on each of downstream task or dataset. In many cases, you're only finetuning a very small fraction of a model's parameters and each checkpoint is only a few MBs in size (instead of GBs). These smaller PEFT adapters demonstrate performance comparable to a fully finetuned model. If you have many datasets, you can save a lot of storage with a PEFT model and not have to worry about catastrophic forgetting or overfitting the backbone or base model. + +## PEFT integrations + +PEFT is widely supported across the Hugging Face ecosystem because of the massive efficiency it brings to training and inference. + +### Diffusers + +The iterative diffusion process consumes a lot of memory which can make it difficult to train. PEFT can help reduce the memory requirements and reduce the storage size of the final model checkpoint. For example, consider the memory required for training a Stable Diffusion model with LoRA on an A100 80GB GPU with more than 64GB of CPU RAM. The final model checkpoint size is only 8.8MB! + +| Model | Full Finetuning | PEFT-LoRA | PEFT-LoRA with Gradient Checkpointing | +| --------- | ---- | ---- | ---- | +| CompVis/stable-diffusion-v1-4 | 27.5GB GPU / 3.97GB CPU | 15.5GB GPU / 3.84GB CPU | 8.12GB GPU / 3.77GB CPU | + +> [!TIP] +> Take a look at the [examples/lora_dreambooth/train_dreambooth.py](examples/lora_dreambooth/train_dreambooth.py) training script to try training your own Stable Diffusion model with LoRA, and play around with the [smangrul/peft-lora-sd-dreambooth](https://huggingface.co/spaces/smangrul/peft-lora-sd-dreambooth) Space which is running on a T4 instance. Learn more about the PEFT integration in Diffusers in this [tutorial](https://huggingface.co/docs/peft/main/en/tutorial/peft_integrations#diffusers). + +### Transformers + +PEFT is directly integrated with [Transformers](https://huggingface.co/docs/transformers/main/en/peft). After loading a model, call `add_adapter` to add a new PEFT adapter to the model: + +```python +from peft import LoraConfig +model = ... # transformers model +peft_config = LoraConfig(...) +model.add_adapter(lora_config, adapter_name="lora_1") +``` + +To load a trained PEFT adapter, call `load_adapter`: + +```python +model = ... # transformers model +model.load_adapter(, adapter_name="lora_1") +``` + +And to switch between different adapters, call `set_adapter`: + +```python +model.set_adapter("lora_2") +``` + +The Transformers integration doesn't include all the functionalities offered in PEFT, such as methods for merging the adapter into the base model. + +### Accelerate + +[Accelerate](https://huggingface.co/docs/accelerate/index) is a library for distributed training and inference on various training setups and hardware (GPUs, TPUs, Apple Silicon, etc.). PEFT models work with Accelerate out of the box, making it really convenient to train really large models or use them for inference on consumer hardware with limited resources. + +### TRL + +PEFT can also be applied to training LLMs with RLHF components such as the ranker and policy. Get started by reading: + +* [Fine-tune a Mistral-7b model with Direct Preference Optimization](https://towardsdatascience.com/fine-tune-a-mistral-7b-model-with-direct-preference-optimization-708042745aac) with PEFT and the [TRL](https://huggingface.co/docs/trl/index) library to learn more about the Direct Preference Optimization (DPO) method and how to apply it to a LLM. +* [Fine-tuning 20B LLMs with RLHF on a 24GB consumer GPU](https://huggingface.co/blog/trl-peft) with PEFT and the [TRL](https://huggingface.co/docs/trl/index) library, and then try out the [gpt2-sentiment_peft.ipynb](https://github.com/huggingface/trl/blob/main/examples/notebooks/gpt2-sentiment.ipynb) notebook to optimize GPT2 to generate positive movie reviews. +* [StackLLaMA: A hands-on guide to train LLaMA with RLHF](https://huggingface.co/blog/stackllama) with PEFT, and then try out the [stack_llama/scripts](https://github.com/huggingface/trl/tree/main/examples/research_projects/stack_llama/scripts) for supervised finetuning, reward modeling, and RL finetuning. + +## Model support + +Use this [Space](https://stevhliu-peft-methods.hf.space) or check out the [docs](https://huggingface.co/docs/peft/main/en/index) to find which models officially support a PEFT method out of the box. Even if you don't see a model listed below, you can manually configure the model config to enable PEFT for a model. Read the [New transformers architecture](https://huggingface.co/docs/peft/main/en/developer_guides/custom_models#new-transformers-architectures) guide to learn how. + +## Contribute + +If you would like to contribute to PEFT, please check out our [contribution guide](https://huggingface.co/docs/peft/developer_guides/contributing). + +## Citing 🤗 PEFT + +To use 🤗 PEFT in your publication, please cite it by using the following BibTeX entry. + +```bibtex +@Misc{peft, + title = {{PEFT}: State-of-the-art Parameter-Efficient Fine-Tuning methods}, + author = {Sourab Mangrulkar and Sylvain Gugger and Lysandre Debut and Younes Belkada and Sayak Paul and Benjamin Bossan and Marian Tietz}, + howpublished = {\url{https://github.com/huggingface/peft}}, + year = {2022} +} +``` diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft-0.19.1.dist-info/RECORD b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft-0.19.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..2dab443ffdcfb3e9067352fa8a2b6172be1cdc6c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft-0.19.1.dist-info/RECORD @@ -0,0 +1,445 @@ +peft-0.19.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +peft-0.19.1.dist-info/METADATA,sha256=H2WLXuhA0oW9t6ChAWf1cAmtTakRjC-6w8IjEX1cfEg,15103 +peft-0.19.1.dist-info/RECORD,, +peft-0.19.1.dist-info/WHEEL,sha256=lTU6B6eIfYoiQJTZNc-fyaR6BpL6ehTzU3xGYxn2n8k,91 +peft-0.19.1.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357 +peft-0.19.1.dist-info/top_level.txt,sha256=DOKoqHe6fr-A3g26PPWvf5bHLy8fHKhflUO5xzJJEUY,5 +peft/__init__.py,sha256=ad4xoMKL4qbiLUigz_RpyOmKZ-7OWgv8zDflLO4AR1E,7031 +peft/__pycache__/__init__.cpython-310.pyc,, +peft/__pycache__/auto.cpython-310.pyc,, +peft/__pycache__/config.cpython-310.pyc,, +peft/__pycache__/functional.cpython-310.pyc,, +peft/__pycache__/helpers.cpython-310.pyc,, +peft/__pycache__/import_utils.cpython-310.pyc,, +peft/__pycache__/mapping.cpython-310.pyc,, +peft/__pycache__/mapping_func.cpython-310.pyc,, +peft/__pycache__/mixed_model.cpython-310.pyc,, +peft/__pycache__/peft_model.cpython-310.pyc,, +peft/auto.py,sha256=MAxPviiRqTiPwRLsSIXd3o4TPzS_8SkJu1L_uxPbD5s,7269 +peft/config.py,sha256=sFBiR5NPsGflO4Bbj2ekNpKFCAm4N3Eajl77CbgG_IU,17107 +peft/functional.py,sha256=2gA_VUoQmcsaH0AA7GhLIsOc_NLja8EKbjxOhj5jono,1284 +peft/helpers.py,sha256=Pqq_1wkyg-6DtV9MK84isB5i4B-QRn_du8DdJRJ6Poo,11211 +peft/import_utils.py,sha256=yR0ZM8FVrVqOcy0h_rTTWXjFyBzPwXPfg_AUY6zLyz8,6639 +peft/mapping.py,sha256=8c4_n32gANDzdLA-8wohO1jcYuGrDLXYecRs_Rc4Mrc,3878 +peft/mapping_func.py,sha256=cU2zvBesXT1yuupEop-DYZnacxzsx-lvnPNn681giaE,5898 +peft/mixed_model.py,sha256=0Ygk6s7ncQCZEayuDI6B_Z1zXHqtn1Ug6QpnfWKaDwg,21167 +peft/optimizers/__init__.py,sha256=U9b6PPoAZ7XaOvEaP8JNSQsCGNHxygrt_8srMxZBdyE,760 +peft/optimizers/__pycache__/__init__.cpython-310.pyc,, +peft/optimizers/__pycache__/lorafa.cpython-310.pyc,, +peft/optimizers/__pycache__/loraplus.cpython-310.pyc,, +peft/optimizers/lorafa.py,sha256=_I_keXdJVjnYti6TyNbQ8Arw4JtCwq56bYgf5hTVFnw,11390 +peft/optimizers/loraplus.py,sha256=_yyE145kThOfAzdvyLrSc1KIrs28NG1BTy_bGspif8o,4736 +peft/peft_model.py,sha256=z50e0JHckDFfRW7UVuQE51F9W3mRklYlCcD-mY-I_uI,169169 +peft/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +peft/tuners/__init__.py,sha256=Y3my7EWaojdB0ep_a_CFoHRoAOFfZW6joEHjPrMipzA,4642 +peft/tuners/__pycache__/__init__.cpython-310.pyc,, +peft/tuners/__pycache__/_buffer_dict.cpython-310.pyc,, +peft/tuners/__pycache__/lycoris_utils.cpython-310.pyc,, +peft/tuners/__pycache__/tuners_utils.cpython-310.pyc,, +peft/tuners/_buffer_dict.py,sha256=Ws3qF5XfS6p3YHTmQb3MDGdcHAfwzdk2eTPsh3Xuylc,5529 +peft/tuners/adalora/__init__.py,sha256=UZn9KKpzni8W1va5aGMS5nfz0GYY0lWbrjSV4V64fiQ,1479 +peft/tuners/adalora/__pycache__/__init__.cpython-310.pyc,, +peft/tuners/adalora/__pycache__/bnb.cpython-310.pyc,, +peft/tuners/adalora/__pycache__/config.cpython-310.pyc,, +peft/tuners/adalora/__pycache__/gptq.cpython-310.pyc,, +peft/tuners/adalora/__pycache__/layer.cpython-310.pyc,, +peft/tuners/adalora/__pycache__/model.cpython-310.pyc,, +peft/tuners/adalora/bnb.py,sha256=dR19kiSJEmxtcbDAmalLFxJ-WE5QkxFPHb3y36bj8Cg,5426 +peft/tuners/adalora/config.py,sha256=0MHuhMmNo_sjraeXCIWFbQBymhFwrA_YN_Q-fNOjx68,5689 +peft/tuners/adalora/gptq.py,sha256=eT_VQkEtZugcp0DNJvSrDjPTl-V1s-N92BC-UmeGw1k,2684 +peft/tuners/adalora/layer.py,sha256=ZmirOcQiCqYAUcmSsiUKnguu_G-etZQb_5o8F6grnao,14966 +peft/tuners/adalora/model.py,sha256=u0mq_CQeN9sxsNC34PQmfMCplp6svCEMjXFJd0LTYJg,15102 +peft/tuners/adamss/__init__.py,sha256=_L4RMJgoIMmP77FhVOvuGAl5T88iIvTX1Fsh2xBnuxo,1006 +peft/tuners/adamss/__pycache__/__init__.cpython-310.pyc,, +peft/tuners/adamss/__pycache__/asa_callback.cpython-310.pyc,, +peft/tuners/adamss/__pycache__/config.cpython-310.pyc,, +peft/tuners/adamss/__pycache__/layer.cpython-310.pyc,, +peft/tuners/adamss/__pycache__/model.cpython-310.pyc,, +peft/tuners/adamss/__pycache__/utils.cpython-310.pyc,, +peft/tuners/adamss/asa_callback.py,sha256=1HheXwpPWvsXJhHUCyLcHkwUIYobY56T1SxqRaAQwW8,3207 +peft/tuners/adamss/config.py,sha256=AXmBZ-SchHs9JfC7AZA-xd9nkLaxjKkDZjiyiZxixJk,17035 +peft/tuners/adamss/layer.py,sha256=qOoEPkRzoOIByQGzqcuyDlYE9DIs_9yG2qV0su1vMEE,29070 +peft/tuners/adamss/model.py,sha256=XMmYpr8x1_n5ngIo6ANmtpq2kMsbli1u9n88n2rVTyk,11975 +peft/tuners/adamss/utils.py,sha256=dU040X807UxmfjFAasFhgGIegRsuwJAMsgJ5ao1hJhY,4111 +peft/tuners/adaption_prompt/__init__.py,sha256=C3vrdUyV7042lan7Y3jrRer7-EElxHNvd9LsvwSWHCc,949 +peft/tuners/adaption_prompt/__pycache__/__init__.cpython-310.pyc,, +peft/tuners/adaption_prompt/__pycache__/config.cpython-310.pyc,, +peft/tuners/adaption_prompt/__pycache__/layer.cpython-310.pyc,, +peft/tuners/adaption_prompt/__pycache__/model.cpython-310.pyc,, +peft/tuners/adaption_prompt/__pycache__/utils.cpython-310.pyc,, +peft/tuners/adaption_prompt/config.py,sha256=OC9R0jtc8ZCkEvM4U9DDEzr9dBY1znsFUWLaSsC55tM,3157 +peft/tuners/adaption_prompt/layer.py,sha256=mcqaQ0Vfm9sSxeYMgokRHShJVTITOT5KVkrhaJJpD_M,9689 +peft/tuners/adaption_prompt/model.py,sha256=uk3XZRDYlkjAcsKFyv_QpqSHsU5a4jmiFaOAgERHbx0,8046 +peft/tuners/adaption_prompt/utils.py,sha256=d69bbtFIFQZy4k5YHlNc6CAAD3EnwgowtXbrMTEPS0M,7184 +peft/tuners/boft/__init__.py,sha256=M5RzpzRMchgBuglsGS6rAgcc1cOTrZiRn-cD3ic9sXQ,865 +peft/tuners/boft/__pycache__/__init__.cpython-310.pyc,, +peft/tuners/boft/__pycache__/config.cpython-310.pyc,, +peft/tuners/boft/__pycache__/layer.cpython-310.pyc,, +peft/tuners/boft/__pycache__/model.cpython-310.pyc,, +peft/tuners/boft/config.py,sha256=fMllyQI2rzIKxNsMT2ITbX-IWjBhO7ZN2b14u2epIck,8370 +peft/tuners/boft/fbd/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +peft/tuners/boft/fbd/__pycache__/__init__.cpython-310.pyc,, +peft/tuners/boft/fbd/fbd_cuda.cpp,sha256=w9Pny1nGyyERI6Vmjnxh-LhbP769aL0XKDZIc_nAy48,815 +peft/tuners/boft/fbd/fbd_cuda_kernel.cu,sha256=SgFrZw-WjJrOxq-Q3qugwLAoI4gBWDqJGlnfoPgpQPs,3076 +peft/tuners/boft/layer.py,sha256=oDDK0S1e1jHkpJP8JZvsDvxedMpVjFb4RY22AxpYB5U,42732 +peft/tuners/boft/model.py,sha256=RfEA1dJgW7YF6Vl1Y0D8BoYPv1Od_rLIEhD3NAT0tGw,5333 +peft/tuners/c3a/__init__.py,sha256=fvrOSHHtbJ2YbLc5B3NRXTj9KXcYAz6oZqpkgGD8EZk,879 +peft/tuners/c3a/__pycache__/__init__.cpython-310.pyc,, +peft/tuners/c3a/__pycache__/config.cpython-310.pyc,, +peft/tuners/c3a/__pycache__/layer.cpython-310.pyc,, +peft/tuners/c3a/__pycache__/model.cpython-310.pyc,, +peft/tuners/c3a/__pycache__/utils.cpython-310.pyc,, +peft/tuners/c3a/config.py,sha256=5p620LSBl7h5lwhNKyzdOgbWHNjcS8Do5rAukZEGUOE,6824 +peft/tuners/c3a/layer.py,sha256=ekmId8qz9I6AHkoztZIT0RauRW0GlhIZXnAPLNNwxVY,8674 +peft/tuners/c3a/model.py,sha256=9krLbHCWmO0Z26yM3H1V2J6sgVwUzRPCXvJYHL3BV74,3565 +peft/tuners/c3a/utils.py,sha256=N3HPTyDqhUel3uMbQACzHLLln733h6qfw5RPpWae4H8,1767 +peft/tuners/cartridge/__init__.py,sha256=qsm96uAO_2s-PiXdK5C-oR_VJJNYL30KFvpNJzXQSyM,864 +peft/tuners/cartridge/__pycache__/__init__.cpython-310.pyc,, +peft/tuners/cartridge/__pycache__/config.cpython-310.pyc,, +peft/tuners/cartridge/__pycache__/model.cpython-310.pyc,, +peft/tuners/cartridge/__pycache__/utils.cpython-310.pyc,, +peft/tuners/cartridge/config.py,sha256=QZdChgotPCmLyBugs6Cuus3gxmn6YlgxXzMINX9SmLU,3509 +peft/tuners/cartridge/model.py,sha256=vddNdl3DP-KzbBOXdGyMFqTeJWKHeEtedBjNVswYLm0,4793 +peft/tuners/cartridge/utils.py,sha256=bdkaq3n_OggjpZToak5qqur-gqJlvP1K8gT-Jm998mM,9606 +peft/tuners/cpt/__init__.py,sha256=eRetdUVUtxHm7Ic_YkGUvCrlmkGjHEZOQW48wlT6lDU,829 +peft/tuners/cpt/__pycache__/__init__.cpython-310.pyc,, +peft/tuners/cpt/__pycache__/config.cpython-310.pyc,, +peft/tuners/cpt/__pycache__/model.cpython-310.pyc,, +peft/tuners/cpt/config.py,sha256=4ndbytAfH9didkFxFs0T0RDWsm37gPO8YSqPCgRwbQY,4126 +peft/tuners/cpt/model.py,sha256=CWaYuKa05pGEfIVktLqBybh8O1Q791u6PjlXm7AhJPk,8451 +peft/tuners/delora/__init__.py,sha256=VUJflGJWoydwPrs5Fy1YL_Qf9X_GxUQ2EvXLza1WHJI,912 +peft/tuners/delora/__pycache__/__init__.cpython-310.pyc,, +peft/tuners/delora/__pycache__/config.cpython-310.pyc,, +peft/tuners/delora/__pycache__/layer.cpython-310.pyc,, +peft/tuners/delora/__pycache__/model.cpython-310.pyc,, +peft/tuners/delora/config.py,sha256=l34QUZ1os1igYkSbOZPAFyZI7ZCLW9WTn982WamgQGI,9251 +peft/tuners/delora/layer.py,sha256=62a_EjqapAhCBjaFDlBDxue3ZLWFtvh23HaGLFI1Bpk,10524 +peft/tuners/delora/model.py,sha256=7TmXFENbsANn6GPB9ujnjUyY7s99PQ4pZuwP58LUsQU,3925 +peft/tuners/fourierft/__init__.py,sha256=mM9_QZx9OX6iGv6bdUX3OA717S4J12XHB17olneyoFA,946 +peft/tuners/fourierft/__pycache__/__init__.cpython-310.pyc,, +peft/tuners/fourierft/__pycache__/config.cpython-310.pyc,, +peft/tuners/fourierft/__pycache__/layer.cpython-310.pyc,, +peft/tuners/fourierft/__pycache__/model.cpython-310.pyc,, +peft/tuners/fourierft/config.py,sha256=p4CQgBOrailVA9pF6Vm8X71WWNqHs_WXMbN1ivkCIJ8,12215 +peft/tuners/fourierft/layer.py,sha256=elVCjbYYZaJLoiRas9fZVJNfrjC8ZbasgcQWad9Nlw8,8940 +peft/tuners/fourierft/model.py,sha256=X41WsSUjoj39CdAoXxAbfz_p1077Pk_QZQwODzvb7_w,5117 +peft/tuners/gralora/__init__.py,sha256=5fGvAhJiR6vhIfL3x7mUpwpQONw-MLPL-Cuqw2jZcTs,892 +peft/tuners/gralora/__pycache__/__init__.cpython-310.pyc,, +peft/tuners/gralora/__pycache__/config.cpython-310.pyc,, +peft/tuners/gralora/__pycache__/layer.cpython-310.pyc,, +peft/tuners/gralora/__pycache__/model.cpython-310.pyc,, +peft/tuners/gralora/config.py,sha256=5Lyn9MXFQooqs5mYtcsiMqb0D8bqTQIcYNXs3w5bt2o,9860 +peft/tuners/gralora/layer.py,sha256=AQcfrlq-wi_7ywOi0-l6T1XhcS_laQu6B8Pf36FME5I,15973 +peft/tuners/gralora/model.py,sha256=mVFivSlm_iurrHv-W6iudoxHCLf-B1f93HYf5ofk6AI,5131 +peft/tuners/hra/__init__.py,sha256=YAhlcshKSkU5RB57ggsi4Q57zeGPIgKQwL_FbCd8SKg,904 +peft/tuners/hra/__pycache__/__init__.cpython-310.pyc,, +peft/tuners/hra/__pycache__/config.cpython-310.pyc,, +peft/tuners/hra/__pycache__/layer.cpython-310.pyc,, +peft/tuners/hra/__pycache__/model.cpython-310.pyc,, +peft/tuners/hra/config.py,sha256=8dO7PNWCBOh4BnD1S2frpj14aAP8R2DH-5e8PENpK_k,6946 +peft/tuners/hra/layer.py,sha256=Qs727PVaI9DPkvsdD7Rw_jwWzsPeMJSEmFKY4_7uoq4,19115 +peft/tuners/hra/model.py,sha256=QzQxSzguByRTMC7GEZiAwrLKok5gJyEdzr5mD_IR1Jk,4779 +peft/tuners/ia3/__init__.py,sha256=kuH_j1DLRgh8tXv4zqpfTedXpV7cHkUwSX8Q_KOwzDg,1349 +peft/tuners/ia3/__pycache__/__init__.cpython-310.pyc,, +peft/tuners/ia3/__pycache__/bnb.cpython-310.pyc,, +peft/tuners/ia3/__pycache__/config.cpython-310.pyc,, +peft/tuners/ia3/__pycache__/layer.cpython-310.pyc,, +peft/tuners/ia3/__pycache__/model.cpython-310.pyc,, +peft/tuners/ia3/bnb.py,sha256=GvoVKQS0t4u5Xnq-isEMLi8m_VgZdBZPc6LrVEZdHkM,4668 +peft/tuners/ia3/config.py,sha256=aldnE7rwHyX0GdiYDHwxg2bhce9WG84PrFotNyrE3bk,5924 +peft/tuners/ia3/layer.py,sha256=TlcHBieLL3j5oFJFnoQQ8mr0QPvpWZJcRkSSWaDiTFI,15053 +peft/tuners/ia3/model.py,sha256=TQ9m1saq3h3U9T_HIi6jo_hBmn0HhvOhlvb3jYTt0kA,13607 +peft/tuners/lily/__init__.py,sha256=vVC9tDoumbwkbrGWQxwjXh-kbNZseChWkNMm-e4IKgs,932 +peft/tuners/lily/__pycache__/__init__.cpython-310.pyc,, +peft/tuners/lily/__pycache__/config.cpython-310.pyc,, +peft/tuners/lily/__pycache__/layer.cpython-310.pyc,, +peft/tuners/lily/__pycache__/model.cpython-310.pyc,, +peft/tuners/lily/config.py,sha256=vR8KIpP7drnXijYBIzyI3-0Frn7NWVQKhN0FiIRMlok,14892 +peft/tuners/lily/layer.py,sha256=sL5Cx5yVAy81eeRmLj7wgkMGZ5dkIIha5jU1XyqJHAQ,6938 +peft/tuners/lily/model.py,sha256=_j13i2pPyUTWwDS8vqufICGU1eSlt5ophOSEcJjhre4,6720 +peft/tuners/ln_tuning/__init__.py,sha256=eSQwNTe2K73a10v8Va35OgaUfvIwIYdDt4Xxw-W8DNM,852 +peft/tuners/ln_tuning/__pycache__/__init__.cpython-310.pyc,, +peft/tuners/ln_tuning/__pycache__/config.cpython-310.pyc,, +peft/tuners/ln_tuning/__pycache__/layer.cpython-310.pyc,, +peft/tuners/ln_tuning/__pycache__/model.cpython-310.pyc,, +peft/tuners/ln_tuning/config.py,sha256=Lfa6Bo1jMO0v-KQrDo8lbtCsg9BQiB5BARimKY837WE,3405 +peft/tuners/ln_tuning/layer.py,sha256=KB_F0ow_nlTfPnK1k14dGQsSm4dV35m38Z45pOCG6Co,4751 +peft/tuners/ln_tuning/model.py,sha256=LwWlpz-4yeG-B0R2pofRbswywZQyt_VpPv1MRweOmJw,5346 +peft/tuners/loha/__init__.py,sha256=ONprqmQIy45oSa9FLtn-XksHwHyLmPQ_reZ5OhwMBy8,943 +peft/tuners/loha/__pycache__/__init__.cpython-310.pyc,, +peft/tuners/loha/__pycache__/config.cpython-310.pyc,, +peft/tuners/loha/__pycache__/layer.cpython-310.pyc,, +peft/tuners/loha/__pycache__/model.cpython-310.pyc,, +peft/tuners/loha/config.py,sha256=GWzvaH08T_10oGGvjRFSCtaWuW9s-oAw0XHqIbZORnQ,7531 +peft/tuners/loha/layer.py,sha256=IV0qV_YNFuttiA0T9gJN0j7ypGwxbA-rTpjBLZLlE2Y,19003 +peft/tuners/loha/model.py,sha256=oABxNAyiVCccBEVPLtzxGMRagMMe7RWX2es0FlWdiVM,4429 +peft/tuners/lokr/__init__.py,sha256=j8J43bJg8uaCH-LgGXtJ1B8xdtmKtdIu8k2Fr6Zoscw,927 +peft/tuners/lokr/__pycache__/__init__.cpython-310.pyc,, +peft/tuners/lokr/__pycache__/config.cpython-310.pyc,, +peft/tuners/lokr/__pycache__/layer.cpython-310.pyc,, +peft/tuners/lokr/__pycache__/model.cpython-310.pyc,, +peft/tuners/lokr/config.py,sha256=3xCqIgW7IwSM1D0K2Tbk-jw-wKaQrbebyyCOtd5jnH8,8325 +peft/tuners/lokr/layer.py,sha256=JcxeVf0lSrdzN7UlFAYQF8Z-KGNr1XRkFi50LEbvvx0,20757 +peft/tuners/lokr/model.py,sha256=kVTAGl_Isi73_H5LjdVus7owFx0NuTUOouBucqxlcCI,4556 +peft/tuners/lora/__init__.py,sha256=AlQZRpclG-Mft9xyC8D7n9_SLOAvMnMZChbaDORpCWg,2207 +peft/tuners/lora/__pycache__/__init__.cpython-310.pyc,, +peft/tuners/lora/__pycache__/aqlm.cpython-310.pyc,, +peft/tuners/lora/__pycache__/arrow.cpython-310.pyc,, +peft/tuners/lora/__pycache__/awq.cpython-310.pyc,, +peft/tuners/lora/__pycache__/bnb.cpython-310.pyc,, +peft/tuners/lora/__pycache__/config.cpython-310.pyc,, +peft/tuners/lora/__pycache__/conversion.cpython-310.pyc,, +peft/tuners/lora/__pycache__/corda.cpython-310.pyc,, +peft/tuners/lora/__pycache__/dora.cpython-310.pyc,, +peft/tuners/lora/__pycache__/eetq.cpython-310.pyc,, +peft/tuners/lora/__pycache__/eva.cpython-310.pyc,, +peft/tuners/lora/__pycache__/gptq.cpython-310.pyc,, +peft/tuners/lora/__pycache__/hqq.cpython-310.pyc,, +peft/tuners/lora/__pycache__/inc.cpython-310.pyc,, +peft/tuners/lora/__pycache__/intruders.cpython-310.pyc,, +peft/tuners/lora/__pycache__/layer.cpython-310.pyc,, +peft/tuners/lora/__pycache__/loraga.cpython-310.pyc,, +peft/tuners/lora/__pycache__/model.cpython-310.pyc,, +peft/tuners/lora/__pycache__/te.cpython-310.pyc,, +peft/tuners/lora/__pycache__/torchao.cpython-310.pyc,, +peft/tuners/lora/__pycache__/tp_layer.cpython-310.pyc,, +peft/tuners/lora/__pycache__/variants.cpython-310.pyc,, +peft/tuners/lora/aqlm.py,sha256=_-6h1C6yLSXuLpgDO1FT9w_FO-FwMEqj0uxIAKMXymo,3509 +peft/tuners/lora/arrow.py,sha256=hdysWKrJ2VHjdedWB3anJUyt93lJSs2XJGgKu0lisx4,19850 +peft/tuners/lora/awq.py,sha256=einasBI5OmMbK4M6uI5c0DCVabB3K42b6QXObZspxKY,3332 +peft/tuners/lora/bnb.py,sha256=bEUPIApJHnr9X9hwlxhSF_PAoG5HKwKC4NLiofIi5ZI,26118 +peft/tuners/lora/config.py,sha256=qfleGhQ7gyDPLgoxOfKcgH2TeHZZH1_BziT8T9eDO1k,53728 +peft/tuners/lora/conversion.py,sha256=6oLLSkngPydAJBM8Za1WUi5Q0hD7nTluxriA_KH8vuI,17974 +peft/tuners/lora/corda.py,sha256=fcCHphZS1U1Y0p-KrXx78NUWIvRbk5t4AawCXl53WaE,15982 +peft/tuners/lora/dora.py,sha256=L_nSIu6touyC1kFK0uDkaxfGzLdvwswJI6IMB5zPl0w,11792 +peft/tuners/lora/eetq.py,sha256=m1vpAYC5EPJ_mtJ7zEHhpiEKDi5FcyVUSz5fLIDSPog,3877 +peft/tuners/lora/eva.py,sha256=L7-pUGesLUAROjhNgVCI8bjwU7EA7flR9lHgjB4wPEg,34122 +peft/tuners/lora/gptq.py,sha256=5TY2f2LCIkmNoA8TitxcIJqndFYlO9As1cqUWhACZnQ,4569 +peft/tuners/lora/hqq.py,sha256=7Pe3e7Q2-fA-xg4ujAKnlLk_AZTzOfpeaLpHI7vRO1g,10143 +peft/tuners/lora/inc.py,sha256=CYSjT9beAd7MAqWSbqHBG4k5vAJyvmVEIc_csg1sK2I,3076 +peft/tuners/lora/intruders.py,sha256=JNuz-w7ymH8WTaYgpH_R7ZwVavg9VX48cY3HZs9AToo,8088 +peft/tuners/lora/layer.py,sha256=REu6Dl28XFXtUaKIqDZsGKp-vlM9CBMSoZNH60iyFbY,113852 +peft/tuners/lora/loraga.py,sha256=VdI_kJs1SWEpvDYb8M_1naBselcIatmL5xCXUEV4zOg,7664 +peft/tuners/lora/model.py,sha256=YwFARxpiPkLxMGHmEhW2DqRcpRHucpq146GTNygXgPs,49179 +peft/tuners/lora/te.py,sha256=eEiQupo8DZbvTkbYqcaTMNFp6O6JuG_zSDOeJUJL4Pg,4326 +peft/tuners/lora/torchao.py,sha256=sQMyRWEsQJWCDHRr6jhT42YR4WmpqQr2tkQ95KWL8Ss,5570 +peft/tuners/lora/tp_layer.py,sha256=KcuJvt_A4nfnt6GOVotTeOYSUi97K1MvJtBaetW2dhw,14109 +peft/tuners/lora/variants.py,sha256=4e4oL3RwJ3NHVerR50aHog5yi9q5CD5qwCePyINCfzI,40376 +peft/tuners/lycoris_utils.py,sha256=mw6xc9-Uwke6WFXOySAPNMH80PbgCohh4xkaq4meR-s,10096 +peft/tuners/miss/__init__.py,sha256=0k0uGeggR84kDE11na2-A3XRsWfX9s4N4h5aoLq2Nu0,891 +peft/tuners/miss/__pycache__/__init__.cpython-310.pyc,, +peft/tuners/miss/__pycache__/config.cpython-310.pyc,, +peft/tuners/miss/__pycache__/layer.cpython-310.pyc,, +peft/tuners/miss/__pycache__/model.cpython-310.pyc,, +peft/tuners/miss/config.py,sha256=6ucl5RwsnIOBb3iN62Ie0Ff26Gq58E2RpJ6b14oDMRg,7682 +peft/tuners/miss/layer.py,sha256=j22PskOsNg7uvg176QRhXZh7O4FpBeyL8Z7VS9hFGg8,17344 +peft/tuners/miss/model.py,sha256=olfjJarVFbRAZ_iU6qRV_0PkY0ffa0JIVdxlP6AoRQ8,4730 +peft/tuners/mixed/__init__.py,sha256=see7CbOiJJ-E8W1QSSBtIK4oQfFnkJOUVU5xckCYyzw,706 +peft/tuners/mixed/__pycache__/__init__.cpython-310.pyc,, +peft/tuners/mixed/__pycache__/model.cpython-310.pyc,, +peft/tuners/mixed/model.py,sha256=_RfxhnwPrWNVfyA7Su5SuJghqUsVQdVSQmAlHAq1wkI,13700 +peft/tuners/multitask_prompt_tuning/__init__.py,sha256=YRacKPnRhZ63bW8EmTzUirZjhMxU0sivhsLtj3NiCTU,1000 +peft/tuners/multitask_prompt_tuning/__pycache__/__init__.cpython-310.pyc,, +peft/tuners/multitask_prompt_tuning/__pycache__/config.cpython-310.pyc,, +peft/tuners/multitask_prompt_tuning/__pycache__/model.cpython-310.pyc,, +peft/tuners/multitask_prompt_tuning/config.py,sha256=WMitUfJdO-u7GAeSQMkV643upKCU5iOlUsHb5O-SzDY,2478 +peft/tuners/multitask_prompt_tuning/model.py,sha256=zDfMF8lCosOKP14qrPe-5GffdHOFvgoeLkRxXfNK5gI,4915 +peft/tuners/oft/__init__.py,sha256=WeqJeH3Ho_jaWI_BMbxHXSIeCi8HntaEwpJL_5jBo8Y,1529 +peft/tuners/oft/__pycache__/__init__.cpython-310.pyc,, +peft/tuners/oft/__pycache__/aqlm.cpython-310.pyc,, +peft/tuners/oft/__pycache__/awq.cpython-310.pyc,, +peft/tuners/oft/__pycache__/bnb.cpython-310.pyc,, +peft/tuners/oft/__pycache__/config.cpython-310.pyc,, +peft/tuners/oft/__pycache__/eetq.cpython-310.pyc,, +peft/tuners/oft/__pycache__/gptq.cpython-310.pyc,, +peft/tuners/oft/__pycache__/hqq.cpython-310.pyc,, +peft/tuners/oft/__pycache__/inc.cpython-310.pyc,, +peft/tuners/oft/__pycache__/layer.cpython-310.pyc,, +peft/tuners/oft/__pycache__/model.cpython-310.pyc,, +peft/tuners/oft/aqlm.py,sha256=OJa0Po1Sv8MA5OyWmhuhgjli9FoPffMOUyqqujO0-zg,3291 +peft/tuners/oft/awq.py,sha256=atnKTTg0pFHYl0JR2XD6UGFo4pu_9BbD4wR7k5No3hQ,3493 +peft/tuners/oft/bnb.py,sha256=HooSmYNDmk6aQ5tr5negP7glbflhk9plFdFbkoBfE0U,15881 +peft/tuners/oft/config.py,sha256=-k23msGh7DepEoVxcACHQQwKkvWhZ-XUFGPdCHOC7DI,11107 +peft/tuners/oft/eetq.py,sha256=nzvLoK96rxn-YjV-UFU_K-DMN4KLubGTsz7z1YP7WBg,4001 +peft/tuners/oft/gptq.py,sha256=Rc2Cm3cbfS9GYkVFCmAg6IX6qDJwPCxatdgHylqi9GI,3539 +peft/tuners/oft/hqq.py,sha256=1FgcujKqpDVEHNwvooy6DVvROYIh2Is1FaZsf4xApts,7322 +peft/tuners/oft/inc.py,sha256=neKIK1Z0NbZJE5V5NKU41o76k5jRGG1p9FXUVuRFeFw,2959 +peft/tuners/oft/layer.py,sha256=T0ikxV6Cl_3eIGZq81Olxhmmbk-pvqQCQqz6ZtKH7HM,48887 +peft/tuners/oft/model.py,sha256=B9ASfPobKV7KYzH6jFCybKtUXtTuuCiDZDYTnHUXdik,7575 +peft/tuners/osf/__init__.py,sha256=4ZhEQYYtAIlRE0UVoJrUfDjg6WVcMo8gufHVV2zPpD0,321 +peft/tuners/osf/__pycache__/__init__.cpython-310.pyc,, +peft/tuners/osf/__pycache__/config.cpython-310.pyc,, +peft/tuners/osf/__pycache__/layer.cpython-310.pyc,, +peft/tuners/osf/__pycache__/model.cpython-310.pyc,, +peft/tuners/osf/__pycache__/utils.cpython-310.pyc,, +peft/tuners/osf/config.py,sha256=FbrUwemyqrQigmtoKP2yLOHVs5teB9SYYqhZdbi-sVI,3521 +peft/tuners/osf/layer.py,sha256=lbW_6NM_vIXKksLZjllHL2MIjtUtdYRZZPf7YQEkowU,11664 +peft/tuners/osf/model.py,sha256=wkfqsyujwXeqWPtU5QfwZ6zbwNXOJTlFRUU5Q3yIoLc,4680 +peft/tuners/osf/utils.py,sha256=Et23Uhwv74i3rF3Jli-KSVpj8b1lR9t4lEtqRIsaXmQ,5402 +peft/tuners/p_tuning/__init__.py,sha256=EtRO5mb2JSJk55PIDamQMHwwLmusvYksmcs1OiDOLHU,942 +peft/tuners/p_tuning/__pycache__/__init__.cpython-310.pyc,, +peft/tuners/p_tuning/__pycache__/config.cpython-310.pyc,, +peft/tuners/p_tuning/__pycache__/model.cpython-310.pyc,, +peft/tuners/p_tuning/config.py,sha256=MzgKKOPQ1uit5eDw5wN5TjkJHRnQ2mPXIzR8zIfV-ac,2142 +peft/tuners/p_tuning/model.py,sha256=rv2mbmPOArAefeqhJ09Oz7XNGaScWGRT1hgKlrfhfAw,5575 +peft/tuners/peanut/__init__.py,sha256=ol0Z8sIihUJsCXoae2TTyhNz10I5o2mohk853epkSqU,1011 +peft/tuners/peanut/__pycache__/__init__.cpython-310.pyc,, +peft/tuners/peanut/__pycache__/config.cpython-310.pyc,, +peft/tuners/peanut/__pycache__/layer.cpython-310.pyc,, +peft/tuners/peanut/__pycache__/model.cpython-310.pyc,, +peft/tuners/peanut/config.py,sha256=OLDwLehtTrf7B3kHWE0oj8588bmKeKJuWiIZsPJ1NxU,9019 +peft/tuners/peanut/layer.py,sha256=vP3FY2V4jSAKAxC74SUFGijT5vPE4xMNrJkbFX0Pyu8,9480 +peft/tuners/peanut/model.py,sha256=FOcyM4kv-jCh1Cxt_gvSdWGCOAI1yC85q59IGd9aaxc,3314 +peft/tuners/poly/__init__.py,sha256=tqQ06eCqWv5unMpmBYW9xtcUHiUa8z91h7tmSWVZWo4,883 +peft/tuners/poly/__pycache__/__init__.cpython-310.pyc,, +peft/tuners/poly/__pycache__/config.cpython-310.pyc,, +peft/tuners/poly/__pycache__/layer.cpython-310.pyc,, +peft/tuners/poly/__pycache__/model.cpython-310.pyc,, +peft/tuners/poly/__pycache__/router.cpython-310.pyc,, +peft/tuners/poly/config.py,sha256=p9hpa17p16OcLcui7_yQtuP2Eg0tvIoQeXlSlJsbnNI,4569 +peft/tuners/poly/layer.py,sha256=vy679pcyaHs-f7OjJRMUtd8xW98ZbBs-L4qliXt4spY,6664 +peft/tuners/poly/model.py,sha256=6ClkZBjyBEfxrlDlZZCb7AdnprI55A2gteHIPURHWK0,3535 +peft/tuners/poly/router.py,sha256=o0Q3h6yM9FxJWNGhwNOMqaNeuqbV2hcOxFxUDRumc5A,2784 +peft/tuners/prefix_tuning/__init__.py,sha256=iBQHtZgrv5FU_mz4RWT0IdDBfc5C-tX-qDYxnwRL8Wc,868 +peft/tuners/prefix_tuning/__pycache__/__init__.cpython-310.pyc,, +peft/tuners/prefix_tuning/__pycache__/config.cpython-310.pyc,, +peft/tuners/prefix_tuning/__pycache__/model.cpython-310.pyc,, +peft/tuners/prefix_tuning/config.py,sha256=akqzCGz3EyABR08ugpe8Hr-kqR_AK9tL6DW-rm2m2a8,1922 +peft/tuners/prefix_tuning/model.py,sha256=n9Cp8IH8A8oEX6CrXV-cbUw_LYaIWR1trW90y10tNtA,4502 +peft/tuners/prompt_tuning/__init__.py,sha256=CeZkm_qTIucS_KE60RPGdf_ecUMWtXvtWLupMQVAdTw,912 +peft/tuners/prompt_tuning/__pycache__/__init__.cpython-310.pyc,, +peft/tuners/prompt_tuning/__pycache__/config.cpython-310.pyc,, +peft/tuners/prompt_tuning/__pycache__/model.cpython-310.pyc,, +peft/tuners/prompt_tuning/config.py,sha256=y5tR7Lblwl-Z65VIW5DIzsPa3XXAocsYi-Onh5TTyXc,3843 +peft/tuners/prompt_tuning/model.py,sha256=43GOyOJIJvYS8BaJOISruq15KG-JXOpnmiLe0pmmlkQ,4650 +peft/tuners/psoft/__init__.py,sha256=VHPkJM65CaH_D0NYbBO6Hwd33CnBw0U5a2gdGQl5GQ0,909 +peft/tuners/psoft/__pycache__/__init__.cpython-310.pyc,, +peft/tuners/psoft/__pycache__/config.cpython-310.pyc,, +peft/tuners/psoft/__pycache__/layer.cpython-310.pyc,, +peft/tuners/psoft/__pycache__/model.cpython-310.pyc,, +peft/tuners/psoft/config.py,sha256=ChLD6ie-Jlb77owFVTTiVenfCL-jrzqMX0SQezl8iFI,17436 +peft/tuners/psoft/layer.py,sha256=Ruo5X5Digdq23dGwW5_Bs-qG9sUFoYxjwvv_UgVv6FQ,17629 +peft/tuners/psoft/model.py,sha256=Y8aPh0VjcEN-musneMq0pwYczKu9xWNCN1cmfQUOemw,3022 +peft/tuners/pvera/__init__.py,sha256=4A0k0kUsz1yzMPL_rDQbgCcak6DhSNXzEw_QgftVI24,918 +peft/tuners/pvera/__pycache__/__init__.cpython-310.pyc,, +peft/tuners/pvera/__pycache__/bnb.cpython-310.pyc,, +peft/tuners/pvera/__pycache__/config.cpython-310.pyc,, +peft/tuners/pvera/__pycache__/layer.cpython-310.pyc,, +peft/tuners/pvera/__pycache__/model.cpython-310.pyc,, +peft/tuners/pvera/bnb.py,sha256=fZu_tnH37J_TgNlj1LrIY1hijWgSM4eSR0uFYBkPukY,17191 +peft/tuners/pvera/config.py,sha256=tX6I-gY100Zk0myDLNZtK-RcBLI8nbA5FlkG2qkPfBc,10614 +peft/tuners/pvera/layer.py,sha256=oFZSM6VpEeYaxIBGmtynjqdve31EMHSYHRtLGRTZ6-E,13214 +peft/tuners/pvera/model.py,sha256=ux8R1Rz2VL8Hh-u4EYdv3M5ag_MOVllMH9sSYXNlscs,11042 +peft/tuners/randlora/__init__.py,sha256=fvo7F6284VmDqCHXcUF5py2vK5bfRwiJ3x3o6eImI0M,1353 +peft/tuners/randlora/__pycache__/__init__.cpython-310.pyc,, +peft/tuners/randlora/__pycache__/bnb.cpython-310.pyc,, +peft/tuners/randlora/__pycache__/config.cpython-310.pyc,, +peft/tuners/randlora/__pycache__/layer.cpython-310.pyc,, +peft/tuners/randlora/__pycache__/model.cpython-310.pyc,, +peft/tuners/randlora/bnb.py,sha256=EtXm7pwynvAANxiAjCBRZmTwvS2zGSXjVOPxzqg8b_U,19585 +peft/tuners/randlora/config.py,sha256=MLFBjIANFmW9tUt7ne4iUZQd_OnseHH9zR_-V1Uya_Q,9945 +peft/tuners/randlora/layer.py,sha256=gl3TLQN6l-X35SGlYrqKO9rM9CU0ZAQGkD-0DjhnqB0,15501 +peft/tuners/randlora/model.py,sha256=mgPEQXvDHRe8eitCpmj1pqyRzQvBBJ0f2BOlWbr1b9E,15186 +peft/tuners/road/__init__.py,sha256=MqIF5US_kNuJkBiuigcHfrY5xbQYY0w-XtZ8W82SRCc,1458 +peft/tuners/road/__pycache__/__init__.cpython-310.pyc,, +peft/tuners/road/__pycache__/bnb.cpython-310.pyc,, +peft/tuners/road/__pycache__/config.cpython-310.pyc,, +peft/tuners/road/__pycache__/layer.cpython-310.pyc,, +peft/tuners/road/__pycache__/model.cpython-310.pyc,, +peft/tuners/road/bnb.py,sha256=XefUL7RL_IQvIG5ZR_JBiODF9eidRLkaCvPhBRKe8Gg,17669 +peft/tuners/road/config.py,sha256=thy3zcxZAWjve-B-qrQ9zyJYvDI2WGr8x1voSTiz4ng,6817 +peft/tuners/road/layer.py,sha256=pHwlRGMGDHD2AGNCADbnD0nXn7PQSPim066yizXEY_I,17575 +peft/tuners/road/model.py,sha256=csO4FWozf7nwzyjariiev347AkQxxYcYzPJg36nBCxI,6090 +peft/tuners/shira/__init__.py,sha256=128Mt8OZfVNlJyHI-9mgHCuIk6mg6PP0oop-HTWAjZQ,942 +peft/tuners/shira/__pycache__/__init__.cpython-310.pyc,, +peft/tuners/shira/__pycache__/config.cpython-310.pyc,, +peft/tuners/shira/__pycache__/layer.cpython-310.pyc,, +peft/tuners/shira/__pycache__/mask_functions.cpython-310.pyc,, +peft/tuners/shira/__pycache__/model.cpython-310.pyc,, +peft/tuners/shira/config.py,sha256=XEPT_LLADulAvim1HVv3P4z3i0A0VA1z00-3nav6fwY,6598 +peft/tuners/shira/layer.py,sha256=qi13GbIecwrly4oyqRDffuYqG0HdGG5jK3v9S5SE45o,9402 +peft/tuners/shira/mask_functions.py,sha256=t9QCZFVICYPkSdU5jtk4nV8jgnlTT71WpsR_yYzCKwg,2985 +peft/tuners/shira/model.py,sha256=2aTGNseKRNXq-6qUcS2JFBCbziNnne0sZ8hax1IctOM,4668 +peft/tuners/tinylora/__init__.py,sha256=s8jfMNcq8crb4DiM0ZtFltk0RgYybeGxOqjNH7vsRbU,964 +peft/tuners/tinylora/__pycache__/__init__.cpython-310.pyc,, +peft/tuners/tinylora/__pycache__/config.cpython-310.pyc,, +peft/tuners/tinylora/__pycache__/layer.cpython-310.pyc,, +peft/tuners/tinylora/__pycache__/model.cpython-310.pyc,, +peft/tuners/tinylora/config.py,sha256=Z1bOqUTAHRdspW8sLEi7MjFrkwW8iOFT1L-Etg9TYUw,10135 +peft/tuners/tinylora/layer.py,sha256=wQFPMVq02L5hpVx1Ro5wAySopAzxyGEiE3v4nEnWg1U,24517 +peft/tuners/tinylora/model.py,sha256=TMVlts_3sYyhYVHBwvyo8eIjKmDibSNGJ_uF8EGm2Gw,13046 +peft/tuners/trainable_tokens/__init__.py,sha256=necElnvofPCAK6LNgN01FswZ2h-Zvde8W59bxULEtoU,1026 +peft/tuners/trainable_tokens/__pycache__/__init__.cpython-310.pyc,, +peft/tuners/trainable_tokens/__pycache__/config.cpython-310.pyc,, +peft/tuners/trainable_tokens/__pycache__/layer.cpython-310.pyc,, +peft/tuners/trainable_tokens/__pycache__/model.cpython-310.pyc,, +peft/tuners/trainable_tokens/config.py,sha256=G35U_OvYJGpmc347C-CDMyVkd7TKCEiN4xtWAHj4Uis,4377 +peft/tuners/trainable_tokens/layer.py,sha256=vmDMX1AaVjM5eoB1rHtEXXybOo7KeWP1qfmt-2wRlBA,11903 +peft/tuners/trainable_tokens/model.py,sha256=0twSNWRufwGrIq4RWCLtUQmIwwBUFyr908Q53a8SK3o,6524 +peft/tuners/tuners_utils.py,sha256=0UcZ1YE-VAlBH5JKUtNPlz0ZLKAAEHv0zM1f6uZBeh4,103252 +peft/tuners/vblora/__init__.py,sha256=8vps9lYLOY5u82MTjhkv_6bXvkjeRPOfPsXc0lQYXn8,901 +peft/tuners/vblora/__pycache__/__init__.cpython-310.pyc,, +peft/tuners/vblora/__pycache__/config.cpython-310.pyc,, +peft/tuners/vblora/__pycache__/layer.cpython-310.pyc,, +peft/tuners/vblora/__pycache__/model.cpython-310.pyc,, +peft/tuners/vblora/config.py,sha256=uRZcB4eAzW2gPorupyDyNGJRG8JmK6J-UkVmqhBEsfg,10572 +peft/tuners/vblora/layer.py,sha256=_DoGQKMj0T3_YDIYGSTuW4EAA8qsQXFboDKfW5VY67A,11212 +peft/tuners/vblora/model.py,sha256=DbgHLA-cAZkR22yI-k6l9c2uKaPt37m1p44PVhTdXVo,8452 +peft/tuners/vera/__init__.py,sha256=Wa_lRLZxdDSIbq7twa6hfh36BF5X7y5e6i4h4GSxfug,1320 +peft/tuners/vera/__pycache__/__init__.cpython-310.pyc,, +peft/tuners/vera/__pycache__/bnb.cpython-310.pyc,, +peft/tuners/vera/__pycache__/config.cpython-310.pyc,, +peft/tuners/vera/__pycache__/layer.cpython-310.pyc,, +peft/tuners/vera/__pycache__/model.cpython-310.pyc,, +peft/tuners/vera/bnb.py,sha256=dcCSOX9mesyuMmQN99YbygsvxJEsH_PypioC6ABe_K0,16373 +peft/tuners/vera/config.py,sha256=5wB8jf5ydlpD0m5CX5kuTnfvgxeiY2qMUuADpVpc9p8,8093 +peft/tuners/vera/layer.py,sha256=3FNHZqZJugXulcGAuNFSBFPWZm0KXQAHRFw-3cv5ADU,12323 +peft/tuners/vera/model.py,sha256=rHE7ggyT4vG9lpxLgfeZ2lS3LgS7fwTteFk3SarquXU,11571 +peft/tuners/waveft/__init__.py,sha256=L4ICvcoyQ7V-CTCT6_1Bpc0Rosas3vcR0oM9DC9Kr18,913 +peft/tuners/waveft/__pycache__/__init__.cpython-310.pyc,, +peft/tuners/waveft/__pycache__/config.cpython-310.pyc,, +peft/tuners/waveft/__pycache__/constants.cpython-310.pyc,, +peft/tuners/waveft/__pycache__/layer.cpython-310.pyc,, +peft/tuners/waveft/__pycache__/model.cpython-310.pyc,, +peft/tuners/waveft/__pycache__/wavelet.cpython-310.pyc,, +peft/tuners/waveft/__pycache__/waverec2d.cpython-310.pyc,, +peft/tuners/waveft/config.py,sha256=MM3DwA5uNzzW7Mw0gFEAtgJEoAuoGnrnvlDARckDf6o,13772 +peft/tuners/waveft/constants.py,sha256=YaEdHWLKHIY2w0zzHhENpIPkLwJTW3b2ucCprsAdT-A,2676 +peft/tuners/waveft/layer.py,sha256=ejvkUyqpQ_dyxYcgIIcdXj7NpMsYugUWAajAXrhq1es,13221 +peft/tuners/waveft/model.py,sha256=jXFpHdidI9wpQ47j7voPu7TGk-_ABJPBlQOoaPRwy9o,8423 +peft/tuners/waveft/wavelet.py,sha256=dEFFnG30TfSNckNTkamJc4T9aTiwUL-mPufxel8XheI,25219 +peft/tuners/waveft/waverec2d.py,sha256=rUycRzi96eTSJKbJ0nkIuP5BXK0h8UqLmZytsuzXEfs,11666 +peft/tuners/xlora/__init__.py,sha256=N7_cYjTq-KIaNMrHDksLz0vMczgKx9y6_3byEhDoxgQ,830 +peft/tuners/xlora/__pycache__/__init__.cpython-310.pyc,, +peft/tuners/xlora/__pycache__/classifier.cpython-310.pyc,, +peft/tuners/xlora/__pycache__/config.cpython-310.pyc,, +peft/tuners/xlora/__pycache__/layer.cpython-310.pyc,, +peft/tuners/xlora/__pycache__/model.cpython-310.pyc,, +peft/tuners/xlora/classifier.py,sha256=D2oOfxWLdqh2kluj9shfiUoJv1TdSM70jsZDkc7uJy0,7386 +peft/tuners/xlora/config.py,sha256=Erf64V-fe2aIQIBZwtYuc9JWjIepb-78o6IqVJMwzy8,4633 +peft/tuners/xlora/layer.py,sha256=oVfGXGBpfIN9ge_dAbBogbIkg2KEupyi455aKsyodNY,9760 +peft/tuners/xlora/model.py,sha256=GL33k2ZvVj4uJ2xfe1gLjhd2pheGO2QM52BMl-lTlkg,21073 +peft/utils/__init__.py,sha256=R7aOB9qo5-83mMeWQu-7-7mgnwwXd-d8N7h7Y2u8Gbc,6076 +peft/utils/__pycache__/__init__.cpython-310.pyc,, +peft/utils/__pycache__/constants.cpython-310.pyc,, +peft/utils/__pycache__/hotswap.cpython-310.pyc,, +peft/utils/__pycache__/incremental_pca.cpython-310.pyc,, +peft/utils/__pycache__/integrations.cpython-310.pyc,, +peft/utils/__pycache__/loftq_utils.cpython-310.pyc,, +peft/utils/__pycache__/merge_utils.cpython-310.pyc,, +peft/utils/__pycache__/other.cpython-310.pyc,, +peft/utils/__pycache__/peft_types.cpython-310.pyc,, +peft/utils/__pycache__/save_and_load.cpython-310.pyc,, +peft/utils/__pycache__/transformers_weight_conversion.cpython-310.pyc,, +peft/utils/__pycache__/warning.cpython-310.pyc,, +peft/utils/constants.py,sha256=2CHo1O__qC4hpO-c-WIeVrudn0XlKC8CGsnpm-YY1OY,16849 +peft/utils/hotswap.py,sha256=nZGVmQtzpab-R740QK2h8AftyzA4Gcgxk3FszXBhL5Q,26543 +peft/utils/incremental_pca.py,sha256=C6uNBqOfbc4eR_i2HXLjk8sxsqQ_bxh42pGXKRt_Xfs,14026 +peft/utils/integrations.py,sha256=orIwQXa3TjoZsWrITZ2-HloM3LrU580rDu57XDSAIc0,11235 +peft/utils/loftq_utils.py,sha256=4u7yzOlsS6CHKbwHSFOKUFVYYqyp7Z6DSDJsK_HFUeQ,18529 +peft/utils/merge_utils.py,sha256=vImRUzIi1VNERn6ypls-YAHTZqsxEI26y-MRY4pQZns,9893 +peft/utils/other.py,sha256=tqh0Cu6YHru6Mde_t0GplQkq0tpipECY1JSrpORqfpU,78531 +peft/utils/peft_types.py,sha256=UIcK4C35IwNebQkIMqIGtL_a14cMhar47DVZ0GShyPs,5734 +peft/utils/save_and_load.py,sha256=EYDc33SAo8iCC2P-LRud6LlX-S3kaI47ov6sTWri_lM,50803 +peft/utils/transformers_weight_conversion.py,sha256=EewzYTBMbXMEsD9DKWxARLXparUgUV_9ABXGVLOJgeE,23911 +peft/utils/warning.py,sha256=IPHYPCKbhGouQY9tcxnoAcLAbVFXoZdf-ic-kpiVIvY,660 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft-0.19.1.dist-info/WHEEL b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft-0.19.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..370ec5f1aa3524bfd31a19fd21e907335f48a7f6 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft-0.19.1.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (78.1.1) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft-0.19.1.dist-info/top_level.txt b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft-0.19.1.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..dc89ba063e639dfa24fd7f53340bc368adbebb7a --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft-0.19.1.dist-info/top_level.txt @@ -0,0 +1 @@ +peft diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/functional.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/functional.py new file mode 100644 index 0000000000000000000000000000000000000000..60df690cafe1e9a3b5c8ff09d550f82110afe593 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/functional.py @@ -0,0 +1,34 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 are useful for integration with non-PeftModel models, e.g. transformers or diffusers. + +The functions provided here can be considered "public API" of PEFT and hence are safe to be used by packages that +provide PEFT integrations. +""" + +from peft.mapping import inject_adapter_in_model +from peft.tuners.tuners_utils import cast_adapter_dtype, delete_adapter, set_adapter, set_requires_grad +from peft.utils import get_peft_model_state_dict, set_peft_model_state_dict + + +__all__ = [ + "cast_adapter_dtype", + "delete_adapter", + "get_peft_model_state_dict", + "inject_adapter_in_model", + "set_adapter", + "set_peft_model_state_dict", + "set_requires_grad", +] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/mixed_model.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/mixed_model.py new file mode 100644 index 0000000000000000000000000000000000000000..26409a6ed77f645b0296c44661b67ea0fdf159d2 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/mixed_model.py @@ -0,0 +1,473 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 __future__ import annotations + +import os +from contextlib import contextmanager +from typing import Any, Optional, Union + +import torch +from accelerate.hooks import remove_hook_from_submodules +from torch import nn +from transformers.utils import PushToHubMixin + +from peft.utils.constants import DUMMY_MODEL_CONFIG + +from .config import PeftConfig +from .peft_model import PeftModel +from .tuners import MixedModel +from .utils import _set_adapter, _set_trainable + + +def _prepare_model_for_gradient_checkpointing(model: nn.Module) -> None: + r""" + Prepares the model for gradient checkpointing if necessary + """ + # Note: same as PeftModel._prepare_model_for_gradient_checkpointing + if not getattr(model, "is_gradient_checkpointing", True): + return model + + if not ( + getattr(model, "is_loaded_in_8bit", False) + or getattr(model, "is_loaded_in_4bit", False) + or getattr(model, "is_quantized", False) + ): + if hasattr(model, "enable_input_require_grads"): + model.enable_input_require_grads() + elif hasattr(model, "get_input_embeddings"): + + def make_inputs_require_grad(module, input, output): + output.requires_grad_(True) + + model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) + + +def _check_config_compatible(peft_config: PeftConfig) -> None: + from .tuners.mixed import COMPATIBLE_TUNER_TYPES + + if peft_config.peft_type not in COMPATIBLE_TUNER_TYPES: + raise ValueError( + f"The provided `peft_type` '{peft_config.peft_type.value}' is not compatible with the `PeftMixedModel`. " + f"Compatible types are: {COMPATIBLE_TUNER_TYPES}" + ) + + +class PeftMixedModel(PushToHubMixin, torch.nn.Module): + """ + PeftMixedModel for loading mixing different types of adapters for inference. + + This class does not support loading/saving, and it shouldn't usually be initialized directly. Instead, use + `get_peft_model` with the argument `mixed=True`. + + > [!TIP] > Read the [Mixed adapter types](https://huggingface.co/docs/peft/en/developer_guides/mixed_models) guide + to learn > more about using different adapter types. + + Example: + + ```py + >>> base_model = ... # load the base model, e.g. from transformers + >>> peft_model = PeftMixedModel.from_pretrained(base_model, path_to_adapter1, "adapter1").eval() + >>> peft_model.load_adapter(path_to_adapter2, "adapter2") + >>> peft_model.set_adapter(["adapter1", "adapter2"]) # activate both adapters + >>> peft_model(data) # forward pass using both adapters + ``` + + Args: + model (`torch.nn.Module`): + The model to be tuned. + config (`PeftConfig`): + The config of the model to be tuned. The adapter type must be compatible. + adapter_name (`str`, `optional`, defaults to `"default"`): + The name of the first adapter. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device. Useful to speed up the loading process. + """ + + def __init__(self, model: nn.Module, peft_config: PeftConfig, adapter_name: str = "default") -> None: + super().__init__() + _check_config_compatible(peft_config) + _prepare_model_for_gradient_checkpointing(model) + self.modules_to_save = None + self.base_model = MixedModel(model, {adapter_name: peft_config}, adapter_name) + self.set_modules_to_save(peft_config, adapter_name) + + self.config = getattr(model, "config", DUMMY_MODEL_CONFIG) + + # the `pretraining_tp` is set for some models to simulate Tensor Parallelism during inference to avoid + # numerical differences, https://github.com/pytorch/pytorch/issues/76232 - to avoid any unexpected + # behavior we disable that in this line. + if hasattr(self.base_model, "config") and hasattr(self.base_model.config, "pretraining_tp"): + self.base_model.config.pretraining_tp = 1 + + @property + def peft_config(self) -> dict[str, PeftConfig]: + return self.base_model.peft_config + + @property + def active_adapter(self) -> str: + return self.base_model.active_adapter + + @property + def active_adapters(self) -> list[str]: + return self.base_model.active_adapters + + def get_nb_trainable_parameters(self): + r""" + Returns the number of trainable parameters and number of all parameters in the model. + """ + # note: same as PeftModel.get_nb_trainable_parameters + trainable_params = 0 + all_param = 0 + for _, param in self.named_parameters(): + num_params = param.numel() + # if using DS Zero 3 and the weights are initialized empty + if num_params == 0 and hasattr(param, "ds_numel"): + num_params = param.ds_numel + + # Due to the design of 4bit linear layers from bitsandbytes + # one needs to multiply the number of parameters by 2 to get + # the correct number of parameters + if param.__class__.__name__ == "Params4bit": + num_params = num_params * 2 + + all_param += num_params + if param.requires_grad: + trainable_params += num_params + + return trainable_params, all_param + + def print_trainable_parameters(self): + """ + Prints the number of trainable parameters in the model. + + Note: print_trainable_parameters() uses get_nb_trainable_parameters() which is different from + num_parameters(only_trainable=True) from huggingface/transformers. get_nb_trainable_parameters() returns + (trainable parameters, all parameters) of the Peft Model which includes modified backbone transformer model. + For techniques like LoRA, the backbone transformer model is modified in place with LoRA modules. However, for + prompt tuning, the backbone transformer model is unmodified. num_parameters(only_trainable=True) returns number + of trainable parameters of the backbone transformer model which can be different. + """ + # note: same as PeftModel.print_trainable_parameters + trainable_params, all_param = self.get_nb_trainable_parameters() + + print( + f"trainable params: {trainable_params:,d} || " + f"all params: {all_param:,d} || " + f"trainable%: {100 * trainable_params / all_param:.4f}" + ) + + def __getattr__(self, name: str): + """Forward missing attributes to the wrapped module.""" + try: + return super().__getattr__(name) # defer to nn.Module's logic + except AttributeError: + if name == "base_model": # see #1892: prevent infinite recursion if class is not initialized + raise + return getattr(self.base_model, name) + + def forward(self, *args: Any, **kwargs: Any): + """ + Forward pass of the model. + """ + return self.base_model(*args, **kwargs) + + def generate(self, *args: Any, **kwargs: Any): + """ + Generate output. + """ + return self.base_model.generate(*args, **kwargs) + + @contextmanager + def disable_adapter(self): + """ + Disables the adapter module. + """ + try: + self.base_model.disable_adapter_layers() + yield + finally: + self.base_model.enable_adapter_layers() + + def add_adapter( + self, + adapter_name: str, + peft_config: PeftConfig, + low_cpu_mem_usage: bool = False, + autocast_adapter_dtype: bool = True, + ) -> None: + """ + Add an adapter to the model based on the passed configuration. + + This adapter is not trained. To load a trained adapter, check out [`PeftModel.load_adapter`]. + + The name for the new adapter should be unique. + + The new adapter is not automatically set as the active adapter. Use [`PeftModel.set_adapter`] to set the active + adapter. + + Args: + adapter_name (`str`): + The name of the adapter to be added. + peft_config ([`PeftConfig`]): + The configuration of the adapter to be added. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device. Useful to speed up the process when loading saved + adapters. + + > [!TIP] > Don't use `low_cpu_mem_usage=True` when creating a new PEFT adapter for training (training + is untested > and discouraged for PeftMixedModel in general). + autocast_adapter_dtype (`bool`, *optional*, defaults to `True`): + Whether to autocast the adapter dtype. Defaults to `True`. Right now, this will only cast adapter + weights using float16 and bfloat16 to float32, as this is typically required for stable training, and + only affect select PEFT tuners. If set to `False`, the dtypes will stay the same as those of the + corresponding layer. + """ + _check_config_compatible(peft_config) + + try: + self.peft_config[adapter_name] = peft_config + self.base_model.inject_adapter(self, adapter_name, low_cpu_mem_usage=low_cpu_mem_usage) + except Exception: # something went wrong, roll back + if adapter_name in self.peft_config: + del self.peft_config[adapter_name] + raise + + self.base_model._cast_adapter_dtype(adapter_name=adapter_name, autocast_adapter_dtype=autocast_adapter_dtype) + + self.set_modules_to_save(peft_config, adapter_name) + + def set_modules_to_save(self, peft_config: PeftConfig, adapter_name: str) -> None: + if (modules_to_save := getattr(peft_config, "modules_to_save", None)) is None: + return + + if self.modules_to_save is None: + self.modules_to_save = set(modules_to_save) + else: + self.modules_to_save.update(modules_to_save) + _set_trainable( + self, + adapter_name, + module_names=getattr(peft_config, "modules_to_save", None), + inference_mode=peft_config.inference_mode, + ) + + def set_adapter(self, adapter_name: Union[str, list[str]], inference_mode: bool = False) -> None: + """ + Sets the active adapter(s) for the model. + + Note that the order in which the adapters are applied during the forward pass may not be the same as the order + in which they are passed to this function. Instead, the order during the forward pass is determined by the + order in which the adapters were loaded into the model. The active adapters only determine which adapters are + active during the forward pass, but not the order in which they are applied. + + Additionally, this function will set the specified adapter to trainable (i.e., requires_grad=True) unless + inference_mode is True. + + Args: + adapter_name (str, list[str]): + The name(s) of the adapter(s) to set as active + inference_mode (bool, optional): + Whether the activated adapter should be frozen (i.e. `requires_grad=False`). Default is False. + """ + if isinstance(adapter_name, str): + adapter_name = [adapter_name] + + mismatched = set(adapter_name) - set(self.peft_config.keys()) + if mismatched: + raise ValueError( + f"Adapter(s) {sorted(mismatched)} not found, available adapters: {sorted(self.peft_config.keys())}" + ) + + self.base_model.set_adapter(adapter_name, inference_mode=inference_mode) + _set_adapter(self, adapter_name, inference_mode=inference_mode) + + def delete_adapter(self, adapter_name: Union[str, list[str]]) -> None: + if isinstance(adapter_name, str): + adapter_name = [adapter_name] + + mismatched = set(adapter_name) - set(self.peft_config.keys()) + if mismatched: + raise ValueError( + f"Adapter(s) {sorted(mismatched)} not found, available adapters: {sorted(self.peft_config.keys())}" + ) + + self.base_model.delete_adapter(adapter_name) + + def merge_and_unload(self, *args: Any, **kwargs: Any): + r""" + This method merges the adapter layers into the base model. This is needed if someone wants to use the base + model as a standalone model. + + Args: + progressbar (`bool`): + whether to show a progressbar indicating the unload and merge process + safe_merge (`bool`): + whether to activate the safe merging check to check if there is any potential Nan in the adapter + weights + adapter_names (`List[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults + to `None`. + """ + return self.base_model.merge_and_unload(*args, **kwargs) + + def unload(self, *args: Any, **kwargs: Any): + """ + Gets back the base model by removing all the adapter modules without merging. This gives back the original base + model. + """ + return self.base_model.unload(*args, **kwargs) + + def get_layer_status(self): + raise TypeError(f"get_layer_status is not supported for {self.__class__.__name__}.") + + def get_model_status(self): + raise TypeError(f"get_model_status is not supported for {self.__class__.__name__}.") + + @classmethod + def _split_kwargs(cls, kwargs: dict[str, Any]): + return PeftModel._split_kwargs(kwargs) + + def _check_new_adapter_config(self, peft_config: PeftConfig, is_trainable: bool) -> None: + return PeftModel._check_new_adapter_config(self, peft_config, is_trainable=is_trainable) + + def load_adapter(self, model_id: str, adapter_name: str, *args: Any, **kwargs: Any): + """ + Load a trained adapter into the model. + + The name for the new adapter should be unique. + + The new adapter is not automatically set as the active adapter. Use [`PeftModel.set_adapter`] to set the active + adapter. + + Args: + adapter_name (`str`): + The name of the adapter to be added. + peft_config ([`PeftConfig`]): + The configuration of the adapter to be added. + is_trainable (`bool`, *optional*, defaults to `False`): + Whether the adapter should be trainable or not. If `False`, the adapter will be frozen and can only be + used for inference. + torch_device (`str`, *optional*, defaults to None): + The device to load the adapter on. If `None`, the device will be inferred. + autocast_adapter_dtype (`bool`, *optional*, defaults to `True`): + Whether to autocast the adapter dtype. Defaults to `True`. Right now, this will only cast adapter + weights using float16 and bfloat16 to float32, as this is typically required for stable training, and + only affect select PEFT tuners. + ephemeral_gpu_offload (`bool`, *optional*, defaults to `False`): + Whether to use ephemeral GPU offloading for partially loaded modules. Defaults to `False`. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device before loading the saved weights. Useful to speed up the + process. + kwargs: (`optional`): + Additional arguments to modify the way the adapter is loaded, e.g. the token for Hugging Face Hub. + """ + # the low_cpu_mem_usage option is handled through kwargs + output = PeftModel.load_adapter(self, model_id, adapter_name, *args, **kwargs) + # TODO: not quite clear why this is necessary but tests fail without it + self.set_adapter(self.active_adapters) + return output + + def create_or_update_model_card(self, output_dir: str): + raise NotImplementedError(f"Model card creation is not supported for {self.__class__.__name__} (yet).") + + def save_pretrained( + self, + save_directory: str, + safe_serialization: bool = False, + selected_adapters: Optional[list[str]] = None, + **kwargs: Any, + ): + raise NotImplementedError(f"Saving is not supported for {self.__class__.__name__} (yet).") + + @classmethod + def from_pretrained( + cls, + model: nn.Module, + model_id: str | os.PathLike, + adapter_name: str = "default", + is_trainable: bool = False, + config: Optional[PeftConfig] = None, + **kwargs: Any, + ): + r""" + Instantiate a PEFT mixed model from a pretrained model and loaded PEFT weights. + + Note that the passed `model` may be modified inplace. + + Args: + model (`nn.Module`): + The model to be adapted. + model_id (`str` or `os.PathLike`): + The name of the PEFT configuration to use. Can be either: + - A string, the `model id` of a PEFT configuration hosted inside a model repo on the Hugging Face + Hub. + - A path to a directory containing a PEFT configuration file saved using the `save_pretrained` + method (`./my_peft_config_directory/`). + adapter_name (`str`, *optional*, defaults to `"default"`): + The name of the adapter to be loaded. This is useful for loading multiple adapters. + is_trainable (`bool`, *optional*, defaults to `False`): + Whether the adapter should be trainable or not. If `False`, the adapter will be frozen and use for + inference + config ([`~peft.PeftConfig`], *optional*): + The configuration object to use instead of an automatically loaded configuration. This configuration + object is mutually exclusive with `model_id` and `kwargs`. This is useful when configuration is already + loaded before calling `from_pretrained`. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device before loading the saved weights. Useful to speed up the + process. + kwargs: (`optional`): + Additional keyword arguments passed along to the specific PEFT configuration class. + """ + # note: adapted from PeftModel.from_pretrained + from .mapping import PEFT_TYPE_TO_CONFIG_MAPPING, PEFT_TYPE_TO_MIXED_MODEL_MAPPING + + # load the config + if config is None: + hf_kwargs = { + "subfolder": kwargs.get("subfolder", None), + "revision": kwargs.get("revision", None), + "cache_dir": kwargs.get("cache_dir", None), + "token": kwargs.get("token", None), + } + if use_auth_token := kwargs.get("use_auth_token", None): + hf_kwargs["use_auth_token"] = use_auth_token + config = PEFT_TYPE_TO_CONFIG_MAPPING[PeftConfig._get_peft_type(model_id, **hf_kwargs)].from_pretrained( + model_id, **kwargs + ) + elif isinstance(config, PeftConfig): + config.inference_mode = not is_trainable + else: + raise ValueError(f"The input config must be a PeftConfig, got {config.__class__}") + + # note: this is different from PeftModel.from_pretrained + if config.peft_type not in PEFT_TYPE_TO_MIXED_MODEL_MAPPING: + raise ValueError(f"Adapter of type {config.peft_type} is not supported for mixed models.") + + if (getattr(model, "hf_device_map", None) is not None) and len( + set(model.hf_device_map.values()).intersection({"cpu", "disk"}) + ) > 0: + remove_hook_from_submodules(model) + + if config.is_prompt_learning and is_trainable: + # note: should not be possible to reach, but just in case + raise ValueError("Cannot set a prompt learning adapter to trainable when loading pretrained adapter.") + else: + config.inference_mode = not is_trainable + + # note: this is different from PeftModel.from_pretrained, we always return a PeftMixedModel + model = cls(model, config, adapter_name) + # the low_cpu_mem_usage option is handled through kwargs + model.load_adapter(model_id, adapter_name, is_trainable=is_trainable, **kwargs) + return model diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/py.typed b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pip-23.0.1.dist-info/INSTALLER b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pip-23.0.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pip-23.0.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pip-23.0.1.dist-info/LICENSE.txt b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pip-23.0.1.dist-info/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..8e7b65eaf628360e6f32f4140fcdd7ec7c2b7077 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pip-23.0.1.dist-info/LICENSE.txt @@ -0,0 +1,20 @@ +Copyright (c) 2008-present The pip developers (see AUTHORS.txt file) + +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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pip-23.0.1.dist-info/METADATA b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pip-23.0.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..984f9ad3f984053e3fc51062d02a866d5d6b813b --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pip-23.0.1.dist-info/METADATA @@ -0,0 +1,88 @@ +Metadata-Version: 2.1 +Name: pip +Version: 23.0.1 +Summary: The PyPA recommended tool for installing Python packages. +Home-page: https://pip.pypa.io/ +Author: The pip developers +Author-email: distutils-sig@python.org +License: MIT +Project-URL: Documentation, https://pip.pypa.io +Project-URL: Source, https://github.com/pypa/pip +Project-URL: Changelog, https://pip.pypa.io/en/stable/news/ +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Topic :: Software Development :: Build Tools +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +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 :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Requires-Python: >=3.7 +License-File: LICENSE.txt + +pip - The Python Package Installer +================================== + +.. image:: https://img.shields.io/pypi/v/pip.svg + :target: https://pypi.org/project/pip/ + +.. image:: https://readthedocs.org/projects/pip/badge/?version=latest + :target: https://pip.pypa.io/en/latest + +pip is the `package installer`_ for Python. You can use pip to install packages from the `Python Package Index`_ and other indexes. + +Please take a look at our documentation for how to install and use pip: + +* `Installation`_ +* `Usage`_ + +We release updates regularly, with a new version every 3 months. Find more details in our documentation: + +* `Release notes`_ +* `Release process`_ + +In pip 20.3, we've `made a big improvement to the heart of pip`_; `learn more`_. We want your input, so `sign up for our user experience research studies`_ to help us do it right. + +**Note**: pip 21.0, in January 2021, removed Python 2 support, per pip's `Python 2 support policy`_. Please migrate to Python 3. + +If you find bugs, need help, or want to talk to the developers, please use our mailing lists or chat rooms: + +* `Issue tracking`_ +* `Discourse channel`_ +* `User IRC`_ + +If you want to get involved head over to GitHub to get the source code, look at our development documentation and feel free to jump on the developer mailing lists and chat rooms: + +* `GitHub page`_ +* `Development documentation`_ +* `Development IRC`_ + +Code of Conduct +--------------- + +Everyone interacting in the pip project's codebases, issue trackers, chat +rooms, and mailing lists is expected to follow the `PSF Code of Conduct`_. + +.. _package installer: https://packaging.python.org/guides/tool-recommendations/ +.. _Python Package Index: https://pypi.org +.. _Installation: https://pip.pypa.io/en/stable/installation/ +.. _Usage: https://pip.pypa.io/en/stable/ +.. _Release notes: https://pip.pypa.io/en/stable/news.html +.. _Release process: https://pip.pypa.io/en/latest/development/release-process/ +.. _GitHub page: https://github.com/pypa/pip +.. _Development documentation: https://pip.pypa.io/en/latest/development +.. _made a big improvement to the heart of pip: https://pyfound.blogspot.com/2020/11/pip-20-3-new-resolver.html +.. _learn more: https://pip.pypa.io/en/latest/user_guide/#changes-to-the-pip-dependency-resolver-in-20-3-2020 +.. _sign up for our user experience research studies: https://pyfound.blogspot.com/2020/03/new-pip-resolver-to-roll-out-this-year.html +.. _Python 2 support policy: https://pip.pypa.io/en/latest/development/release-process/#python-2-support +.. _Issue tracking: https://github.com/pypa/pip/issues +.. _Discourse channel: https://discuss.python.org/c/packaging +.. _User IRC: https://kiwiirc.com/nextclient/#ircs://irc.libera.chat:+6697/pypa +.. _Development IRC: https://kiwiirc.com/nextclient/#ircs://irc.libera.chat:+6697/pypa-dev +.. _PSF Code of Conduct: https://github.com/pypa/.github/blob/main/CODE_OF_CONDUCT.md diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pip-23.0.1.dist-info/RECORD b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pip-23.0.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..cc3d5a34258a56f74fa7cba41e4af45b2c9272ab --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pip-23.0.1.dist-info/RECORD @@ -0,0 +1,1002 @@ +../../../bin/pip,sha256=J4RKfgy5R184w10wnrGDXTW2-hEbWQB1zH0hQbbgzdA,255 +../../../bin/pip3,sha256=J4RKfgy5R184w10wnrGDXTW2-hEbWQB1zH0hQbbgzdA,255 +../../../bin/pip3.10,sha256=J4RKfgy5R184w10wnrGDXTW2-hEbWQB1zH0hQbbgzdA,255 +pip-23.0.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +pip-23.0.1.dist-info/LICENSE.txt,sha256=Y0MApmnUmurmWxLGxIySTFGkzfPR_whtw0VtyLyqIQQ,1093 +pip-23.0.1.dist-info/METADATA,sha256=POh89utz-H1e0K-xDY9CL9gs-x0MjH-AWxbhJG3aaVE,4072 +pip-23.0.1.dist-info/RECORD,, +pip-23.0.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip-23.0.1.dist-info/WHEEL,sha256=2wepM1nk4DS4eFpYrW1TTqPcoGNfHhhO_i5m4cOimbo,92 +pip-23.0.1.dist-info/entry_points.txt,sha256=w694mjHYSfmSoUVVSaHoQ9UkOBBdtKKIJbyDRLdKju8,124 +pip-23.0.1.dist-info/top_level.txt,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +pip/__init__.py,sha256=5yroedzc2dKKbcynDrHX8vBoLxqU27KmFvvHmdqQN9w,357 +pip/__main__.py,sha256=mXwWDftNLMKfwVqKFWGE_uuBZvGSIiUELhLkeysIuZc,1198 +pip/__pip-runner__.py,sha256=EnrfKmKMzWAdqg_JicLCOP9Y95Ux7zHh4ObvqLtQcjo,1444 +pip/__pycache__/__init__.cpython-310.pyc,, +pip/__pycache__/__main__.cpython-310.pyc,, +pip/__pycache__/__pip-runner__.cpython-310.pyc,, +pip/_internal/__init__.py,sha256=nnFCuxrPMgALrIDxSoy-H6Zj4W4UY60D-uL1aJyq0pc,573 +pip/_internal/__pycache__/__init__.cpython-310.pyc,, +pip/_internal/__pycache__/build_env.cpython-310.pyc,, +pip/_internal/__pycache__/cache.cpython-310.pyc,, +pip/_internal/__pycache__/configuration.cpython-310.pyc,, +pip/_internal/__pycache__/exceptions.cpython-310.pyc,, +pip/_internal/__pycache__/main.cpython-310.pyc,, +pip/_internal/__pycache__/pyproject.cpython-310.pyc,, +pip/_internal/__pycache__/self_outdated_check.cpython-310.pyc,, +pip/_internal/__pycache__/wheel_builder.cpython-310.pyc,, +pip/_internal/build_env.py,sha256=1ESpqw0iupS_K7phZK5zshVE5Czy9BtGLFU4W6Enva8,10243 +pip/_internal/cache.py,sha256=C3n78VnBga9rjPXZqht_4A4d-T25poC7K0qBM7FHDhU,10734 +pip/_internal/cli/__init__.py,sha256=FkHBgpxxb-_gd6r1FjnNhfMOzAUYyXoXKJ6abijfcFU,132 +pip/_internal/cli/__pycache__/__init__.cpython-310.pyc,, +pip/_internal/cli/__pycache__/autocompletion.cpython-310.pyc,, +pip/_internal/cli/__pycache__/base_command.cpython-310.pyc,, +pip/_internal/cli/__pycache__/cmdoptions.cpython-310.pyc,, +pip/_internal/cli/__pycache__/command_context.cpython-310.pyc,, +pip/_internal/cli/__pycache__/main.cpython-310.pyc,, +pip/_internal/cli/__pycache__/main_parser.cpython-310.pyc,, +pip/_internal/cli/__pycache__/parser.cpython-310.pyc,, +pip/_internal/cli/__pycache__/progress_bars.cpython-310.pyc,, +pip/_internal/cli/__pycache__/req_command.cpython-310.pyc,, +pip/_internal/cli/__pycache__/spinners.cpython-310.pyc,, +pip/_internal/cli/__pycache__/status_codes.cpython-310.pyc,, +pip/_internal/cli/autocompletion.py,sha256=wY2JPZY2Eji1vhR7bVo-yCBPJ9LCy6P80iOAhZD1Vi8,6676 +pip/_internal/cli/base_command.py,sha256=t1D5x40Hfn9HnPnMt-iSxvqL14nht2olBCacW74pc-k,7842 +pip/_internal/cli/cmdoptions.py,sha256=0OHXkgnppCtC4QyF28ZL8FBosVUXG5pWj2uzO1CgWhM,29497 +pip/_internal/cli/command_context.py,sha256=RHgIPwtObh5KhMrd3YZTkl8zbVG-6Okml7YbFX4Ehg0,774 +pip/_internal/cli/main.py,sha256=ioJ8IVlb2K1qLOxR-tXkee9lURhYV89CDM71MKag7YY,2472 +pip/_internal/cli/main_parser.py,sha256=laDpsuBDl6kyfywp9eMMA9s84jfH2TJJn-vmL0GG90w,4338 +pip/_internal/cli/parser.py,sha256=tWP-K1uSxnJyXu3WE0kkH3niAYRBeuUaxeydhzOdhL4,10817 +pip/_internal/cli/progress_bars.py,sha256=So4mPoSjXkXiSHiTzzquH3VVyVD_njXlHJSExYPXAow,1968 +pip/_internal/cli/req_command.py,sha256=ypTutLv4j_efxC2f6C6aCQufxre-zaJdi5m_tWlLeBk,18172 +pip/_internal/cli/spinners.py,sha256=hIJ83GerdFgFCdobIA23Jggetegl_uC4Sp586nzFbPE,5118 +pip/_internal/cli/status_codes.py,sha256=sEFHUaUJbqv8iArL3HAtcztWZmGOFX01hTesSytDEh0,116 +pip/_internal/commands/__init__.py,sha256=5oRO9O3dM2vGuh0bFw4HOVletryrz5HHMmmPWwJrH9U,3882 +pip/_internal/commands/__pycache__/__init__.cpython-310.pyc,, +pip/_internal/commands/__pycache__/cache.cpython-310.pyc,, +pip/_internal/commands/__pycache__/check.cpython-310.pyc,, +pip/_internal/commands/__pycache__/completion.cpython-310.pyc,, +pip/_internal/commands/__pycache__/configuration.cpython-310.pyc,, +pip/_internal/commands/__pycache__/debug.cpython-310.pyc,, +pip/_internal/commands/__pycache__/download.cpython-310.pyc,, +pip/_internal/commands/__pycache__/freeze.cpython-310.pyc,, +pip/_internal/commands/__pycache__/hash.cpython-310.pyc,, +pip/_internal/commands/__pycache__/help.cpython-310.pyc,, +pip/_internal/commands/__pycache__/index.cpython-310.pyc,, +pip/_internal/commands/__pycache__/inspect.cpython-310.pyc,, +pip/_internal/commands/__pycache__/install.cpython-310.pyc,, +pip/_internal/commands/__pycache__/list.cpython-310.pyc,, +pip/_internal/commands/__pycache__/search.cpython-310.pyc,, +pip/_internal/commands/__pycache__/show.cpython-310.pyc,, +pip/_internal/commands/__pycache__/uninstall.cpython-310.pyc,, +pip/_internal/commands/__pycache__/wheel.cpython-310.pyc,, +pip/_internal/commands/cache.py,sha256=muaT0mbL-ZUpn6AaushVAipzTiMwE4nV2BLbJBwt_KQ,7582 +pip/_internal/commands/check.py,sha256=0gjXR7j36xJT5cs2heYU_dfOfpnFfzX8OoPNNoKhqdM,1685 +pip/_internal/commands/completion.py,sha256=H0TJvGrdsoleuIyQKzJbicLFppYx2OZA0BLNpQDeFjI,4129 +pip/_internal/commands/configuration.py,sha256=NB5uf8HIX8-li95YLoZO09nALIWlLCHDF5aifSKcBn8,9815 +pip/_internal/commands/debug.py,sha256=AesEID-4gPFDWTwPiPaGZuD4twdT-imaGuMR5ZfSn8s,6591 +pip/_internal/commands/download.py,sha256=LwKEyYMG2L67nQRyGo8hQdNEeMU2bmGWqJfcB8JDXas,5289 +pip/_internal/commands/freeze.py,sha256=gCjoD6foBZPBAAYx5t8zZLkJhsF_ZRtnb3dPuD7beO8,2951 +pip/_internal/commands/hash.py,sha256=EVVOuvGtoPEdFi8SNnmdqlCQrhCxV-kJsdwtdcCnXGQ,1703 +pip/_internal/commands/help.py,sha256=gcc6QDkcgHMOuAn5UxaZwAStsRBrnGSn_yxjS57JIoM,1132 +pip/_internal/commands/index.py,sha256=cGQVSA5dAs7caQ9sz4kllYvaI4ZpGiq1WhCgaImXNSA,4793 +pip/_internal/commands/inspect.py,sha256=2wSPt9yfr3r6g-s2S5L6PvRtaHNVyb4TuodMStJ39cw,3188 +pip/_internal/commands/install.py,sha256=3vT9tnHOV-p6dPMaKDqzivqmcq_kPAI-jVkxOEwN5C4,32389 +pip/_internal/commands/list.py,sha256=Fk1TSxB33NlRS4qlLQ0xwnytnF9-zkQJbKQYv2xc4Q4,12343 +pip/_internal/commands/search.py,sha256=sbBZiARRc050QquOKcCvOr2K3XLsoYebLKZGRi__iUI,5697 +pip/_internal/commands/show.py,sha256=t5jia4zcYJRJZy4U_Von7zMl03hJmmcofj6oDNTnj7Y,6419 +pip/_internal/commands/uninstall.py,sha256=OIqO9tqadY8kM4HwhFf1Q62fUIp7v8KDrTRo8yWMz7Y,3886 +pip/_internal/commands/wheel.py,sha256=mbFJd4dmUfrVFJkQbK8n2zHyRcD3AI91f7EUo9l3KYg,7396 +pip/_internal/configuration.py,sha256=uBKTus43pDIO6IzT2mLWQeROmHhtnoabhniKNjPYvD0,13529 +pip/_internal/distributions/__init__.py,sha256=Hq6kt6gXBgjNit5hTTWLAzeCNOKoB-N0pGYSqehrli8,858 +pip/_internal/distributions/__pycache__/__init__.cpython-310.pyc,, +pip/_internal/distributions/__pycache__/base.cpython-310.pyc,, +pip/_internal/distributions/__pycache__/installed.cpython-310.pyc,, +pip/_internal/distributions/__pycache__/sdist.cpython-310.pyc,, +pip/_internal/distributions/__pycache__/wheel.cpython-310.pyc,, +pip/_internal/distributions/base.py,sha256=jrF1Vi7eGyqFqMHrieh1PIOrGU7KeCxhYPZnbvtmvGY,1221 +pip/_internal/distributions/installed.py,sha256=NI2OgsgH9iBq9l5vB-56vOg5YsybOy-AU4VE5CSCO2I,729 +pip/_internal/distributions/sdist.py,sha256=SQBdkatXSigKGG_SaD0U0p1Jwdfrg26UCNcHgkXZfdA,6494 +pip/_internal/distributions/wheel.py,sha256=m-J4XO-gvFerlYsFzzSXYDvrx8tLZlJFTCgDxctn8ig,1164 +pip/_internal/exceptions.py,sha256=cU4dz7x-1uFGrf2A1_Np9tKcy599bRJKRJkikgARxW4,24244 +pip/_internal/index/__init__.py,sha256=vpt-JeTZefh8a-FC22ZeBSXFVbuBcXSGiILhQZJaNpQ,30 +pip/_internal/index/__pycache__/__init__.cpython-310.pyc,, +pip/_internal/index/__pycache__/collector.cpython-310.pyc,, +pip/_internal/index/__pycache__/package_finder.cpython-310.pyc,, +pip/_internal/index/__pycache__/sources.cpython-310.pyc,, +pip/_internal/index/collector.py,sha256=3OmYZ3tCoRPGOrELSgQWG-03M-bQHa2-VCA3R_nJAaU,16504 +pip/_internal/index/package_finder.py,sha256=rrUw4vj7QE_eMt022jw--wQiKznMaUgVBkJ1UCrVUxo,37873 +pip/_internal/index/sources.py,sha256=SVyPitv08-Qalh2_Bk5diAJ9GAA_d-a93koouQodAG0,6557 +pip/_internal/locations/__init__.py,sha256=Dh8LJWG8LRlDK4JIj9sfRF96TREzE--N_AIlx7Tqoe4,15365 +pip/_internal/locations/__pycache__/__init__.cpython-310.pyc,, +pip/_internal/locations/__pycache__/_distutils.cpython-310.pyc,, +pip/_internal/locations/__pycache__/_sysconfig.cpython-310.pyc,, +pip/_internal/locations/__pycache__/base.cpython-310.pyc,, +pip/_internal/locations/_distutils.py,sha256=cmi6h63xYNXhQe7KEWEMaANjHFy5yQOPt_1_RCWyXMY,6100 +pip/_internal/locations/_sysconfig.py,sha256=jyNVtUfMIf0mtyY-Xp1m9yQ8iwECozSVVFmjkN9a2yw,7680 +pip/_internal/locations/base.py,sha256=RQiPi1d4FVM2Bxk04dQhXZ2PqkeljEL2fZZ9SYqIQ78,2556 +pip/_internal/main.py,sha256=r-UnUe8HLo5XFJz8inTcOOTiu_sxNhgHb6VwlGUllOI,340 +pip/_internal/metadata/__init__.py,sha256=84j1dPJaIoz5Q2ZTPi0uB1iaDAHiUNfKtYSGQCfFKpo,4280 +pip/_internal/metadata/__pycache__/__init__.cpython-310.pyc,, +pip/_internal/metadata/__pycache__/_json.cpython-310.pyc,, +pip/_internal/metadata/__pycache__/base.cpython-310.pyc,, +pip/_internal/metadata/__pycache__/pkg_resources.cpython-310.pyc,, +pip/_internal/metadata/_json.py,sha256=BTkWfFDrWFwuSodImjtbAh8wCL3isecbnjTb5E6UUDI,2595 +pip/_internal/metadata/base.py,sha256=vIwIo1BtoqegehWMAXhNrpLGYBq245rcaCNkBMPnTU8,25277 +pip/_internal/metadata/importlib/__init__.py,sha256=9ZVO8BoE7NEZPmoHp5Ap_NJo0HgNIezXXg-TFTtt3Z4,107 +pip/_internal/metadata/importlib/__pycache__/__init__.cpython-310.pyc,, +pip/_internal/metadata/importlib/__pycache__/_compat.cpython-310.pyc,, +pip/_internal/metadata/importlib/__pycache__/_dists.cpython-310.pyc,, +pip/_internal/metadata/importlib/__pycache__/_envs.cpython-310.pyc,, +pip/_internal/metadata/importlib/_compat.py,sha256=GAe_prIfCE4iUylrnr_2dJRlkkBVRUbOidEoID7LPoE,1882 +pip/_internal/metadata/importlib/_dists.py,sha256=BUV8y6D0PePZrEN3vfJL-m1FDqZ6YPRgAiBeBinHhNg,8181 +pip/_internal/metadata/importlib/_envs.py,sha256=7BxanCh3T7arusys__O2ZHJdnmDhQXFmfU7x1-jB5xI,7457 +pip/_internal/metadata/pkg_resources.py,sha256=WjwiNdRsvxqxL4MA5Tb5a_q3Q3sUhdpbZF8wGLtPMI0,9773 +pip/_internal/models/__init__.py,sha256=3DHUd_qxpPozfzouoqa9g9ts1Czr5qaHfFxbnxriepM,63 +pip/_internal/models/__pycache__/__init__.cpython-310.pyc,, +pip/_internal/models/__pycache__/candidate.cpython-310.pyc,, +pip/_internal/models/__pycache__/direct_url.cpython-310.pyc,, +pip/_internal/models/__pycache__/format_control.cpython-310.pyc,, +pip/_internal/models/__pycache__/index.cpython-310.pyc,, +pip/_internal/models/__pycache__/installation_report.cpython-310.pyc,, +pip/_internal/models/__pycache__/link.cpython-310.pyc,, +pip/_internal/models/__pycache__/scheme.cpython-310.pyc,, +pip/_internal/models/__pycache__/search_scope.cpython-310.pyc,, +pip/_internal/models/__pycache__/selection_prefs.cpython-310.pyc,, +pip/_internal/models/__pycache__/target_python.cpython-310.pyc,, +pip/_internal/models/__pycache__/wheel.cpython-310.pyc,, +pip/_internal/models/candidate.py,sha256=6pcABsaR7CfIHlbJbr2_kMkVJFL_yrYjTx6SVWUnCPQ,990 +pip/_internal/models/direct_url.py,sha256=f3WiKUwWPdBkT1xm7DlolS32ZAMYh3jbkkVH-BUON5A,6626 +pip/_internal/models/format_control.py,sha256=DJpMYjxeYKKQdwNcML2_F0vtAh-qnKTYe-CpTxQe-4g,2520 +pip/_internal/models/index.py,sha256=tYnL8oxGi4aSNWur0mG8DAP7rC6yuha_MwJO8xw0crI,1030 +pip/_internal/models/installation_report.py,sha256=Hymmzv9-e3WhtewYm2NIOeMyAB6lXp736mpYqb9scZ0,2617 +pip/_internal/models/link.py,sha256=nfybVSpXgVHeU0MkC8hMkN2IgMup8Pdaudg74_sQEC8,18602 +pip/_internal/models/scheme.py,sha256=3EFQp_ICu_shH1-TBqhl0QAusKCPDFOlgHFeN4XowWs,738 +pip/_internal/models/search_scope.py,sha256=iGPQQ6a4Lau8oGQ_FWj8aRLik8A21o03SMO5KnSt-Cg,4644 +pip/_internal/models/selection_prefs.py,sha256=KZdi66gsR-_RUXUr9uejssk3rmTHrQVJWeNA2sV-VSY,1907 +pip/_internal/models/target_python.py,sha256=qKpZox7J8NAaPmDs5C_aniwfPDxzvpkrCKqfwndG87k,3858 +pip/_internal/models/wheel.py,sha256=YqazoIZyma_Q1ejFa1C7NHKQRRWlvWkdK96VRKmDBeI,3600 +pip/_internal/network/__init__.py,sha256=jf6Tt5nV_7zkARBrKojIXItgejvoegVJVKUbhAa5Ioc,50 +pip/_internal/network/__pycache__/__init__.cpython-310.pyc,, +pip/_internal/network/__pycache__/auth.cpython-310.pyc,, +pip/_internal/network/__pycache__/cache.cpython-310.pyc,, +pip/_internal/network/__pycache__/download.cpython-310.pyc,, +pip/_internal/network/__pycache__/lazy_wheel.cpython-310.pyc,, +pip/_internal/network/__pycache__/session.cpython-310.pyc,, +pip/_internal/network/__pycache__/utils.cpython-310.pyc,, +pip/_internal/network/__pycache__/xmlrpc.cpython-310.pyc,, +pip/_internal/network/auth.py,sha256=MQVP0k4hUXk8ReYEfsGQ5t7_TS7cNHQuaHJuBlJLHxU,16507 +pip/_internal/network/cache.py,sha256=hgXftU-eau4MWxHSLquTMzepYq5BPC2zhCkhN3glBy8,2145 +pip/_internal/network/download.py,sha256=HvDDq9bVqaN3jcS3DyVJHP7uTqFzbShdkf7NFSoHfkw,6096 +pip/_internal/network/lazy_wheel.py,sha256=PbPyuleNhtEq6b2S7rufoGXZWMD15FAGL4XeiAQ8FxA,7638 +pip/_internal/network/session.py,sha256=BpDOJ7_Xw5VkgPYWsePzcaqOfcyRZcB2AW7W0HGBST0,18443 +pip/_internal/network/utils.py,sha256=6A5SrUJEEUHxbGtbscwU2NpCyz-3ztiDlGWHpRRhsJ8,4073 +pip/_internal/network/xmlrpc.py,sha256=AzQgG4GgS152_cqmGr_Oz2MIXsCal-xfsis7fA7nmU0,1791 +pip/_internal/operations/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_internal/operations/__pycache__/__init__.cpython-310.pyc,, +pip/_internal/operations/__pycache__/check.cpython-310.pyc,, +pip/_internal/operations/__pycache__/freeze.cpython-310.pyc,, +pip/_internal/operations/__pycache__/prepare.cpython-310.pyc,, +pip/_internal/operations/build/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_internal/operations/build/__pycache__/__init__.cpython-310.pyc,, +pip/_internal/operations/build/__pycache__/build_tracker.cpython-310.pyc,, +pip/_internal/operations/build/__pycache__/metadata.cpython-310.pyc,, +pip/_internal/operations/build/__pycache__/metadata_editable.cpython-310.pyc,, +pip/_internal/operations/build/__pycache__/metadata_legacy.cpython-310.pyc,, +pip/_internal/operations/build/__pycache__/wheel.cpython-310.pyc,, +pip/_internal/operations/build/__pycache__/wheel_editable.cpython-310.pyc,, +pip/_internal/operations/build/__pycache__/wheel_legacy.cpython-310.pyc,, +pip/_internal/operations/build/build_tracker.py,sha256=vf81EwomN3xe9G8qRJED0VGqNikmRQRQoobNsxi5Xrs,4133 +pip/_internal/operations/build/metadata.py,sha256=9S0CUD8U3QqZeXp-Zyt8HxwU90lE4QrnYDgrqZDzBnc,1422 +pip/_internal/operations/build/metadata_editable.py,sha256=VLL7LvntKE8qxdhUdEJhcotFzUsOSI8NNS043xULKew,1474 +pip/_internal/operations/build/metadata_legacy.py,sha256=o-eU21As175hDC7dluM1fJJ_FqokTIShyWpjKaIpHZw,2198 +pip/_internal/operations/build/wheel.py,sha256=sT12FBLAxDC6wyrDorh8kvcZ1jG5qInCRWzzP-UkJiQ,1075 +pip/_internal/operations/build/wheel_editable.py,sha256=yOtoH6zpAkoKYEUtr8FhzrYnkNHQaQBjWQ2HYae1MQg,1417 +pip/_internal/operations/build/wheel_legacy.py,sha256=C9j6rukgQI1n_JeQLoZGuDdfUwzCXShyIdPTp6edbMQ,3064 +pip/_internal/operations/check.py,sha256=WsN7z0_QSgJjw0JsWWcqOHj4wWTaFv0J7mxgUByDCOg,5122 +pip/_internal/operations/freeze.py,sha256=mwTZ2uML8aQgo3k8MR79a7SZmmmvdAJqdyaknKbavmg,9784 +pip/_internal/operations/install/__init__.py,sha256=mX7hyD2GNBO2mFGokDQ30r_GXv7Y_PLdtxcUv144e-s,51 +pip/_internal/operations/install/__pycache__/__init__.cpython-310.pyc,, +pip/_internal/operations/install/__pycache__/editable_legacy.cpython-310.pyc,, +pip/_internal/operations/install/__pycache__/legacy.cpython-310.pyc,, +pip/_internal/operations/install/__pycache__/wheel.cpython-310.pyc,, +pip/_internal/operations/install/editable_legacy.py,sha256=ee4kfJHNuzTdKItbfAsNOSEwq_vD7DRPGkBdK48yBhU,1354 +pip/_internal/operations/install/legacy.py,sha256=cHdcHebyzf8w7OaOLwcsTNSMSSV8WBoAPFLay_9CjE8,4105 +pip/_internal/operations/install/wheel.py,sha256=CxzEg2wTPX4SxNTPIx0ozTqF1X7LhpCyP3iM2FjcKUE,27407 +pip/_internal/operations/prepare.py,sha256=BeYXrLFpRoV5XBnRXQHxRA2plyC36kK9Pms5D9wjCo4,25091 +pip/_internal/pyproject.py,sha256=QqSZR5AGwtf3HTa8NdbDq2yj9T2r9S2h9gnU4aX2Kvg,6987 +pip/_internal/req/__init__.py,sha256=rUQ9d_Sh3E5kNYqX9pkN0D06YL-LrtcbJQ-LiIonq08,2807 +pip/_internal/req/__pycache__/__init__.cpython-310.pyc,, +pip/_internal/req/__pycache__/constructors.cpython-310.pyc,, +pip/_internal/req/__pycache__/req_file.cpython-310.pyc,, +pip/_internal/req/__pycache__/req_install.cpython-310.pyc,, +pip/_internal/req/__pycache__/req_set.cpython-310.pyc,, +pip/_internal/req/__pycache__/req_uninstall.cpython-310.pyc,, +pip/_internal/req/constructors.py,sha256=ypjtq1mOQ3d2mFkFPMf_6Mr8SLKeHQk3tUKHA1ddG0U,16611 +pip/_internal/req/req_file.py,sha256=N6lPO3c0to_G73YyGAnk7VUYmed5jV4Qxgmt1xtlXVg,17646 +pip/_internal/req/req_install.py,sha256=X4WNQlTtvkeATwWdSiJcNLihwbYI_EnGDgE99p-Aa00,35763 +pip/_internal/req/req_set.py,sha256=j3esG0s6SzoVReX9rWn4rpYNtyET_fwxbwJPRimvRxo,2858 +pip/_internal/req/req_uninstall.py,sha256=ZFQfgSNz6H1BMsgl87nQNr2iaQCcbFcmXpW8rKVQcic,24045 +pip/_internal/resolution/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_internal/resolution/__pycache__/__init__.cpython-310.pyc,, +pip/_internal/resolution/__pycache__/base.cpython-310.pyc,, +pip/_internal/resolution/base.py,sha256=qlmh325SBVfvG6Me9gc5Nsh5sdwHBwzHBq6aEXtKsLA,583 +pip/_internal/resolution/legacy/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_internal/resolution/legacy/__pycache__/__init__.cpython-310.pyc,, +pip/_internal/resolution/legacy/__pycache__/resolver.cpython-310.pyc,, +pip/_internal/resolution/legacy/resolver.py,sha256=9em8D5TcSsEN4xZM1WreaRShOnyM4LlvhMSHpUPsocE,24129 +pip/_internal/resolution/resolvelib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_internal/resolution/resolvelib/__pycache__/__init__.cpython-310.pyc,, +pip/_internal/resolution/resolvelib/__pycache__/base.cpython-310.pyc,, +pip/_internal/resolution/resolvelib/__pycache__/candidates.cpython-310.pyc,, +pip/_internal/resolution/resolvelib/__pycache__/factory.cpython-310.pyc,, +pip/_internal/resolution/resolvelib/__pycache__/found_candidates.cpython-310.pyc,, +pip/_internal/resolution/resolvelib/__pycache__/provider.cpython-310.pyc,, +pip/_internal/resolution/resolvelib/__pycache__/reporter.cpython-310.pyc,, +pip/_internal/resolution/resolvelib/__pycache__/requirements.cpython-310.pyc,, +pip/_internal/resolution/resolvelib/__pycache__/resolver.cpython-310.pyc,, +pip/_internal/resolution/resolvelib/base.py,sha256=u1O4fkvCO4mhmu5i32xrDv9AX5NgUci_eYVyBDQhTIM,5220 +pip/_internal/resolution/resolvelib/candidates.py,sha256=6kQZeMzwibnL4lO6bW0hUQQjNEvXfADdFphRRkRvOtc,18963 +pip/_internal/resolution/resolvelib/factory.py,sha256=OnjkLIgyk5Tol7uOOqapA1D4qiRHWmPU18DF1yN5N8o,27878 +pip/_internal/resolution/resolvelib/found_candidates.py,sha256=hvL3Hoa9VaYo-qEOZkBi2Iqw251UDxPz-uMHVaWmLpE,5705 +pip/_internal/resolution/resolvelib/provider.py,sha256=Vd4jW_NnyifB-HMkPYtZIO70M3_RM0MbL5YV6XyBM-w,9914 +pip/_internal/resolution/resolvelib/reporter.py,sha256=3ZVVYrs5PqvLFJkGLcuXoMK5mTInFzl31xjUpDBpZZk,2526 +pip/_internal/resolution/resolvelib/requirements.py,sha256=B1ndvKPSuyyyTEXt9sKhbwminViSWnBrJa7qO2ln4Z0,5455 +pip/_internal/resolution/resolvelib/resolver.py,sha256=nYZ9bTFXj5c1ILKnkSgU7tUCTYyo5V5J-J0sKoA7Wzg,11533 +pip/_internal/self_outdated_check.py,sha256=pnqBuKKZQ8OxKP0MaUUiDHl3AtyoMJHHG4rMQ7YcYXY,8167 +pip/_internal/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_internal/utils/__pycache__/__init__.cpython-310.pyc,, +pip/_internal/utils/__pycache__/_log.cpython-310.pyc,, +pip/_internal/utils/__pycache__/appdirs.cpython-310.pyc,, +pip/_internal/utils/__pycache__/compat.cpython-310.pyc,, +pip/_internal/utils/__pycache__/compatibility_tags.cpython-310.pyc,, +pip/_internal/utils/__pycache__/datetime.cpython-310.pyc,, +pip/_internal/utils/__pycache__/deprecation.cpython-310.pyc,, +pip/_internal/utils/__pycache__/direct_url_helpers.cpython-310.pyc,, +pip/_internal/utils/__pycache__/distutils_args.cpython-310.pyc,, +pip/_internal/utils/__pycache__/egg_link.cpython-310.pyc,, +pip/_internal/utils/__pycache__/encoding.cpython-310.pyc,, +pip/_internal/utils/__pycache__/entrypoints.cpython-310.pyc,, +pip/_internal/utils/__pycache__/filesystem.cpython-310.pyc,, +pip/_internal/utils/__pycache__/filetypes.cpython-310.pyc,, +pip/_internal/utils/__pycache__/glibc.cpython-310.pyc,, +pip/_internal/utils/__pycache__/hashes.cpython-310.pyc,, +pip/_internal/utils/__pycache__/inject_securetransport.cpython-310.pyc,, +pip/_internal/utils/__pycache__/logging.cpython-310.pyc,, +pip/_internal/utils/__pycache__/misc.cpython-310.pyc,, +pip/_internal/utils/__pycache__/models.cpython-310.pyc,, +pip/_internal/utils/__pycache__/packaging.cpython-310.pyc,, +pip/_internal/utils/__pycache__/setuptools_build.cpython-310.pyc,, +pip/_internal/utils/__pycache__/subprocess.cpython-310.pyc,, +pip/_internal/utils/__pycache__/temp_dir.cpython-310.pyc,, +pip/_internal/utils/__pycache__/unpacking.cpython-310.pyc,, +pip/_internal/utils/__pycache__/urls.cpython-310.pyc,, +pip/_internal/utils/__pycache__/virtualenv.cpython-310.pyc,, +pip/_internal/utils/__pycache__/wheel.cpython-310.pyc,, +pip/_internal/utils/_log.py,sha256=-jHLOE_THaZz5BFcCnoSL9EYAtJ0nXem49s9of4jvKw,1015 +pip/_internal/utils/appdirs.py,sha256=swgcTKOm3daLeXTW6v5BUS2Ti2RvEnGRQYH_yDXklAo,1665 +pip/_internal/utils/compat.py,sha256=ACyBfLgj3_XG-iA5omEDrXqDM0cQKzi8h8HRBInzG6Q,1884 +pip/_internal/utils/compatibility_tags.py,sha256=ydin8QG8BHqYRsPY4OL6cmb44CbqXl1T0xxS97VhHkk,5377 +pip/_internal/utils/datetime.py,sha256=m21Y3wAtQc-ji6Veb6k_M5g6A0ZyFI4egchTdnwh-pQ,242 +pip/_internal/utils/deprecation.py,sha256=OLc7GzDwPob9y8jscDYCKUNBV-9CWwqFplBOJPLOpBM,5764 +pip/_internal/utils/direct_url_helpers.py,sha256=6F1tc2rcKaCZmgfVwsE6ObIe_Pux23mUVYA-2D9wCFc,3206 +pip/_internal/utils/distutils_args.py,sha256=bYUt4wfFJRaeGO4VHia6FNaA8HlYXMcKuEq1zYijY5g,1115 +pip/_internal/utils/egg_link.py,sha256=ZryCchR_yQSCsdsMkCpxQjjLbQxObA5GDtLG0RR5mGc,2118 +pip/_internal/utils/encoding.py,sha256=qqsXDtiwMIjXMEiIVSaOjwH5YmirCaK-dIzb6-XJsL0,1169 +pip/_internal/utils/entrypoints.py,sha256=YlhLTRl2oHBAuqhc-zmL7USS67TPWVHImjeAQHreZTQ,3064 +pip/_internal/utils/filesystem.py,sha256=RhMIXUaNVMGjc3rhsDahWQ4MavvEQDdqXqgq-F6fpw8,5122 +pip/_internal/utils/filetypes.py,sha256=i8XAQ0eFCog26Fw9yV0Yb1ygAqKYB1w9Cz9n0fj8gZU,716 +pip/_internal/utils/glibc.py,sha256=tDfwVYnJCOC0BNVpItpy8CGLP9BjkxFHdl0mTS0J7fc,3110 +pip/_internal/utils/hashes.py,sha256=1WhkVNIHNfuYLafBHThIjVKGplxFJXSlQtuG2mXNlJI,4831 +pip/_internal/utils/inject_securetransport.py,sha256=o-QRVMGiENrTJxw3fAhA7uxpdEdw6M41TjHYtSVRrcg,795 +pip/_internal/utils/logging.py,sha256=U2q0i1n8hPS2gQh8qcocAg5dovGAa_bR24akmXMzrk4,11632 +pip/_internal/utils/misc.py,sha256=XLtMDOmy8mWiNLuPIhxPdO1bWIleLdN6JnWDZsXfTgE,22253 +pip/_internal/utils/models.py,sha256=5GoYU586SrxURMvDn_jBMJInitviJg4O5-iOU-6I0WY,1193 +pip/_internal/utils/packaging.py,sha256=5Wm6_x7lKrlqVjPI5MBN_RurcRHwVYoQ7Ksrs84de7s,2108 +pip/_internal/utils/setuptools_build.py,sha256=4i3CuS34yNrkePnZ73rR47pyDzpZBo-SX9V5PNDSSHY,5662 +pip/_internal/utils/subprocess.py,sha256=0EMhgfPGFk8FZn6Qq7Hp9PN6YHuQNWiVby4DXcTCON4,9200 +pip/_internal/utils/temp_dir.py,sha256=aCX489gRa4Nu0dMKRFyGhV6maJr60uEynu5uCbKR4Qg,7702 +pip/_internal/utils/unpacking.py,sha256=SBb2iV1crb89MDRTEKY86R4A_UOWApTQn9VQVcMDOlE,8821 +pip/_internal/utils/urls.py,sha256=AhaesUGl-9it6uvG6fsFPOr9ynFpGaTMk4t5XTX7Z_Q,1759 +pip/_internal/utils/virtualenv.py,sha256=S6f7csYorRpiD6cvn3jISZYc3I8PJC43H5iMFpRAEDU,3456 +pip/_internal/utils/wheel.py,sha256=lXOgZyTlOm5HmK8tw5iw0A3_5A6wRzsXHOaQkIvvloU,4549 +pip/_internal/vcs/__init__.py,sha256=UAqvzpbi0VbZo3Ub6skEeZAw-ooIZR-zX_WpCbxyCoU,596 +pip/_internal/vcs/__pycache__/__init__.cpython-310.pyc,, +pip/_internal/vcs/__pycache__/bazaar.cpython-310.pyc,, +pip/_internal/vcs/__pycache__/git.cpython-310.pyc,, +pip/_internal/vcs/__pycache__/mercurial.cpython-310.pyc,, +pip/_internal/vcs/__pycache__/subversion.cpython-310.pyc,, +pip/_internal/vcs/__pycache__/versioncontrol.cpython-310.pyc,, +pip/_internal/vcs/bazaar.py,sha256=j0oin0fpGRHcCFCxEcpPCQoFEvA-DMLULKdGP8Nv76o,3519 +pip/_internal/vcs/git.py,sha256=mjhwudCx9WlLNkxZ6_kOKmueF0rLoU2i1xeASKF6yiQ,18116 +pip/_internal/vcs/mercurial.py,sha256=Bzbd518Jsx-EJI0IhIobiQqiRsUv5TWYnrmRIFWE0Gw,5238 +pip/_internal/vcs/subversion.py,sha256=vhZs8L-TNggXqM1bbhl-FpbxE3TrIB6Tgnx8fh3S2HE,11729 +pip/_internal/vcs/versioncontrol.py,sha256=KUOc-hN51em9jrqxKwUR3JnkgSE-xSOqMiiJcSaL6B8,22811 +pip/_internal/wheel_builder.py,sha256=8cObBCu4mIsMJqZM7xXI9DO3vldiAnRNa1Gt6izPPTs,13079 +pip/_vendor/__init__.py,sha256=fNxOSVD0auElsD8fN9tuq5psfgMQ-RFBtD4X5gjlRkg,4966 +pip/_vendor/__pycache__/__init__.cpython-310.pyc,, +pip/_vendor/__pycache__/six.cpython-310.pyc,, +pip/_vendor/__pycache__/typing_extensions.cpython-310.pyc,, +pip/_vendor/cachecontrol/__init__.py,sha256=hrxlv3q7upsfyMw8k3gQ9vagBax1pYHSGGqYlZ0Zk0M,465 +pip/_vendor/cachecontrol/__pycache__/__init__.cpython-310.pyc,, +pip/_vendor/cachecontrol/__pycache__/_cmd.cpython-310.pyc,, +pip/_vendor/cachecontrol/__pycache__/adapter.cpython-310.pyc,, +pip/_vendor/cachecontrol/__pycache__/cache.cpython-310.pyc,, +pip/_vendor/cachecontrol/__pycache__/compat.cpython-310.pyc,, +pip/_vendor/cachecontrol/__pycache__/controller.cpython-310.pyc,, +pip/_vendor/cachecontrol/__pycache__/filewrapper.cpython-310.pyc,, +pip/_vendor/cachecontrol/__pycache__/heuristics.cpython-310.pyc,, +pip/_vendor/cachecontrol/__pycache__/serialize.cpython-310.pyc,, +pip/_vendor/cachecontrol/__pycache__/wrapper.cpython-310.pyc,, +pip/_vendor/cachecontrol/_cmd.py,sha256=lxUXqfNTVx84zf6tcWbkLZHA6WVBRtJRpfeA9ZqhaAY,1379 +pip/_vendor/cachecontrol/adapter.py,sha256=ew9OYEQHEOjvGl06ZsuX8W3DAvHWsQKHwWAxISyGug8,5033 +pip/_vendor/cachecontrol/cache.py,sha256=Tty45fOjH40fColTGkqKQvQQmbYsMpk-nCyfLcv2vG4,1535 +pip/_vendor/cachecontrol/caches/__init__.py,sha256=h-1cUmOz6mhLsjTjOrJ8iPejpGdLCyG4lzTftfGZvLg,242 +pip/_vendor/cachecontrol/caches/__pycache__/__init__.cpython-310.pyc,, +pip/_vendor/cachecontrol/caches/__pycache__/file_cache.cpython-310.pyc,, +pip/_vendor/cachecontrol/caches/__pycache__/redis_cache.cpython-310.pyc,, +pip/_vendor/cachecontrol/caches/file_cache.py,sha256=GpexcE29LoY4MaZwPUTcUBZaDdcsjqyLxZFznk8Hbr4,5271 +pip/_vendor/cachecontrol/caches/redis_cache.py,sha256=mp-QWonP40I3xJGK3XVO-Gs9a3UjzlqqEmp9iLJH9F4,1033 +pip/_vendor/cachecontrol/compat.py,sha256=LNx7vqBndYdHU8YuJt53ab_8rzMGTXVrvMb7CZJkxG0,778 +pip/_vendor/cachecontrol/controller.py,sha256=bAYrt7x_VH4toNpI066LQxbHpYGpY1MxxmZAhspplvw,16416 +pip/_vendor/cachecontrol/filewrapper.py,sha256=X4BAQOO26GNOR7nH_fhTzAfeuct2rBQcx_15MyFBpcs,3946 +pip/_vendor/cachecontrol/heuristics.py,sha256=8kAyuZLSCyEIgQr6vbUwfhpqg9ows4mM0IV6DWazevI,4154 +pip/_vendor/cachecontrol/serialize.py,sha256=_U1NU_C-SDgFzkbAxAsPDgMTHeTWZZaHCQnZN_jh0U8,7105 +pip/_vendor/cachecontrol/wrapper.py,sha256=X3-KMZ20Ho3VtqyVaXclpeQpFzokR5NE8tZSfvKVaB8,774 +pip/_vendor/certifi/__init__.py,sha256=bK_nm9bLJzNvWZc2oZdiTwg2KWD4HSPBWGaM0zUDvMw,94 +pip/_vendor/certifi/__main__.py,sha256=1k3Cr95vCxxGRGDljrW3wMdpZdL3Nhf0u1n-k2qdsCY,255 +pip/_vendor/certifi/__pycache__/__init__.cpython-310.pyc,, +pip/_vendor/certifi/__pycache__/__main__.cpython-310.pyc,, +pip/_vendor/certifi/__pycache__/core.cpython-310.pyc,, +pip/_vendor/certifi/cacert.pem,sha256=LBHDzgj_xA05AxnHK8ENT5COnGNElNZe0svFUHMf1SQ,275233 +pip/_vendor/certifi/core.py,sha256=ZwiOsv-sD_ouU1ft8wy_xZ3LQ7UbcVzyqj2XNyrsZis,4279 +pip/_vendor/chardet/__init__.py,sha256=57R-HSxj0PWmILMN0GFmUNqEMfrEVSamXyjD-W6_fbs,4797 +pip/_vendor/chardet/__pycache__/__init__.cpython-310.pyc,, +pip/_vendor/chardet/__pycache__/big5freq.cpython-310.pyc,, +pip/_vendor/chardet/__pycache__/big5prober.cpython-310.pyc,, +pip/_vendor/chardet/__pycache__/chardistribution.cpython-310.pyc,, +pip/_vendor/chardet/__pycache__/charsetgroupprober.cpython-310.pyc,, +pip/_vendor/chardet/__pycache__/charsetprober.cpython-310.pyc,, +pip/_vendor/chardet/__pycache__/codingstatemachine.cpython-310.pyc,, +pip/_vendor/chardet/__pycache__/codingstatemachinedict.cpython-310.pyc,, +pip/_vendor/chardet/__pycache__/cp949prober.cpython-310.pyc,, +pip/_vendor/chardet/__pycache__/enums.cpython-310.pyc,, +pip/_vendor/chardet/__pycache__/escprober.cpython-310.pyc,, +pip/_vendor/chardet/__pycache__/escsm.cpython-310.pyc,, +pip/_vendor/chardet/__pycache__/eucjpprober.cpython-310.pyc,, +pip/_vendor/chardet/__pycache__/euckrfreq.cpython-310.pyc,, +pip/_vendor/chardet/__pycache__/euckrprober.cpython-310.pyc,, +pip/_vendor/chardet/__pycache__/euctwfreq.cpython-310.pyc,, +pip/_vendor/chardet/__pycache__/euctwprober.cpython-310.pyc,, +pip/_vendor/chardet/__pycache__/gb2312freq.cpython-310.pyc,, +pip/_vendor/chardet/__pycache__/gb2312prober.cpython-310.pyc,, +pip/_vendor/chardet/__pycache__/hebrewprober.cpython-310.pyc,, +pip/_vendor/chardet/__pycache__/jisfreq.cpython-310.pyc,, +pip/_vendor/chardet/__pycache__/johabfreq.cpython-310.pyc,, +pip/_vendor/chardet/__pycache__/johabprober.cpython-310.pyc,, +pip/_vendor/chardet/__pycache__/jpcntx.cpython-310.pyc,, +pip/_vendor/chardet/__pycache__/langbulgarianmodel.cpython-310.pyc,, +pip/_vendor/chardet/__pycache__/langgreekmodel.cpython-310.pyc,, +pip/_vendor/chardet/__pycache__/langhebrewmodel.cpython-310.pyc,, +pip/_vendor/chardet/__pycache__/langhungarianmodel.cpython-310.pyc,, +pip/_vendor/chardet/__pycache__/langrussianmodel.cpython-310.pyc,, +pip/_vendor/chardet/__pycache__/langthaimodel.cpython-310.pyc,, +pip/_vendor/chardet/__pycache__/langturkishmodel.cpython-310.pyc,, +pip/_vendor/chardet/__pycache__/latin1prober.cpython-310.pyc,, +pip/_vendor/chardet/__pycache__/macromanprober.cpython-310.pyc,, +pip/_vendor/chardet/__pycache__/mbcharsetprober.cpython-310.pyc,, +pip/_vendor/chardet/__pycache__/mbcsgroupprober.cpython-310.pyc,, +pip/_vendor/chardet/__pycache__/mbcssm.cpython-310.pyc,, +pip/_vendor/chardet/__pycache__/resultdict.cpython-310.pyc,, +pip/_vendor/chardet/__pycache__/sbcharsetprober.cpython-310.pyc,, +pip/_vendor/chardet/__pycache__/sbcsgroupprober.cpython-310.pyc,, +pip/_vendor/chardet/__pycache__/sjisprober.cpython-310.pyc,, +pip/_vendor/chardet/__pycache__/universaldetector.cpython-310.pyc,, +pip/_vendor/chardet/__pycache__/utf1632prober.cpython-310.pyc,, +pip/_vendor/chardet/__pycache__/utf8prober.cpython-310.pyc,, +pip/_vendor/chardet/__pycache__/version.cpython-310.pyc,, +pip/_vendor/chardet/big5freq.py,sha256=ltcfP-3PjlNHCoo5e4a7C4z-2DhBTXRfY6jbMbB7P30,31274 +pip/_vendor/chardet/big5prober.py,sha256=lPMfwCX6v2AaPgvFh_cSWZcgLDbWiFCHLZ_p9RQ9uxE,1763 +pip/_vendor/chardet/chardistribution.py,sha256=13B8XUG4oXDuLdXvfbIWwLFeR-ZU21AqTS1zcdON8bU,10032 +pip/_vendor/chardet/charsetgroupprober.py,sha256=UKK3SaIZB2PCdKSIS0gnvMtLR9JJX62M-fZJu3OlWyg,3915 +pip/_vendor/chardet/charsetprober.py,sha256=L3t8_wIOov8em-vZWOcbkdsrwe43N6_gqNh5pH7WPd4,5420 +pip/_vendor/chardet/cli/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_vendor/chardet/cli/__pycache__/__init__.cpython-310.pyc,, +pip/_vendor/chardet/cli/__pycache__/chardetect.cpython-310.pyc,, +pip/_vendor/chardet/cli/chardetect.py,sha256=zibMVg5RpKb-ME9_7EYG4ZM2Sf07NHcQzZ12U-rYJho,3242 +pip/_vendor/chardet/codingstatemachine.py,sha256=K7k69sw3jY5DmTXoSJQVsUtFIQKYPQVOSJJhBuGv_yE,3732 +pip/_vendor/chardet/codingstatemachinedict.py,sha256=0GY3Hi2qIZvDrOOJ3AtqppM1RsYxr_66ER4EHjuMiMc,542 +pip/_vendor/chardet/cp949prober.py,sha256=0jKRV7fECuWI16rNnks0ZECKA1iZYCIEaP8A1ZvjUSI,1860 +pip/_vendor/chardet/enums.py,sha256=TzECiZoCKNMqgwU76cPCeKWFBqaWvAdLMev5_bCkhY8,1683 +pip/_vendor/chardet/escprober.py,sha256=Kho48X65xE0scFylIdeJjM2bcbvRvv0h0WUbMWrJD3A,4006 +pip/_vendor/chardet/escsm.py,sha256=AqyXpA2FQFD7k-buBty_7itGEYkhmVa8X09NLRul3QM,12176 +pip/_vendor/chardet/eucjpprober.py,sha256=5KYaM9fsxkRYzw1b5k0fL-j_-ezIw-ij9r97a9MHxLY,3934 +pip/_vendor/chardet/euckrfreq.py,sha256=3mHuRvXfsq_QcQysDQFb8qSudvTiol71C6Ic2w57tKM,13566 +pip/_vendor/chardet/euckrprober.py,sha256=hiFT6wM174GIwRvqDsIcuOc-dDsq2uPKMKbyV8-1Xnc,1753 +pip/_vendor/chardet/euctwfreq.py,sha256=2alILE1Lh5eqiFJZjzRkMQXolNJRHY5oBQd-vmZYFFM,36913 +pip/_vendor/chardet/euctwprober.py,sha256=NxbpNdBtU0VFI0bKfGfDkpP7S2_8_6FlO87dVH0ogws,1753 +pip/_vendor/chardet/gb2312freq.py,sha256=49OrdXzD-HXqwavkqjo8Z7gvs58hONNzDhAyMENNkvY,20735 +pip/_vendor/chardet/gb2312prober.py,sha256=KPEBueaSLSvBpFeINMu0D6TgHcR90e5PaQawifzF4o0,1759 +pip/_vendor/chardet/hebrewprober.py,sha256=96T_Lj_OmW-fK7JrSHojYjyG3fsGgbzkoTNleZ3kfYE,14537 +pip/_vendor/chardet/jisfreq.py,sha256=mm8tfrwqhpOd3wzZKS4NJqkYBQVcDfTM2JiQ5aW932E,25796 +pip/_vendor/chardet/johabfreq.py,sha256=dBpOYG34GRX6SL8k_LbS9rxZPMjLjoMlgZ03Pz5Hmqc,42498 +pip/_vendor/chardet/johabprober.py,sha256=O1Qw9nVzRnun7vZp4UZM7wvJSv9W941mEU9uDMnY3DU,1752 +pip/_vendor/chardet/jpcntx.py,sha256=uhHrYWkLxE_rF5OkHKInm0HUsrjgKHHVQvtt3UcvotA,27055 +pip/_vendor/chardet/langbulgarianmodel.py,sha256=vmbvYFP8SZkSxoBvLkFqKiH1sjma5ihk3PTpdy71Rr4,104562 +pip/_vendor/chardet/langgreekmodel.py,sha256=JfB7bupjjJH2w3X_mYnQr9cJA_7EuITC2cRW13fUjeI,98484 +pip/_vendor/chardet/langhebrewmodel.py,sha256=3HXHaLQPNAGcXnJjkIJfozNZLTvTJmf4W5Awi6zRRKc,98196 +pip/_vendor/chardet/langhungarianmodel.py,sha256=WxbeQIxkv8YtApiNqxQcvj-tMycsoI4Xy-fwkDHpP_Y,101363 +pip/_vendor/chardet/langrussianmodel.py,sha256=s395bTZ87ESTrZCOdgXbEjZ9P1iGPwCl_8xSsac_DLY,128035 +pip/_vendor/chardet/langthaimodel.py,sha256=7bJlQitRpTnVGABmbSznHnJwOHDy3InkTvtFUx13WQI,102774 +pip/_vendor/chardet/langturkishmodel.py,sha256=XY0eGdTIy4eQ9Xg1LVPZacb-UBhHBR-cq0IpPVHowKc,95372 +pip/_vendor/chardet/latin1prober.py,sha256=p15EEmFbmQUwbKLC7lOJVGHEZwcG45ubEZYTGu01J5g,5380 +pip/_vendor/chardet/macromanprober.py,sha256=9anfzmY6TBfUPDyBDOdY07kqmTHpZ1tK0jL-p1JWcOY,6077 +pip/_vendor/chardet/mbcharsetprober.py,sha256=Wr04WNI4F3X_VxEverNG-H25g7u-MDDKlNt-JGj-_uU,3715 +pip/_vendor/chardet/mbcsgroupprober.py,sha256=iRpaNBjV0DNwYPu_z6TiHgRpwYahiM7ztI_4kZ4Uz9A,2131 +pip/_vendor/chardet/mbcssm.py,sha256=hUtPvDYgWDaA2dWdgLsshbwRfm3Q5YRlRogdmeRUNQw,30391 +pip/_vendor/chardet/metadata/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_vendor/chardet/metadata/__pycache__/__init__.cpython-310.pyc,, +pip/_vendor/chardet/metadata/__pycache__/languages.cpython-310.pyc,, +pip/_vendor/chardet/metadata/languages.py,sha256=FhvBIdZFxRQ-dTwkb_0madRKgVBCaUMQz9I5xqjE5iQ,13560 +pip/_vendor/chardet/resultdict.py,sha256=ez4FRvN5KaSosJeJ2WzUyKdDdg35HDy_SSLPXKCdt5M,402 +pip/_vendor/chardet/sbcharsetprober.py,sha256=-nd3F90i7GpXLjehLVHqVBE0KlWzGvQUPETLBNn4o6U,6400 +pip/_vendor/chardet/sbcsgroupprober.py,sha256=gcgI0fOfgw_3YTClpbra_MNxwyEyJ3eUXraoLHYb59E,4137 +pip/_vendor/chardet/sjisprober.py,sha256=aqQufMzRw46ZpFlzmYaYeT2-nzmKb-hmcrApppJ862k,4007 +pip/_vendor/chardet/universaldetector.py,sha256=xYBrg4x0dd9WnT8qclfADVD9ondrUNkqPmvte1pa520,14848 +pip/_vendor/chardet/utf1632prober.py,sha256=pw1epGdMj1hDGiCu1AHqqzOEfjX8MVdiW7O1BlT8-eQ,8505 +pip/_vendor/chardet/utf8prober.py,sha256=8m08Ub5490H4jQ6LYXvFysGtgKoKsHUd2zH_i8_TnVw,2812 +pip/_vendor/chardet/version.py,sha256=lGtJcxGM44Qz4Cbk4rbbmrKxnNr1-97U25TameLehZw,244 +pip/_vendor/colorama/__init__.py,sha256=wePQA4U20tKgYARySLEC047ucNX-g8pRLpYBuiHlLb8,266 +pip/_vendor/colorama/__pycache__/__init__.cpython-310.pyc,, +pip/_vendor/colorama/__pycache__/ansi.cpython-310.pyc,, +pip/_vendor/colorama/__pycache__/ansitowin32.cpython-310.pyc,, +pip/_vendor/colorama/__pycache__/initialise.cpython-310.pyc,, +pip/_vendor/colorama/__pycache__/win32.cpython-310.pyc,, +pip/_vendor/colorama/__pycache__/winterm.cpython-310.pyc,, +pip/_vendor/colorama/ansi.py,sha256=Top4EeEuaQdBWdteKMEcGOTeKeF19Q-Wo_6_Cj5kOzQ,2522 +pip/_vendor/colorama/ansitowin32.py,sha256=vPNYa3OZbxjbuFyaVo0Tmhmy1FZ1lKMWCnT7odXpItk,11128 +pip/_vendor/colorama/initialise.py,sha256=-hIny86ClXo39ixh5iSCfUIa2f_h_bgKRDW7gqs-KLU,3325 +pip/_vendor/colorama/tests/__init__.py,sha256=MkgPAEzGQd-Rq0w0PZXSX2LadRWhUECcisJY8lSrm4Q,75 +pip/_vendor/colorama/tests/__pycache__/__init__.cpython-310.pyc,, +pip/_vendor/colorama/tests/__pycache__/ansi_test.cpython-310.pyc,, +pip/_vendor/colorama/tests/__pycache__/ansitowin32_test.cpython-310.pyc,, +pip/_vendor/colorama/tests/__pycache__/initialise_test.cpython-310.pyc,, +pip/_vendor/colorama/tests/__pycache__/isatty_test.cpython-310.pyc,, +pip/_vendor/colorama/tests/__pycache__/utils.cpython-310.pyc,, +pip/_vendor/colorama/tests/__pycache__/winterm_test.cpython-310.pyc,, +pip/_vendor/colorama/tests/ansi_test.py,sha256=FeViDrUINIZcr505PAxvU4AjXz1asEiALs9GXMhwRaE,2839 +pip/_vendor/colorama/tests/ansitowin32_test.py,sha256=RN7AIhMJ5EqDsYaCjVo-o4u8JzDD4ukJbmevWKS70rY,10678 +pip/_vendor/colorama/tests/initialise_test.py,sha256=BbPy-XfyHwJ6zKozuQOvNvQZzsx9vdb_0bYXn7hsBTc,6741 +pip/_vendor/colorama/tests/isatty_test.py,sha256=Pg26LRpv0yQDB5Ac-sxgVXG7hsA1NYvapFgApZfYzZg,1866 +pip/_vendor/colorama/tests/utils.py,sha256=1IIRylG39z5-dzq09R_ngufxyPZxgldNbrxKxUGwGKE,1079 +pip/_vendor/colorama/tests/winterm_test.py,sha256=qoWFPEjym5gm2RuMwpf3pOis3a5r_PJZFCzK254JL8A,3709 +pip/_vendor/colorama/win32.py,sha256=YQOKwMTwtGBbsY4dL5HYTvwTeP9wIQra5MvPNddpxZs,6181 +pip/_vendor/colorama/winterm.py,sha256=XCQFDHjPi6AHYNdZwy0tA02H-Jh48Jp-HvCjeLeLp3U,7134 +pip/_vendor/distlib/__init__.py,sha256=acgfseOC55dNrVAzaBKpUiH3Z6V7Q1CaxsiQ3K7pC-E,581 +pip/_vendor/distlib/__pycache__/__init__.cpython-310.pyc,, +pip/_vendor/distlib/__pycache__/compat.cpython-310.pyc,, +pip/_vendor/distlib/__pycache__/database.cpython-310.pyc,, +pip/_vendor/distlib/__pycache__/index.cpython-310.pyc,, +pip/_vendor/distlib/__pycache__/locators.cpython-310.pyc,, +pip/_vendor/distlib/__pycache__/manifest.cpython-310.pyc,, +pip/_vendor/distlib/__pycache__/markers.cpython-310.pyc,, +pip/_vendor/distlib/__pycache__/metadata.cpython-310.pyc,, +pip/_vendor/distlib/__pycache__/resources.cpython-310.pyc,, +pip/_vendor/distlib/__pycache__/scripts.cpython-310.pyc,, +pip/_vendor/distlib/__pycache__/util.cpython-310.pyc,, +pip/_vendor/distlib/__pycache__/version.cpython-310.pyc,, +pip/_vendor/distlib/__pycache__/wheel.cpython-310.pyc,, +pip/_vendor/distlib/compat.py,sha256=tfoMrj6tujk7G4UC2owL6ArgDuCKabgBxuJRGZSmpko,41259 +pip/_vendor/distlib/database.py,sha256=o_mw0fAr93NDAHHHfqG54Y1Hi9Rkfrp2BX15XWZYK50,51697 +pip/_vendor/distlib/index.py,sha256=HFiDG7LMoaBs829WuotrfIwcErOOExUOR_AeBtw_TCU,20834 +pip/_vendor/distlib/locators.py,sha256=wNzG-zERzS_XGls-nBPVVyLRHa2skUlkn0-5n0trMWA,51991 +pip/_vendor/distlib/manifest.py,sha256=nQEhYmgoreaBZzyFzwYsXxJARu3fo4EkunU163U16iE,14811 +pip/_vendor/distlib/markers.py,sha256=TpHHHLgkzyT7YHbwj-2i6weRaq-Ivy2-MUnrDkjau-U,5058 +pip/_vendor/distlib/metadata.py,sha256=g_DIiu8nBXRzA-mWPRpatHGbmFZqaFoss7z9TG7QSUU,39801 +pip/_vendor/distlib/resources.py,sha256=LwbPksc0A1JMbi6XnuPdMBUn83X7BPuFNWqPGEKI698,10820 +pip/_vendor/distlib/scripts.py,sha256=BmkTKmiTk4m2cj-iueliatwz3ut_9SsABBW51vnQnZU,18102 +pip/_vendor/distlib/t32.exe,sha256=a0GV5kCoWsMutvliiCKmIgV98eRZ33wXoS-XrqvJQVs,97792 +pip/_vendor/distlib/t64-arm.exe,sha256=68TAa32V504xVBnufojh0PcenpR3U4wAqTqf-MZqbPw,182784 +pip/_vendor/distlib/t64.exe,sha256=gaYY8hy4fbkHYTTnA4i26ct8IQZzkBG2pRdy0iyuBrc,108032 +pip/_vendor/distlib/util.py,sha256=31dPXn3Rfat0xZLeVoFpuniyhe6vsbl9_QN-qd9Lhlk,66262 +pip/_vendor/distlib/version.py,sha256=WG__LyAa2GwmA6qSoEJtvJE8REA1LZpbSizy8WvhJLk,23513 +pip/_vendor/distlib/w32.exe,sha256=R4csx3-OGM9kL4aPIzQKRo5TfmRSHZo6QWyLhDhNBks,91648 +pip/_vendor/distlib/w64-arm.exe,sha256=xdyYhKj0WDcVUOCb05blQYvzdYIKMbmJn2SZvzkcey4,168448 +pip/_vendor/distlib/w64.exe,sha256=ejGf-rojoBfXseGLpya6bFTFPWRG21X5KvU8J5iU-K0,101888 +pip/_vendor/distlib/wheel.py,sha256=Rgqs658VsJ3R2845qwnZD8XQryV2CzWw2mghwLvxxsI,43898 +pip/_vendor/distro/__init__.py,sha256=2fHjF-SfgPvjyNZ1iHh_wjqWdR_Yo5ODHwZC0jLBPhc,981 +pip/_vendor/distro/__main__.py,sha256=bu9d3TifoKciZFcqRBuygV3GSuThnVD_m2IK4cz96Vs,64 +pip/_vendor/distro/__pycache__/__init__.cpython-310.pyc,, +pip/_vendor/distro/__pycache__/__main__.cpython-310.pyc,, +pip/_vendor/distro/__pycache__/distro.cpython-310.pyc,, +pip/_vendor/distro/distro.py,sha256=UZO1LjIhtFCMdlbiz39gj3raV-Amf3SBwzGzfApiMHw,49330 +pip/_vendor/idna/__init__.py,sha256=KJQN1eQBr8iIK5SKrJ47lXvxG0BJ7Lm38W4zT0v_8lk,849 +pip/_vendor/idna/__pycache__/__init__.cpython-310.pyc,, +pip/_vendor/idna/__pycache__/codec.cpython-310.pyc,, +pip/_vendor/idna/__pycache__/compat.cpython-310.pyc,, +pip/_vendor/idna/__pycache__/core.cpython-310.pyc,, +pip/_vendor/idna/__pycache__/idnadata.cpython-310.pyc,, +pip/_vendor/idna/__pycache__/intranges.cpython-310.pyc,, +pip/_vendor/idna/__pycache__/package_data.cpython-310.pyc,, +pip/_vendor/idna/__pycache__/uts46data.cpython-310.pyc,, +pip/_vendor/idna/codec.py,sha256=6ly5odKfqrytKT9_7UrlGklHnf1DSK2r9C6cSM4sa28,3374 +pip/_vendor/idna/compat.py,sha256=0_sOEUMT4CVw9doD3vyRhX80X19PwqFoUBs7gWsFME4,321 +pip/_vendor/idna/core.py,sha256=1JxchwKzkxBSn7R_oCE12oBu3eVux0VzdxolmIad24M,12950 +pip/_vendor/idna/idnadata.py,sha256=xUjqKqiJV8Ho_XzBpAtv5JFoVPSupK-SUXvtjygUHqw,44375 +pip/_vendor/idna/intranges.py,sha256=YBr4fRYuWH7kTKS2tXlFjM24ZF1Pdvcir-aywniInqg,1881 +pip/_vendor/idna/package_data.py,sha256=C_jHJzmX8PI4xq0jpzmcTMxpb5lDsq4o5VyxQzlVrZE,21 +pip/_vendor/idna/uts46data.py,sha256=zvjZU24s58_uAS850Mcd0NnD0X7_gCMAMjzWNIeUJdc,206539 +pip/_vendor/msgpack/__init__.py,sha256=NryGaKLDk_Egd58ZxXpnuI7OWO27AXz7S6CBFRM3sAY,1132 +pip/_vendor/msgpack/__pycache__/__init__.cpython-310.pyc,, +pip/_vendor/msgpack/__pycache__/exceptions.cpython-310.pyc,, +pip/_vendor/msgpack/__pycache__/ext.cpython-310.pyc,, +pip/_vendor/msgpack/__pycache__/fallback.cpython-310.pyc,, +pip/_vendor/msgpack/exceptions.py,sha256=dCTWei8dpkrMsQDcjQk74ATl9HsIBH0ybt8zOPNqMYc,1081 +pip/_vendor/msgpack/ext.py,sha256=TuldJPkYu8Wo_Xh0tFGL2l06-gY88NSR8tOje9fo2Wg,6080 +pip/_vendor/msgpack/fallback.py,sha256=OORDn86-fHBPlu-rPlMdM10KzkH6S_Rx9CHN1b7o4cg,34557 +pip/_vendor/packaging/__about__.py,sha256=ugASIO2w1oUyH8_COqQ2X_s0rDhjbhQC3yJocD03h2c,661 +pip/_vendor/packaging/__init__.py,sha256=b9Kk5MF7KxhhLgcDmiUWukN-LatWFxPdNug0joPhHSk,497 +pip/_vendor/packaging/__pycache__/__about__.cpython-310.pyc,, +pip/_vendor/packaging/__pycache__/__init__.cpython-310.pyc,, +pip/_vendor/packaging/__pycache__/_manylinux.cpython-310.pyc,, +pip/_vendor/packaging/__pycache__/_musllinux.cpython-310.pyc,, +pip/_vendor/packaging/__pycache__/_structures.cpython-310.pyc,, +pip/_vendor/packaging/__pycache__/markers.cpython-310.pyc,, +pip/_vendor/packaging/__pycache__/requirements.cpython-310.pyc,, +pip/_vendor/packaging/__pycache__/specifiers.cpython-310.pyc,, +pip/_vendor/packaging/__pycache__/tags.cpython-310.pyc,, +pip/_vendor/packaging/__pycache__/utils.cpython-310.pyc,, +pip/_vendor/packaging/__pycache__/version.cpython-310.pyc,, +pip/_vendor/packaging/_manylinux.py,sha256=XcbiXB-qcjv3bcohp6N98TMpOP4_j3m-iOA8ptK2GWY,11488 +pip/_vendor/packaging/_musllinux.py,sha256=_KGgY_qc7vhMGpoqss25n2hiLCNKRtvz9mCrS7gkqyc,4378 +pip/_vendor/packaging/_structures.py,sha256=q3eVNmbWJGG_S0Dit_S3Ao8qQqz_5PYTXFAKBZe5yr4,1431 +pip/_vendor/packaging/markers.py,sha256=AJBOcY8Oq0kYc570KuuPTkvuqjAlhufaE2c9sCUbm64,8487 +pip/_vendor/packaging/requirements.py,sha256=NtDlPBtojpn1IUC85iMjPNsUmufjpSlwnNA-Xb4m5NA,4676 +pip/_vendor/packaging/specifiers.py,sha256=LRQ0kFsHrl5qfcFNEEJrIFYsnIHQUJXY9fIsakTrrqE,30110 +pip/_vendor/packaging/tags.py,sha256=lmsnGNiJ8C4D_Pf9PbM0qgbZvD9kmB9lpZBQUZa3R_Y,15699 +pip/_vendor/packaging/utils.py,sha256=dJjeat3BS-TYn1RrUFVwufUMasbtzLfYRoy_HXENeFQ,4200 +pip/_vendor/packaging/version.py,sha256=_fLRNrFrxYcHVfyo8vk9j8s6JM8N_xsSxVFr6RJyco8,14665 +pip/_vendor/pkg_resources/__init__.py,sha256=NnpQ3g6BCHzpMgOR_OLBmYtniY4oOzdKpwqghfq_6ug,108287 +pip/_vendor/pkg_resources/__pycache__/__init__.cpython-310.pyc,, +pip/_vendor/pkg_resources/__pycache__/py31compat.cpython-310.pyc,, +pip/_vendor/pkg_resources/py31compat.py,sha256=CRk8fkiPRDLsbi5pZcKsHI__Pbmh_94L8mr9Qy9Ab2U,562 +pip/_vendor/platformdirs/__init__.py,sha256=9iY4Z8iJDZB0djln6zHHwrPVWpB54TCygcnh--MujU0,12936 +pip/_vendor/platformdirs/__main__.py,sha256=ZmsnTxEOxtTvwa-Y_Vfab_JN3X4XCVeN8X0yyy9-qnc,1176 +pip/_vendor/platformdirs/__pycache__/__init__.cpython-310.pyc,, +pip/_vendor/platformdirs/__pycache__/__main__.cpython-310.pyc,, +pip/_vendor/platformdirs/__pycache__/android.cpython-310.pyc,, +pip/_vendor/platformdirs/__pycache__/api.cpython-310.pyc,, +pip/_vendor/platformdirs/__pycache__/macos.cpython-310.pyc,, +pip/_vendor/platformdirs/__pycache__/unix.cpython-310.pyc,, +pip/_vendor/platformdirs/__pycache__/version.cpython-310.pyc,, +pip/_vendor/platformdirs/__pycache__/windows.cpython-310.pyc,, +pip/_vendor/platformdirs/android.py,sha256=GKizhyS7ESRiU67u8UnBJLm46goau9937EchXWbPBlk,4068 +pip/_vendor/platformdirs/api.py,sha256=MXKHXOL3eh_-trSok-JUTjAR_zjmmKF3rjREVABjP8s,4910 +pip/_vendor/platformdirs/macos.py,sha256=-3UXQewbT0yMhMdkzRXfXGAntmLIH7Qt4a9Hlf8I5_Y,2655 +pip/_vendor/platformdirs/unix.py,sha256=P-WQjSSieE38DXjMDa1t4XHnKJQ5idEaKT0PyXwm8KQ,6911 +pip/_vendor/platformdirs/version.py,sha256=qaN-fw_htIgKUVXoAuAEVgKxQu3tZ9qE2eiKkWIS7LA,160 +pip/_vendor/platformdirs/windows.py,sha256=LOrXLgI0CjQldDo2zhOZYGYZ6g4e_cJOCB_pF9aMRWQ,6596 +pip/_vendor/pygments/__init__.py,sha256=5oLcMLXD0cTG8YcHBPITtK1fS0JBASILEvEnWkTezgE,2999 +pip/_vendor/pygments/__main__.py,sha256=p0_rz3JZmNZMNZBOqDojaEx1cr9wmA9FQZX_TYl74lQ,353 +pip/_vendor/pygments/__pycache__/__init__.cpython-310.pyc,, +pip/_vendor/pygments/__pycache__/__main__.cpython-310.pyc,, +pip/_vendor/pygments/__pycache__/cmdline.cpython-310.pyc,, +pip/_vendor/pygments/__pycache__/console.cpython-310.pyc,, +pip/_vendor/pygments/__pycache__/filter.cpython-310.pyc,, +pip/_vendor/pygments/__pycache__/formatter.cpython-310.pyc,, +pip/_vendor/pygments/__pycache__/lexer.cpython-310.pyc,, +pip/_vendor/pygments/__pycache__/modeline.cpython-310.pyc,, +pip/_vendor/pygments/__pycache__/plugin.cpython-310.pyc,, +pip/_vendor/pygments/__pycache__/regexopt.cpython-310.pyc,, +pip/_vendor/pygments/__pycache__/scanner.cpython-310.pyc,, +pip/_vendor/pygments/__pycache__/sphinxext.cpython-310.pyc,, +pip/_vendor/pygments/__pycache__/style.cpython-310.pyc,, +pip/_vendor/pygments/__pycache__/token.cpython-310.pyc,, +pip/_vendor/pygments/__pycache__/unistring.cpython-310.pyc,, +pip/_vendor/pygments/__pycache__/util.cpython-310.pyc,, +pip/_vendor/pygments/cmdline.py,sha256=rc0fah4eknRqFgn1wKNEwkq0yWnSqYOGaA4PaIeOxVY,23685 +pip/_vendor/pygments/console.py,sha256=hQfqCFuOlGk7DW2lPQYepsw-wkOH1iNt9ylNA1eRymM,1697 +pip/_vendor/pygments/filter.py,sha256=NglMmMPTRRv-zuRSE_QbWid7JXd2J4AvwjCW2yWALXU,1938 +pip/_vendor/pygments/filters/__init__.py,sha256=b5YuXB9rampSy2-cMtKxGQoMDfrG4_DcvVwZrzTlB6w,40386 +pip/_vendor/pygments/filters/__pycache__/__init__.cpython-310.pyc,, +pip/_vendor/pygments/formatter.py,sha256=6-TS2Y8pUMeWIUolWwr1O8ruC-U6HydWDwOdbAiJgJQ,2917 +pip/_vendor/pygments/formatters/__init__.py,sha256=YTqGeHS17fNXCLMZpf7oCxBCKLB9YLsZ8IAsjGhawyg,4810 +pip/_vendor/pygments/formatters/__pycache__/__init__.cpython-310.pyc,, +pip/_vendor/pygments/formatters/__pycache__/_mapping.cpython-310.pyc,, +pip/_vendor/pygments/formatters/__pycache__/bbcode.cpython-310.pyc,, +pip/_vendor/pygments/formatters/__pycache__/groff.cpython-310.pyc,, +pip/_vendor/pygments/formatters/__pycache__/html.cpython-310.pyc,, +pip/_vendor/pygments/formatters/__pycache__/img.cpython-310.pyc,, +pip/_vendor/pygments/formatters/__pycache__/irc.cpython-310.pyc,, +pip/_vendor/pygments/formatters/__pycache__/latex.cpython-310.pyc,, +pip/_vendor/pygments/formatters/__pycache__/other.cpython-310.pyc,, +pip/_vendor/pygments/formatters/__pycache__/pangomarkup.cpython-310.pyc,, +pip/_vendor/pygments/formatters/__pycache__/rtf.cpython-310.pyc,, +pip/_vendor/pygments/formatters/__pycache__/svg.cpython-310.pyc,, +pip/_vendor/pygments/formatters/__pycache__/terminal.cpython-310.pyc,, +pip/_vendor/pygments/formatters/__pycache__/terminal256.cpython-310.pyc,, +pip/_vendor/pygments/formatters/_mapping.py,sha256=fCZgvsM6UEuZUG7J6lr47eVss5owKd_JyaNbDfxeqmQ,4104 +pip/_vendor/pygments/formatters/bbcode.py,sha256=JrL4ITjN-KzPcuQpPMBf1pm33eW2sDUNr8WzSoAJsJA,3314 +pip/_vendor/pygments/formatters/groff.py,sha256=xrOFoLbafSA9uHsSLRogy79_Zc4GWJ8tMK2hCdTJRsw,5086 +pip/_vendor/pygments/formatters/html.py,sha256=QNt9prPgxmbKx2M-nfDwoR1bIg06-sNouQuWnE434Wc,35441 +pip/_vendor/pygments/formatters/img.py,sha256=h75Y7IRZLZxDEIwyoOsdRLTwm7kLVPbODKkgEiJ0iKI,21938 +pip/_vendor/pygments/formatters/irc.py,sha256=iwk5tDJOxbCV64SCmOFyvk__x6RD60ay0nUn7ko9n7U,5871 +pip/_vendor/pygments/formatters/latex.py,sha256=thPbytJCIs2AUXsO3NZwqKtXJ-upOlcXP4CXsx94G4w,19351 +pip/_vendor/pygments/formatters/other.py,sha256=PczqK1Rms43lz6iucOLPeBMxIncPKOGBt-195w1ynII,5073 +pip/_vendor/pygments/formatters/pangomarkup.py,sha256=ZZzMsKJKXrsDniFeMTkIpe7aQ4VZYRHu0idWmSiUJ2U,2212 +pip/_vendor/pygments/formatters/rtf.py,sha256=abrKlWjipBkQvhIICxtjYTUNv6WME0iJJObFvqVuudE,5014 +pip/_vendor/pygments/formatters/svg.py,sha256=6MM9YyO8NhU42RTQfTWBiagWMnsf9iG5gwhqSriHORE,7335 +pip/_vendor/pygments/formatters/terminal.py,sha256=NpEGvwkC6LgMLQTjVzGrJXji3XcET1sb5JCunSCzoRo,4674 +pip/_vendor/pygments/formatters/terminal256.py,sha256=4v4OVizvsxtwWBpIy_Po30zeOzE5oJg_mOc1-rCjMDk,11753 +pip/_vendor/pygments/lexer.py,sha256=ZPB_TGn_qzrXodRFwEdPzzJk6LZBo9BlfSy3lacc6zg,32005 +pip/_vendor/pygments/lexers/__init__.py,sha256=8d80-XfL5UKDCC1wRD1a_ZBZDkZ2HOe7Zul8SsnNYFE,11174 +pip/_vendor/pygments/lexers/__pycache__/__init__.cpython-310.pyc,, +pip/_vendor/pygments/lexers/__pycache__/_mapping.cpython-310.pyc,, +pip/_vendor/pygments/lexers/__pycache__/python.cpython-310.pyc,, +pip/_vendor/pygments/lexers/_mapping.py,sha256=zEiCV5FPiBioMJQJjw9kk7IJ5Y9GwknS4VJPYlcNchs,70232 +pip/_vendor/pygments/lexers/python.py,sha256=gZROs9iNSOA18YyVghP1cUCD0OwYZ04a6PCwgSOCeSA,53376 +pip/_vendor/pygments/modeline.py,sha256=gIbMSYrjSWPk0oATz7W9vMBYkUyTK2OcdVyKjioDRvA,986 +pip/_vendor/pygments/plugin.py,sha256=5rPxEoB_89qQMpOs0nI4KyLOzAHNlbQiwEMOKxqNmv8,2591 +pip/_vendor/pygments/regexopt.py,sha256=c6xcXGpGgvCET_3VWawJJqAnOp0QttFpQEdOPNY2Py0,3072 +pip/_vendor/pygments/scanner.py,sha256=F2T2G6cpkj-yZtzGQr-sOBw5w5-96UrJWveZN6va2aM,3092 +pip/_vendor/pygments/sphinxext.py,sha256=F8L0211sPnXaiWutN0lkSUajWBwlgDMIEFFAbMWOvZY,4630 +pip/_vendor/pygments/style.py,sha256=RRnussX1YiK9Z7HipIvKorImxu3-HnkdpPCO4u925T0,6257 +pip/_vendor/pygments/styles/__init__.py,sha256=iZDZ7PBKb55SpGlE1--cx9cbmWx5lVTH4bXO87t2Vok,3419 +pip/_vendor/pygments/styles/__pycache__/__init__.cpython-310.pyc,, +pip/_vendor/pygments/token.py,sha256=vA2yNHGJBHfq4jNQSah7C9DmIOp34MmYHPA8P-cYAHI,6184 +pip/_vendor/pygments/unistring.py,sha256=gP3gK-6C4oAFjjo9HvoahsqzuV4Qz0jl0E0OxfDerHI,63187 +pip/_vendor/pygments/util.py,sha256=KgwpWWC3By5AiNwxGTI7oI9aXupH2TyZWukafBJe0Mg,9110 +pip/_vendor/pyparsing/__init__.py,sha256=ZPdI7pPo4IYXcABw-51AcqOzsxVvDtqnQbyn_qYWZvo,9171 +pip/_vendor/pyparsing/__pycache__/__init__.cpython-310.pyc,, +pip/_vendor/pyparsing/__pycache__/actions.cpython-310.pyc,, +pip/_vendor/pyparsing/__pycache__/common.cpython-310.pyc,, +pip/_vendor/pyparsing/__pycache__/core.cpython-310.pyc,, +pip/_vendor/pyparsing/__pycache__/exceptions.cpython-310.pyc,, +pip/_vendor/pyparsing/__pycache__/helpers.cpython-310.pyc,, +pip/_vendor/pyparsing/__pycache__/results.cpython-310.pyc,, +pip/_vendor/pyparsing/__pycache__/testing.cpython-310.pyc,, +pip/_vendor/pyparsing/__pycache__/unicode.cpython-310.pyc,, +pip/_vendor/pyparsing/__pycache__/util.cpython-310.pyc,, +pip/_vendor/pyparsing/actions.py,sha256=wU9i32e0y1ymxKE3OUwSHO-SFIrt1h_wv6Ws0GQjpNU,6426 +pip/_vendor/pyparsing/common.py,sha256=lFL97ooIeR75CmW5hjURZqwDCTgruqltcTCZ-ulLO2Q,12936 +pip/_vendor/pyparsing/core.py,sha256=AzTm1KFT1FIhiw2zvXZJmrpQoAwB0wOmeDCiR6SYytw,213344 +pip/_vendor/pyparsing/diagram/__init__.py,sha256=KW0PV_TvWKnL7jysz0pQbZ24nzWWu2ZfNaeyUIIywIg,23685 +pip/_vendor/pyparsing/diagram/__pycache__/__init__.cpython-310.pyc,, +pip/_vendor/pyparsing/exceptions.py,sha256=3LbSafD32NYb1Tzt85GHNkhEAU1eZkTtNSk24cPMemo,9023 +pip/_vendor/pyparsing/helpers.py,sha256=QpUOjW0-psvueMwWb9bQpU2noqKCv98_wnw1VSzSdVo,39129 +pip/_vendor/pyparsing/results.py,sha256=HgNvWVXBdQP-Q6PtJfoCEeOJk2nwEvG-2KVKC5sGA30,25341 +pip/_vendor/pyparsing/testing.py,sha256=7tu4Abp4uSeJV0N_yEPRmmNUhpd18ZQP3CrX41DM814,13402 +pip/_vendor/pyparsing/unicode.py,sha256=fwuhMj30SQ165Cv7HJpu-rSxGbRm93kN9L4Ei7VGc1Y,10787 +pip/_vendor/pyparsing/util.py,sha256=kq772O5YSeXOSdP-M31EWpbH_ayj7BMHImBYo9xPD5M,6805 +pip/_vendor/pyproject_hooks/__init__.py,sha256=kCehmy0UaBa9oVMD7ZIZrnswfnP3LXZ5lvnNJAL5JBM,491 +pip/_vendor/pyproject_hooks/__pycache__/__init__.cpython-310.pyc,, +pip/_vendor/pyproject_hooks/__pycache__/_compat.cpython-310.pyc,, +pip/_vendor/pyproject_hooks/__pycache__/_impl.cpython-310.pyc,, +pip/_vendor/pyproject_hooks/_compat.py,sha256=by6evrYnqkisiM-MQcvOKs5bgDMzlOSgZqRHNqf04zE,138 +pip/_vendor/pyproject_hooks/_impl.py,sha256=61GJxzQip0IInhuO69ZI5GbNQ82XEDUB_1Gg5_KtUoc,11920 +pip/_vendor/pyproject_hooks/_in_process/__init__.py,sha256=9gQATptbFkelkIy0OfWFEACzqxXJMQDWCH9rBOAZVwQ,546 +pip/_vendor/pyproject_hooks/_in_process/__pycache__/__init__.cpython-310.pyc,, +pip/_vendor/pyproject_hooks/_in_process/__pycache__/_in_process.cpython-310.pyc,, +pip/_vendor/pyproject_hooks/_in_process/_in_process.py,sha256=m2b34c917IW5o-Q_6TYIHlsK9lSUlNiyrITTUH_zwew,10927 +pip/_vendor/requests/__init__.py,sha256=64HgJ8cke-XyNrj1ErwNq0F9SqyAThUTh5lV6m7-YkI,5178 +pip/_vendor/requests/__pycache__/__init__.cpython-310.pyc,, +pip/_vendor/requests/__pycache__/__version__.cpython-310.pyc,, +pip/_vendor/requests/__pycache__/_internal_utils.cpython-310.pyc,, +pip/_vendor/requests/__pycache__/adapters.cpython-310.pyc,, +pip/_vendor/requests/__pycache__/api.cpython-310.pyc,, +pip/_vendor/requests/__pycache__/auth.cpython-310.pyc,, +pip/_vendor/requests/__pycache__/certs.cpython-310.pyc,, +pip/_vendor/requests/__pycache__/compat.cpython-310.pyc,, +pip/_vendor/requests/__pycache__/cookies.cpython-310.pyc,, +pip/_vendor/requests/__pycache__/exceptions.cpython-310.pyc,, +pip/_vendor/requests/__pycache__/help.cpython-310.pyc,, +pip/_vendor/requests/__pycache__/hooks.cpython-310.pyc,, +pip/_vendor/requests/__pycache__/models.cpython-310.pyc,, +pip/_vendor/requests/__pycache__/packages.cpython-310.pyc,, +pip/_vendor/requests/__pycache__/sessions.cpython-310.pyc,, +pip/_vendor/requests/__pycache__/status_codes.cpython-310.pyc,, +pip/_vendor/requests/__pycache__/structures.cpython-310.pyc,, +pip/_vendor/requests/__pycache__/utils.cpython-310.pyc,, +pip/_vendor/requests/__version__.py,sha256=h48zn-oFukaXrYHocdadp_hIszWyd_PGrS8Eiii6aoc,435 +pip/_vendor/requests/_internal_utils.py,sha256=aSPlF4uDhtfKxEayZJJ7KkAxtormeTfpwKSBSwtmAUw,1397 +pip/_vendor/requests/adapters.py,sha256=GFEz5koZaMZD86v0SHXKVB5SE9MgslEjkCQzldkNwVM,21443 +pip/_vendor/requests/api.py,sha256=dyvkDd5itC9z2g0wHl_YfD1yf6YwpGWLO7__8e21nks,6377 +pip/_vendor/requests/auth.py,sha256=h-HLlVx9j8rKV5hfSAycP2ApOSglTz77R0tz7qCbbEE,10187 +pip/_vendor/requests/certs.py,sha256=PVPooB0jP5hkZEULSCwC074532UFbR2Ptgu0I5zwmCs,575 +pip/_vendor/requests/compat.py,sha256=IhK9quyX0RRuWTNcg6d2JGSAOUbM6mym2p_2XjLTwf4,1286 +pip/_vendor/requests/cookies.py,sha256=kD3kNEcCj-mxbtf5fJsSaT86eGoEYpD3X0CSgpzl7BM,18560 +pip/_vendor/requests/exceptions.py,sha256=FA-_kVwBZ2jhXauRctN_ewHVK25b-fj0Azyz1THQ0Kk,3823 +pip/_vendor/requests/help.py,sha256=FnAAklv8MGm_qb2UilDQgS6l0cUttiCFKUjx0zn2XNA,3879 +pip/_vendor/requests/hooks.py,sha256=CiuysiHA39V5UfcCBXFIx83IrDpuwfN9RcTUgv28ftQ,733 +pip/_vendor/requests/models.py,sha256=dDZ-iThotky-Noq9yy97cUEJhr3wnY6mv-xR_ePg_lk,35288 +pip/_vendor/requests/packages.py,sha256=njJmVifY4aSctuW3PP5EFRCxjEwMRDO6J_feG2dKWsI,695 +pip/_vendor/requests/sessions.py,sha256=KUqJcRRLovNefUs7ScOXSUVCcfSayTFWtbiJ7gOSlTI,30180 +pip/_vendor/requests/status_codes.py,sha256=FvHmT5uH-_uimtRz5hH9VCbt7VV-Nei2J9upbej6j8g,4235 +pip/_vendor/requests/structures.py,sha256=-IbmhVz06S-5aPSZuUthZ6-6D9XOjRuTXHOabY041XM,2912 +pip/_vendor/requests/utils.py,sha256=0gzSOcx9Ya4liAbHnHuwt4jM78lzCZZoDFgkmsInNUg,33240 +pip/_vendor/resolvelib/__init__.py,sha256=UL-B2BDI0_TRIqkfGwLHKLxY-LjBlomz7941wDqzB1I,537 +pip/_vendor/resolvelib/__pycache__/__init__.cpython-310.pyc,, +pip/_vendor/resolvelib/__pycache__/providers.cpython-310.pyc,, +pip/_vendor/resolvelib/__pycache__/reporters.cpython-310.pyc,, +pip/_vendor/resolvelib/__pycache__/resolvers.cpython-310.pyc,, +pip/_vendor/resolvelib/__pycache__/structs.cpython-310.pyc,, +pip/_vendor/resolvelib/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_vendor/resolvelib/compat/__pycache__/__init__.cpython-310.pyc,, +pip/_vendor/resolvelib/compat/__pycache__/collections_abc.cpython-310.pyc,, +pip/_vendor/resolvelib/compat/collections_abc.py,sha256=uy8xUZ-NDEw916tugUXm8HgwCGiMO0f-RcdnpkfXfOs,156 +pip/_vendor/resolvelib/providers.py,sha256=roVmFBItQJ0TkhNua65h8LdNny7rmeqVEXZu90QiP4o,5872 +pip/_vendor/resolvelib/reporters.py,sha256=fW91NKf-lK8XN7i6Yd_rczL5QeOT3sc6AKhpaTEnP3E,1583 +pip/_vendor/resolvelib/resolvers.py,sha256=2wYzVGBGerbmcIpH8cFmgSKgLSETz8jmwBMGjCBMHG4,17592 +pip/_vendor/resolvelib/structs.py,sha256=IVIYof6sA_N4ZEiE1C1UhzTX495brCNnyCdgq6CYq28,4794 +pip/_vendor/rich/__init__.py,sha256=dRxjIL-SbFVY0q3IjSMrfgBTHrm1LZDgLOygVBwiYZc,6090 +pip/_vendor/rich/__main__.py,sha256=TT8sb9PTnsnKhhrGuHkLN0jdN0dtKhtPkEr9CidDbPM,8478 +pip/_vendor/rich/__pycache__/__init__.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/__main__.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/_cell_widths.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/_emoji_codes.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/_emoji_replace.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/_export_format.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/_extension.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/_inspect.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/_log_render.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/_loop.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/_null_file.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/_palettes.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/_pick.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/_ratio.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/_spinners.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/_stack.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/_timer.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/_win32_console.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/_windows.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/_windows_renderer.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/_wrap.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/abc.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/align.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/ansi.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/bar.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/box.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/cells.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/color.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/color_triplet.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/columns.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/console.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/constrain.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/containers.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/control.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/default_styles.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/diagnose.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/emoji.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/errors.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/file_proxy.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/filesize.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/highlighter.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/json.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/jupyter.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/layout.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/live.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/live_render.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/logging.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/markup.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/measure.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/padding.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/pager.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/palette.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/panel.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/pretty.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/progress.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/progress_bar.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/prompt.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/protocol.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/region.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/repr.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/rule.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/scope.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/screen.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/segment.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/spinner.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/status.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/style.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/styled.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/syntax.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/table.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/terminal_theme.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/text.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/theme.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/themes.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/traceback.cpython-310.pyc,, +pip/_vendor/rich/__pycache__/tree.cpython-310.pyc,, +pip/_vendor/rich/_cell_widths.py,sha256=2n4EiJi3X9sqIq0O16kUZ_zy6UYMd3xFfChlKfnW1Hc,10096 +pip/_vendor/rich/_emoji_codes.py,sha256=hu1VL9nbVdppJrVoijVshRlcRRe_v3dju3Mmd2sKZdY,140235 +pip/_vendor/rich/_emoji_replace.py,sha256=n-kcetsEUx2ZUmhQrfeMNc-teeGhpuSQ5F8VPBsyvDo,1064 +pip/_vendor/rich/_export_format.py,sha256=nHArqOljIlYn6NruhWsAsh-fHo7oJC3y9BDJyAa-QYQ,2114 +pip/_vendor/rich/_extension.py,sha256=Xt47QacCKwYruzjDi-gOBq724JReDj9Cm9xUi5fr-34,265 +pip/_vendor/rich/_inspect.py,sha256=oZJGw31e64dwXSCmrDnvZbwVb1ZKhWfU8wI3VWohjJk,9695 +pip/_vendor/rich/_log_render.py,sha256=1ByI0PA1ZpxZY3CGJOK54hjlq4X-Bz_boIjIqCd8Kns,3225 +pip/_vendor/rich/_loop.py,sha256=hV_6CLdoPm0va22Wpw4zKqM0RYsz3TZxXj0PoS-9eDQ,1236 +pip/_vendor/rich/_null_file.py,sha256=cTaTCU_xuDXGGa9iqK-kZ0uddZCSvM-RgM2aGMuMiHs,1643 +pip/_vendor/rich/_palettes.py,sha256=cdev1JQKZ0JvlguV9ipHgznTdnvlIzUFDBb0It2PzjI,7063 +pip/_vendor/rich/_pick.py,sha256=evDt8QN4lF5CiwrUIXlOJCntitBCOsI3ZLPEIAVRLJU,423 +pip/_vendor/rich/_ratio.py,sha256=2lLSliL025Y-YMfdfGbutkQDevhcyDqc-DtUYW9mU70,5472 +pip/_vendor/rich/_spinners.py,sha256=U2r1_g_1zSjsjiUdAESc2iAMc3i4ri_S8PYP6kQ5z1I,19919 +pip/_vendor/rich/_stack.py,sha256=-C8OK7rxn3sIUdVwxZBBpeHhIzX0eI-VM3MemYfaXm0,351 +pip/_vendor/rich/_timer.py,sha256=zelxbT6oPFZnNrwWPpc1ktUeAT-Vc4fuFcRZLQGLtMI,417 +pip/_vendor/rich/_win32_console.py,sha256=P0vxI2fcndym1UU1S37XAzQzQnkyY7YqAKmxm24_gug,22820 +pip/_vendor/rich/_windows.py,sha256=dvNl9TmfPzNVxiKk5WDFihErZ5796g2UC9-KGGyfXmk,1926 +pip/_vendor/rich/_windows_renderer.py,sha256=t74ZL3xuDCP3nmTp9pH1L5LiI2cakJuQRQleHCJerlk,2783 +pip/_vendor/rich/_wrap.py,sha256=xfV_9t0Sg6rzimmrDru8fCVmUlalYAcHLDfrJZnbbwQ,1840 +pip/_vendor/rich/abc.py,sha256=ON-E-ZqSSheZ88VrKX2M3PXpFbGEUUZPMa_Af0l-4f0,890 +pip/_vendor/rich/align.py,sha256=FV6_GS-8uhIyViMng3hkIWSFaTgMohK1Oqyjl8I8mGE,10368 +pip/_vendor/rich/ansi.py,sha256=THex7-qjc82-ZRtmDPAYlVEObYOEE_ARB1692Fk-JHs,6819 +pip/_vendor/rich/bar.py,sha256=a7UD303BccRCrEhGjfMElpv5RFYIinaAhAuqYqhUvmw,3264 +pip/_vendor/rich/box.py,sha256=FJ6nI3jD7h2XNFU138bJUt2HYmWOlRbltoCEuIAZhew,9842 +pip/_vendor/rich/cells.py,sha256=zMjFI15wCpgjLR14lHdfFMVC6qMDi5OsKIB0PYZBBMk,4503 +pip/_vendor/rich/color.py,sha256=GTITgffj47On3YK1v_I5T2CPZJGSnyWipPID_YkYXqw,18015 +pip/_vendor/rich/color_triplet.py,sha256=3lhQkdJbvWPoLDO-AnYImAWmJvV5dlgYNCVZ97ORaN4,1054 +pip/_vendor/rich/columns.py,sha256=HUX0KcMm9dsKNi11fTbiM_h2iDtl8ySCaVcxlalEzq8,7131 +pip/_vendor/rich/console.py,sha256=w3tJfrILZpS359wrNqaldGmyk3PEhEmV8Pg2g2GjXWI,97992 +pip/_vendor/rich/constrain.py,sha256=1VIPuC8AgtKWrcncQrjBdYqA3JVWysu6jZo1rrh7c7Q,1288 +pip/_vendor/rich/containers.py,sha256=aKgm5UDHn5Nmui6IJaKdsZhbHClh_X7D-_Wg8Ehrr7s,5497 +pip/_vendor/rich/control.py,sha256=DSkHTUQLorfSERAKE_oTAEUFefZnZp4bQb4q8rHbKws,6630 +pip/_vendor/rich/default_styles.py,sha256=WqVh-RPNEsx0Wxf3fhS_fCn-wVqgJ6Qfo-Zg7CoCsLE,7954 +pip/_vendor/rich/diagnose.py,sha256=an6uouwhKPAlvQhYpNNpGq9EJysfMIOvvCbO3oSoR24,972 +pip/_vendor/rich/emoji.py,sha256=omTF9asaAnsM4yLY94eR_9dgRRSm1lHUszX20D1yYCQ,2501 +pip/_vendor/rich/errors.py,sha256=5pP3Kc5d4QJ_c0KFsxrfyhjiPVe7J1zOqSFbFAzcV-Y,642 +pip/_vendor/rich/file_proxy.py,sha256=4gCbGRXg0rW35Plaf0UVvj3dfENHuzc_n8I_dBqxI7o,1616 +pip/_vendor/rich/filesize.py,sha256=9fTLAPCAwHmBXdRv7KZU194jSgNrRb6Wx7RIoBgqeKY,2508 +pip/_vendor/rich/highlighter.py,sha256=3WW6PACGlq0e3YDjfqiMBQ0dYZwu7pcoFYUgJy01nb0,9585 +pip/_vendor/rich/json.py,sha256=TmeFm96Utaov-Ff5miavBPNo51HRooM8S78HEwrYEjA,5053 +pip/_vendor/rich/jupyter.py,sha256=QyoKoE_8IdCbrtiSHp9TsTSNyTHY0FO5whE7jOTd9UE,3252 +pip/_vendor/rich/layout.py,sha256=RFYL6HdCFsHf9WRpcvi3w-fpj-8O5dMZ8W96VdKNdbI,14007 +pip/_vendor/rich/live.py,sha256=emVaLUua-FKSYqZXmtJJjBIstO99CqMOuA6vMAKVkO0,14172 +pip/_vendor/rich/live_render.py,sha256=zElm3PrfSIvjOce28zETHMIUf9pFYSUA5o0AflgUP64,3667 +pip/_vendor/rich/logging.py,sha256=uB-cB-3Q4bmXDLLpbOWkmFviw-Fde39zyMV6tKJ2WHQ,11903 +pip/_vendor/rich/markup.py,sha256=xzF4uAafiEeEYDJYt_vUnJOGoTU8RrH-PH7WcWYXjCg,8198 +pip/_vendor/rich/measure.py,sha256=HmrIJX8sWRTHbgh8MxEay_83VkqNW_70s8aKP5ZcYI8,5305 +pip/_vendor/rich/padding.py,sha256=kTFGsdGe0os7tXLnHKpwTI90CXEvrceeZGCshmJy5zw,4970 +pip/_vendor/rich/pager.py,sha256=SO_ETBFKbg3n_AgOzXm41Sv36YxXAyI3_R-KOY2_uSc,828 +pip/_vendor/rich/palette.py,sha256=lInvR1ODDT2f3UZMfL1grq7dY_pDdKHw4bdUgOGaM4Y,3396 +pip/_vendor/rich/panel.py,sha256=wGMe40J8KCGgQoM0LyjRErmGIkv2bsYA71RCXThD0xE,10574 +pip/_vendor/rich/pretty.py,sha256=dAbLqSF3jJnyfBLJ7QjQ3B2J-WGyBnAdGXeuBVIyMyA,37414 +pip/_vendor/rich/progress.py,sha256=eg-OURdfZW3n3bib1-zP3SZl6cIm2VZup1pr_96CyLk,59836 +pip/_vendor/rich/progress_bar.py,sha256=cEoBfkc3lLwqba4XKsUpy4vSQKDh2QQ5J2J94-ACFoo,8165 +pip/_vendor/rich/prompt.py,sha256=x0mW-pIPodJM4ry6grgmmLrl8VZp99kqcmdnBe70YYA,11303 +pip/_vendor/rich/protocol.py,sha256=5hHHDDNHckdk8iWH5zEbi-zuIVSF5hbU2jIo47R7lTE,1391 +pip/_vendor/rich/region.py,sha256=rNT9xZrVZTYIXZC0NYn41CJQwYNbR-KecPOxTgQvB8Y,166 +pip/_vendor/rich/repr.py,sha256=eJObQe6_c5pUjRM85sZ2rrW47_iF9HT3Z8DrgVjvOl8,4436 +pip/_vendor/rich/rule.py,sha256=V6AWI0wCb6DB0rvN967FRMlQrdlG7HoZdfEAHyeG8CM,4773 +pip/_vendor/rich/scope.py,sha256=TMUU8qo17thyqQCPqjDLYpg_UU1k5qVd-WwiJvnJVas,2843 +pip/_vendor/rich/screen.py,sha256=YoeReESUhx74grqb0mSSb9lghhysWmFHYhsbMVQjXO8,1591 +pip/_vendor/rich/segment.py,sha256=6XdX0MfL18tUCaUWDWncIqx0wpq3GiaqzhYP779JvRA,24224 +pip/_vendor/rich/spinner.py,sha256=7b8MCleS4fa46HX0AzF98zfu6ZM6fAL0UgYzPOoakF4,4374 +pip/_vendor/rich/status.py,sha256=gJsIXIZeSo3urOyxRUjs6VrhX5CZrA0NxIQ-dxhCnwo,4425 +pip/_vendor/rich/style.py,sha256=odBbAlrgdEbAj7pmtPbQtWJNS8upyNhhy--Ks6KwAKk,26332 +pip/_vendor/rich/styled.py,sha256=eZNnzGrI4ki_54pgY3Oj0T-x3lxdXTYh4_ryDB24wBU,1258 +pip/_vendor/rich/syntax.py,sha256=W1xtdBA1-EVP-weYofKXusUlV5zghCOv1nWMHHfNmiY,34995 +pip/_vendor/rich/table.py,sha256=-WzesL-VJKsaiDU3uyczpJMHy6VCaSewBYJwx8RudI8,39684 +pip/_vendor/rich/terminal_theme.py,sha256=1j5-ufJfnvlAo5Qsi_ACZiXDmwMXzqgmFByObT9-yJY,3370 +pip/_vendor/rich/text.py,sha256=andXaxWW_wBveMiZZpd5viQwucWo7SPopcM3ZCQeO0c,45686 +pip/_vendor/rich/theme.py,sha256=GKNtQhDBZKAzDaY0vQVQQFzbc0uWfFe6CJXA-syT7zQ,3627 +pip/_vendor/rich/themes.py,sha256=0xgTLozfabebYtcJtDdC5QkX5IVUEaviqDUJJh4YVFk,102 +pip/_vendor/rich/traceback.py,sha256=6LkGguCEAxKv8v8xmKfMeYPPJ1UXUEHDv4726To6FiQ,26070 +pip/_vendor/rich/tree.py,sha256=BMbUYNjS9uodNPfvtY_odmU09GA5QzcMbQ5cJZhllQI,9169 +pip/_vendor/six.py,sha256=TOOfQi7nFGfMrIvtdr6wX4wyHH8M7aknmuLfo2cBBrM,34549 +pip/_vendor/tenacity/__init__.py,sha256=rjcWJVq5PcNJNC42rt-TAGGskM-RUEkZbDKu1ra7IPo,18364 +pip/_vendor/tenacity/__pycache__/__init__.cpython-310.pyc,, +pip/_vendor/tenacity/__pycache__/_asyncio.cpython-310.pyc,, +pip/_vendor/tenacity/__pycache__/_utils.cpython-310.pyc,, +pip/_vendor/tenacity/__pycache__/after.cpython-310.pyc,, +pip/_vendor/tenacity/__pycache__/before.cpython-310.pyc,, +pip/_vendor/tenacity/__pycache__/before_sleep.cpython-310.pyc,, +pip/_vendor/tenacity/__pycache__/nap.cpython-310.pyc,, +pip/_vendor/tenacity/__pycache__/retry.cpython-310.pyc,, +pip/_vendor/tenacity/__pycache__/stop.cpython-310.pyc,, +pip/_vendor/tenacity/__pycache__/tornadoweb.cpython-310.pyc,, +pip/_vendor/tenacity/__pycache__/wait.cpython-310.pyc,, +pip/_vendor/tenacity/_asyncio.py,sha256=HEb0BVJEeBJE9P-m9XBxh1KcaF96BwoeqkJCL5sbVcQ,3314 +pip/_vendor/tenacity/_utils.py,sha256=-y68scDcyoqvTJuJJ0GTfjdSCljEYlbCYvgk7nM4NdM,1944 +pip/_vendor/tenacity/after.py,sha256=dlmyxxFy2uqpLXDr838DiEd7jgv2AGthsWHGYcGYsaI,1496 +pip/_vendor/tenacity/before.py,sha256=7XtvRmO0dRWUp8SVn24OvIiGFj8-4OP5muQRUiWgLh0,1376 +pip/_vendor/tenacity/before_sleep.py,sha256=ThyDvqKU5yle_IvYQz_b6Tp6UjUS0PhVp6zgqYl9U6Y,1908 +pip/_vendor/tenacity/nap.py,sha256=fRWvnz1aIzbIq9Ap3gAkAZgDH6oo5zxMrU6ZOVByq0I,1383 +pip/_vendor/tenacity/retry.py,sha256=Cy504Ss3UrRV7lnYgvymF66WD1wJ2dbM869kDcjuDes,7550 +pip/_vendor/tenacity/stop.py,sha256=sKHmHaoSaW6sKu3dTxUVKr1-stVkY7lw4Y9yjZU30zQ,2790 +pip/_vendor/tenacity/tornadoweb.py,sha256=E8lWO2nwe6dJgoB-N2HhQprYLDLB_UdSgFnv-EN6wKE,2145 +pip/_vendor/tenacity/wait.py,sha256=tdLTESRm5E237VHG0SxCDXRa0DHKPKVq285kslHVURc,8011 +pip/_vendor/tomli/__init__.py,sha256=JhUwV66DB1g4Hvt1UQCVMdfCu-IgAV8FXmvDU9onxd4,396 +pip/_vendor/tomli/__pycache__/__init__.cpython-310.pyc,, +pip/_vendor/tomli/__pycache__/_parser.cpython-310.pyc,, +pip/_vendor/tomli/__pycache__/_re.cpython-310.pyc,, +pip/_vendor/tomli/__pycache__/_types.cpython-310.pyc,, +pip/_vendor/tomli/_parser.py,sha256=g9-ENaALS-B8dokYpCuzUFalWlog7T-SIYMjLZSWrtM,22633 +pip/_vendor/tomli/_re.py,sha256=dbjg5ChZT23Ka9z9DHOXfdtSpPwUfdgMXnj8NOoly-w,2943 +pip/_vendor/tomli/_types.py,sha256=-GTG2VUqkpxwMqzmVO4F7ybKddIbAnuAHXfmWQcTi3Q,254 +pip/_vendor/typing_extensions.py,sha256=VKZ_nHsuzDbKOVUY2CTdavwBgfZ2EXRyluZHRzUYAbg,80114 +pip/_vendor/urllib3/__init__.py,sha256=iXLcYiJySn0GNbWOOZDDApgBL1JgP44EZ8i1760S8Mc,3333 +pip/_vendor/urllib3/__pycache__/__init__.cpython-310.pyc,, +pip/_vendor/urllib3/__pycache__/_collections.cpython-310.pyc,, +pip/_vendor/urllib3/__pycache__/_version.cpython-310.pyc,, +pip/_vendor/urllib3/__pycache__/connection.cpython-310.pyc,, +pip/_vendor/urllib3/__pycache__/connectionpool.cpython-310.pyc,, +pip/_vendor/urllib3/__pycache__/exceptions.cpython-310.pyc,, +pip/_vendor/urllib3/__pycache__/fields.cpython-310.pyc,, +pip/_vendor/urllib3/__pycache__/filepost.cpython-310.pyc,, +pip/_vendor/urllib3/__pycache__/poolmanager.cpython-310.pyc,, +pip/_vendor/urllib3/__pycache__/request.cpython-310.pyc,, +pip/_vendor/urllib3/__pycache__/response.cpython-310.pyc,, +pip/_vendor/urllib3/_collections.py,sha256=Rp1mVyBgc_UlAcp6M3at1skJBXR5J43NawRTvW2g_XY,10811 +pip/_vendor/urllib3/_version.py,sha256=JWE--BUVy7--9FsXILONIpQ43irftKGjT9j2H_fdF2M,64 +pip/_vendor/urllib3/connection.py,sha256=8976wL6sGeVMW0JnXvx5mD00yXu87uQjxtB9_VL8dx8,20070 +pip/_vendor/urllib3/connectionpool.py,sha256=vS4UaHLoR9_5aGLXSQ776y_jTxgqqjx0YsjkYksWGOo,39095 +pip/_vendor/urllib3/contrib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_vendor/urllib3/contrib/__pycache__/__init__.cpython-310.pyc,, +pip/_vendor/urllib3/contrib/__pycache__/_appengine_environ.cpython-310.pyc,, +pip/_vendor/urllib3/contrib/__pycache__/appengine.cpython-310.pyc,, +pip/_vendor/urllib3/contrib/__pycache__/ntlmpool.cpython-310.pyc,, +pip/_vendor/urllib3/contrib/__pycache__/pyopenssl.cpython-310.pyc,, +pip/_vendor/urllib3/contrib/__pycache__/securetransport.cpython-310.pyc,, +pip/_vendor/urllib3/contrib/__pycache__/socks.cpython-310.pyc,, +pip/_vendor/urllib3/contrib/_appengine_environ.py,sha256=bDbyOEhW2CKLJcQqAKAyrEHN-aklsyHFKq6vF8ZFsmk,957 +pip/_vendor/urllib3/contrib/_securetransport/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_vendor/urllib3/contrib/_securetransport/__pycache__/__init__.cpython-310.pyc,, +pip/_vendor/urllib3/contrib/_securetransport/__pycache__/bindings.cpython-310.pyc,, +pip/_vendor/urllib3/contrib/_securetransport/__pycache__/low_level.cpython-310.pyc,, +pip/_vendor/urllib3/contrib/_securetransport/bindings.py,sha256=4Xk64qIkPBt09A5q-RIFUuDhNc9mXilVapm7WnYnzRw,17632 +pip/_vendor/urllib3/contrib/_securetransport/low_level.py,sha256=B2JBB2_NRP02xK6DCa1Pa9IuxrPwxzDzZbixQkb7U9M,13922 +pip/_vendor/urllib3/contrib/appengine.py,sha256=VR68eAVE137lxTgjBDwCna5UiBZTOKa01Aj_-5BaCz4,11036 +pip/_vendor/urllib3/contrib/ntlmpool.py,sha256=NlfkW7WMdW8ziqudopjHoW299og1BTWi0IeIibquFwk,4528 +pip/_vendor/urllib3/contrib/pyopenssl.py,sha256=hDJh4MhyY_p-oKlFcYcQaVQRDv6GMmBGuW9yjxyeejM,17081 +pip/_vendor/urllib3/contrib/securetransport.py,sha256=yhZdmVjY6PI6EeFbp7qYOp6-vp1Rkv2NMuOGaEj7pmc,34448 +pip/_vendor/urllib3/contrib/socks.py,sha256=aRi9eWXo9ZEb95XUxef4Z21CFlnnjbEiAo9HOseoMt4,7097 +pip/_vendor/urllib3/exceptions.py,sha256=0Mnno3KHTNfXRfY7638NufOPkUb6mXOm-Lqj-4x2w8A,8217 +pip/_vendor/urllib3/fields.py,sha256=kvLDCg_JmH1lLjUUEY_FLS8UhY7hBvDPuVETbY8mdrM,8579 +pip/_vendor/urllib3/filepost.py,sha256=5b_qqgRHVlL7uLtdAYBzBh-GHmU5AfJVt_2N0XS3PeY,2440 +pip/_vendor/urllib3/packages/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_vendor/urllib3/packages/__pycache__/__init__.cpython-310.pyc,, +pip/_vendor/urllib3/packages/__pycache__/six.cpython-310.pyc,, +pip/_vendor/urllib3/packages/backports/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_vendor/urllib3/packages/backports/__pycache__/__init__.cpython-310.pyc,, +pip/_vendor/urllib3/packages/backports/__pycache__/makefile.cpython-310.pyc,, +pip/_vendor/urllib3/packages/backports/makefile.py,sha256=nbzt3i0agPVP07jqqgjhaYjMmuAi_W5E0EywZivVO8E,1417 +pip/_vendor/urllib3/packages/six.py,sha256=b9LM0wBXv7E7SrbCjAm4wwN-hrH-iNxv18LgWNMMKPo,34665 +pip/_vendor/urllib3/poolmanager.py,sha256=0KOOJECoeLYVjUHvv-0h4Oq3FFQQ2yb-Fnjkbj8gJO0,19786 +pip/_vendor/urllib3/request.py,sha256=ZFSIqX0C6WizixecChZ3_okyu7BEv0lZu1VT0s6h4SM,5985 +pip/_vendor/urllib3/response.py,sha256=fmDJAFkG71uFTn-sVSTh2Iw0WmcXQYqkbRjihvwBjU8,30641 +pip/_vendor/urllib3/util/__init__.py,sha256=JEmSmmqqLyaw8P51gUImZh8Gwg9i1zSe-DoqAitn2nc,1155 +pip/_vendor/urllib3/util/__pycache__/__init__.cpython-310.pyc,, +pip/_vendor/urllib3/util/__pycache__/connection.cpython-310.pyc,, +pip/_vendor/urllib3/util/__pycache__/proxy.cpython-310.pyc,, +pip/_vendor/urllib3/util/__pycache__/queue.cpython-310.pyc,, +pip/_vendor/urllib3/util/__pycache__/request.cpython-310.pyc,, +pip/_vendor/urllib3/util/__pycache__/response.cpython-310.pyc,, +pip/_vendor/urllib3/util/__pycache__/retry.cpython-310.pyc,, +pip/_vendor/urllib3/util/__pycache__/ssl_.cpython-310.pyc,, +pip/_vendor/urllib3/util/__pycache__/ssl_match_hostname.cpython-310.pyc,, +pip/_vendor/urllib3/util/__pycache__/ssltransport.cpython-310.pyc,, +pip/_vendor/urllib3/util/__pycache__/timeout.cpython-310.pyc,, +pip/_vendor/urllib3/util/__pycache__/url.cpython-310.pyc,, +pip/_vendor/urllib3/util/__pycache__/wait.cpython-310.pyc,, +pip/_vendor/urllib3/util/connection.py,sha256=5Lx2B1PW29KxBn2T0xkN1CBgRBa3gGVJBKoQoRogEVk,4901 +pip/_vendor/urllib3/util/proxy.py,sha256=zUvPPCJrp6dOF0N4GAVbOcl6o-4uXKSrGiTkkr5vUS4,1605 +pip/_vendor/urllib3/util/queue.py,sha256=nRgX8_eX-_VkvxoX096QWoz8Ps0QHUAExILCY_7PncM,498 +pip/_vendor/urllib3/util/request.py,sha256=C0OUt2tcU6LRiQJ7YYNP9GvPrSvl7ziIBekQ-5nlBZk,3997 +pip/_vendor/urllib3/util/response.py,sha256=GJpg3Egi9qaJXRwBh5wv-MNuRWan5BIu40oReoxWP28,3510 +pip/_vendor/urllib3/util/retry.py,sha256=4laWh0HpwGijLiBmdBIYtbhYekQnNzzhx2W9uys0RHA,22003 +pip/_vendor/urllib3/util/ssl_.py,sha256=X4-AqW91aYPhPx6-xbf66yHFQKbqqfC_5Zt4WkLX1Hc,17177 +pip/_vendor/urllib3/util/ssl_match_hostname.py,sha256=Ir4cZVEjmAk8gUAIHWSi7wtOO83UCYABY2xFD1Ql_WA,5758 +pip/_vendor/urllib3/util/ssltransport.py,sha256=NA-u5rMTrDFDFC8QzRKUEKMG0561hOD4qBTr3Z4pv6E,6895 +pip/_vendor/urllib3/util/timeout.py,sha256=QSbBUNOB9yh6AnDn61SrLQ0hg5oz0I9-uXEG91AJuIg,10003 +pip/_vendor/urllib3/util/url.py,sha256=HLCLEKt8D-QMioTNbneZSzGTGyUkns4w_lSJP1UzE2E,14298 +pip/_vendor/urllib3/util/wait.py,sha256=fOX0_faozG2P7iVojQoE1mbydweNyTcm-hXEfFrTtLI,5403 +pip/_vendor/vendor.txt,sha256=3i3Zr7_kRDD9UEva0I8YOMroCZ8xuZ9OWd_Q4jmazqE,476 +pip/_vendor/webencodings/__init__.py,sha256=qOBJIuPy_4ByYH6W_bNgJF-qYQ2DoU-dKsDu5yRWCXg,10579 +pip/_vendor/webencodings/__pycache__/__init__.cpython-310.pyc,, +pip/_vendor/webencodings/__pycache__/labels.cpython-310.pyc,, +pip/_vendor/webencodings/__pycache__/mklabels.cpython-310.pyc,, +pip/_vendor/webencodings/__pycache__/tests.cpython-310.pyc,, +pip/_vendor/webencodings/__pycache__/x_user_defined.cpython-310.pyc,, +pip/_vendor/webencodings/labels.py,sha256=4AO_KxTddqGtrL9ns7kAPjb0CcN6xsCIxbK37HY9r3E,8979 +pip/_vendor/webencodings/mklabels.py,sha256=GYIeywnpaLnP0GSic8LFWgd0UVvO_l1Nc6YoF-87R_4,1305 +pip/_vendor/webencodings/tests.py,sha256=OtGLyjhNY1fvkW1GvLJ_FV9ZoqC9Anyjr7q3kxTbzNs,6563 +pip/_vendor/webencodings/x_user_defined.py,sha256=yOqWSdmpytGfUgh_Z6JYgDNhoc-BAHyyeeT15Fr42tM,4307 +pip/py.typed,sha256=EBVvvPRTn_eIpz5e5QztSCdrMX7Qwd7VP93RSoIlZ2I,286 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pip-23.0.1.dist-info/REQUESTED b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pip-23.0.1.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pip-23.0.1.dist-info/WHEEL b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pip-23.0.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..57e3d840d59a650ac5bccbad5baeec47d155f0ad --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pip-23.0.1.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.38.4) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pip-23.0.1.dist-info/entry_points.txt b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pip-23.0.1.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..ab909c9b34e885f9cdf17705e34d07242e514c94 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pip-23.0.1.dist-info/entry_points.txt @@ -0,0 +1,4 @@ +[console_scripts] +pip = pip._internal.cli.main:main +pip3 = pip._internal.cli.main:main +pip3.9 = pip._internal.cli.main:main diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pip-23.0.1.dist-info/top_level.txt b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pip-23.0.1.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pip-23.0.1.dist-info/top_level.txt @@ -0,0 +1 @@ +pip diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pip/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pip/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..42f6c455c6eac114945bcda6912d8d5ae41017d6 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pip/__init__.py @@ -0,0 +1,13 @@ +from typing import List, Optional + +__version__ = "23.0.1" + + +def main(args: Optional[List[str]] = None) -> int: + """This is an internal API only meant for use by pip's own console scripts. + + For additional details, see https://github.com/pypa/pip/issues/7498. + """ + from pip._internal.utils.entrypoints import _wrapper + + return _wrapper(args) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pip/__main__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pip/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..fe34a7b7772cef55f5b5cb3455a2850489620ca7 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pip/__main__.py @@ -0,0 +1,31 @@ +import os +import sys +import warnings + +# Remove '' and current working directory from the first entry +# of sys.path, if present to avoid using current directory +# in pip commands check, freeze, install, list and show, +# when invoked as python -m pip +if sys.path[0] in ("", os.getcwd()): + sys.path.pop(0) + +# If we are running from a wheel, add the wheel to sys.path +# This allows the usage python pip-*.whl/pip install pip-*.whl +if __package__ == "": + # __file__ is pip-*.whl/pip/__main__.py + # first dirname call strips of '/__main__.py', second strips off '/pip' + # Resulting path is the name of the wheel itself + # Add that to sys.path so we can import pip + path = os.path.dirname(os.path.dirname(__file__)) + sys.path.insert(0, path) + +if __name__ == "__main__": + # Work around the error reported in #9540, pending a proper fix. + # Note: It is essential the warning filter is set *before* importing + # pip, as the deprecation happens at import time, not runtime. + warnings.filterwarnings( + "ignore", category=DeprecationWarning, module=".*packaging\\.version" + ) + from pip._internal.cli.main import main as _main + + sys.exit(_main()) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pip/__pip-runner__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pip/__pip-runner__.py new file mode 100644 index 0000000000000000000000000000000000000000..49a148a097e9cc06c165571e0bffaf7cae17dc5b --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pip/__pip-runner__.py @@ -0,0 +1,50 @@ +"""Execute exactly this copy of pip, within a different environment. + +This file is named as it is, to ensure that this module can't be imported via +an import statement. +""" + +# /!\ This version compatibility check section must be Python 2 compatible. /!\ + +import sys + +# Copied from setup.py +PYTHON_REQUIRES = (3, 7) + + +def version_str(version): # type: ignore + return ".".join(str(v) for v in version) + + +if sys.version_info[:2] < PYTHON_REQUIRES: + raise SystemExit( + "This version of pip does not support python {} (requires >={}).".format( + version_str(sys.version_info[:2]), version_str(PYTHON_REQUIRES) + ) + ) + +# From here on, we can use Python 3 features, but the syntax must remain +# Python 2 compatible. + +import runpy # noqa: E402 +from importlib.machinery import PathFinder # noqa: E402 +from os.path import dirname # noqa: E402 + +PIP_SOURCES_ROOT = dirname(dirname(__file__)) + + +class PipImportRedirectingFinder: + @classmethod + def find_spec(self, fullname, path=None, target=None): # type: ignore + if fullname != "pip": + return None + + spec = PathFinder.find_spec(fullname, [PIP_SOURCES_ROOT], target) + assert spec, (PIP_SOURCES_ROOT, fullname) + return spec + + +sys.meta_path.insert(0, PipImportRedirectingFinder()) + +assert __name__ == "__main__", "Cannot run __pip-runner__.py as a non-main module" +runpy.run_module("pip", run_name="__main__", alter_sys=True) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pip/py.typed b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pip/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..493b53e4e7a3984ddd49780313bf3bd9901dc1e0 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pip/py.typed @@ -0,0 +1,4 @@ +pip is a command line program. While it is implemented in Python, and so is +available for import, you must not use pip's internal APIs in this way. Typing +information is provided as a convenience only and is not a guarantee. Expect +unannounced changes to the API and types in releases. diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/preshed/__init__.pxd b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/preshed/__init__.pxd new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/preshed/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/preshed/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a55014485a1e94a14df8dfaf1bce1c2921d047c3 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/preshed/__init__.py @@ -0,0 +1 @@ +from .about import * diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/preshed/about.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/preshed/about.py new file mode 100644 index 0000000000000000000000000000000000000000..0b1d6d0253ca541544c0cd9281472d102c352e90 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/preshed/about.py @@ -0,0 +1,8 @@ +__title__ = "preshed" +__version__ = "3.0.13" +__summary__ = "Cython hash table that trusts the keys are pre-hashed" +__uri__ = "https://github.com/explosion/preshed" +__author__ = "Explosion" +__email__ = "contact@explosion.ai" +__license__ = "MIT" +__release__ = True diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/preshed/bloom.pxd b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/preshed/bloom.pxd new file mode 100644 index 0000000000000000000000000000000000000000..6925af16d70a80b3acbfe1236290c8d03670fc3f --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/preshed/bloom.pxd @@ -0,0 +1,27 @@ +from libc.stdint cimport uint64_t, uint32_t +from cymem.cymem cimport Pool + +ctypedef uint64_t key_t + +cdef struct BloomStruct: + key_t* bitfield + key_t hcount # hash count, number of hash functions + key_t length + uint32_t seed + + +cdef class BloomFilter: + cdef Pool mem + cdef BloomStruct* c_bloom + # Thread-unsafe variant of __contains__ + cdef inline bint contains(self, key_t item) noexcept nogil + +# Low-level thread-unsafe C API. +# If you use this API and expose it to Python, you must provide external +# synchronization (e.g. with a lock or critical section). + +cdef void bloom_init(Pool mem, BloomStruct* bloom, key_t hcount, key_t length, uint32_t seed) except * + +cdef bint bloom_contains(const BloomStruct* bloom, key_t item) noexcept nogil + +cdef void bloom_add(BloomStruct* bloom, key_t item) noexcept nogil diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/preshed/bloom.pyx b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/preshed/bloom.pyx new file mode 100644 index 0000000000000000000000000000000000000000..a72d54c866db7cb2be01c832f24876bce7005512 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/preshed/bloom.pyx @@ -0,0 +1,148 @@ +# cython: infer_types=True +# cython: cdivision=True +# +from murmurhash.mrmr cimport hash128_x86 +import math +from array import array + +cimport cython + +from libcpp.vector cimport vector + +try: + import copy_reg +except ImportError: + import copyreg as copy_reg + + +def calculate_size_and_hash_count(members, error_rate): + """Calculate the optimal size in bits and number of hash functions for a + given number of members and error rate. + """ + base = math.log(1 / (2 ** math.log(2))) + bit_count = math.ceil((members * math.log(error_rate)) / base) + hash_count = math.floor((bit_count / members) * math.log(2)) + return (bit_count, hash_count) + + +cdef class BloomFilter: + """Bloom filter that allows for basic membership tests. + + Only integers are supported as keys. + """ + def __init__(self, key_t size=(2 ** 10), key_t hash_funcs=23, uint32_t seed=0): + self.mem = Pool() + self.c_bloom = self.mem.alloc(1, sizeof(BloomStruct)) + bloom_init(self.mem, self.c_bloom, hash_funcs, size, seed) + + @classmethod + def from_error_rate(cls, members, error_rate=1E-4): + params = calculate_size_and_hash_count(members, error_rate) + return cls(*params) + + def add(self, key_t item): + with cython.critical_section(self): + bloom_add(self.c_bloom, item) + + def __contains__(self, key_t item): + with cython.critical_section(self): + return bloom_contains(self.c_bloom, item) + + # Requires external synchronization (e.g. a critical section) + cdef inline bint contains(self, key_t item) noexcept nogil: + return bloom_contains(self.c_bloom, item) + + def to_bytes(self): + with cython.critical_section(self): + return bloom_to_bytes(self.c_bloom) + + def from_bytes(self, bytes byte_string): + with cython.critical_section(self): + bloom_from_bytes(self.mem, self.c_bloom, byte_string) + return self + + def _roundtrip(self): + # Purely for testing, since this operation can't be done atomically + # without holding a critical section the entire time. + # Entering the same critical section recursively doesn't release it. + # (see cpython commit 180d417) + with cython.critical_section(self): + self.from_bytes(self.to_bytes()) + + +cdef bytes bloom_to_bytes(const BloomStruct* bloom): + # local scratch buffer + cdef vector[key_t] ret = vector[key_t]() + ret.push_back(bloom.hcount) + ret.push_back(bloom.length) + ret.push_back(bloom.seed) + for i in range(bloom.length // sizeof(key_t)): + ret.push_back(bloom.bitfield[i]) + # copy data in the scratch buffer into a new bytes object + return (ret.data())[:3*sizeof(key_t) + bloom.length] + + +cdef void bloom_from_bytes(Pool mem, BloomStruct* bloom, bytes data): + cdef char* c_data = data; + cdef key_t* i_data = c_data; + bloom.hcount = i_data[0] + bloom.length = i_data[1] + bloom.seed = i_data[2] + bloom.bitfield = mem.alloc(bloom.length // sizeof(key_t), sizeof(key_t)) + for i in range(bloom.length // sizeof(key_t)): + bloom.bitfield[i] = i_data[3+i] + + +cdef void bloom_init(Pool mem, BloomStruct* bloom, key_t hcount, key_t length, uint32_t seed) except *: + # size should be a multiple of the container size - round up + if length % sizeof(key_t): + length = math.ceil(length / sizeof(key_t)) * sizeof(key_t) + bloom.length = length + bloom.hcount = hcount + bloom.bitfield = mem.alloc(length // sizeof(key_t), sizeof(key_t)) + bloom.seed = seed + + +# Instead of calling MurmurHash with a different seed for each hash function, this +# generates two initial hash values and then combines them to create the correct +# number of hashes. This technique is faster than just doing MurmurhHash +# repeatedly and has been shown to work as well as full hashing. + +# For details see "Less Hashing, Same Performance: Building a Better Bloom +# Filter", Kirsch & Mitzenmacher. + +# https://www.semanticscholar.org/paper/Less-hashing%2C-same-performance%3A-Building-a-better-Kirsch-Mitzenmacher/65c43afbfc064705bdc40d3473f32518e9306429 +# The choice of seeds is arbitrary. + + +cdef void bloom_add(BloomStruct* bloom, key_t item) noexcept nogil: + cdef key_t hv + cdef key_t[2] keys + cdef key_t one = 1 # We want this explicitly typed, because bits + hash128_x86(&item, sizeof(key_t), 0, &keys) + for hiter in range(bloom.hcount): + hv = (keys[0] + (hiter * keys[1])) % bloom.length + bloom.bitfield[hv // sizeof(key_t)] |= one << (hv % sizeof(key_t)) + + +cdef bint bloom_contains(const BloomStruct* bloom, key_t item) noexcept nogil: + cdef key_t hv + cdef key_t[2] keys + cdef key_t one = 1 # We want this explicitly typed, because bits + hash128_x86(&item, sizeof(key_t), 0, &keys) + for hiter in range(bloom.hcount): + hv = (keys[0] + (hiter * keys[1])) % bloom.length + if not (bloom.bitfield[hv // sizeof(key_t)] & one << (hv % sizeof(key_t))): + return False + return True + + +def pickle_bloom(BloomFilter bloom): + return unpickle_bloom, (bloom.to_bytes(),) + + +def unpickle_bloom(byte_string): + return BloomFilter().from_bytes(byte_string) + + +copy_reg.pickle(BloomFilter, pickle_bloom, unpickle_bloom) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/preshed/counter.pxd b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/preshed/counter.pxd new file mode 100644 index 0000000000000000000000000000000000000000..bade909b81bd6fd763a58bbd81c1f69b3b582985 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/preshed/counter.pxd @@ -0,0 +1,19 @@ +from libc.stdint cimport int64_t + +from cymem.cymem cimport Pool + +from .maps cimport MapStruct +from .maps cimport map_init, map_get, map_set, map_iter +from .maps cimport key_t + + +ctypedef int64_t count_t + + +cdef class PreshCounter: + cdef Pool mem + cdef MapStruct* c_map + cdef public object smoother + cdef readonly count_t total + + cpdef int inc(self, key_t key, count_t inc) except -1 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/preshed/counter.pyx b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/preshed/counter.pyx new file mode 100644 index 0000000000000000000000000000000000000000..01763013fd4a763fe93c7887ecd9ae93ac45db35 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/preshed/counter.pyx @@ -0,0 +1,191 @@ +"""Count occurrences of uint64-valued keys.""" +from __future__ import division +cimport cython +from libc.math cimport log, exp, sqrt + + +cdef class PreshCounter: + def __init__(self, initial_size=8): + assert initial_size != 0 + assert initial_size & (initial_size - 1) == 0 + self.mem = Pool() + self.c_map = self.mem.alloc(1, sizeof(MapStruct)) + map_init(self.mem, self.c_map, initial_size) + self.smoother = None + self.total = 0 + + property length: + def __get__(self): + return self.c_map.length + + def __len__(self): + return self.c_map.length + + def __iter__(self): + cdef int i = 0 + cdef key_t key + cdef void* value + while map_iter(self.c_map, &i, &key, &value): + yield key, value + + def __getitem__(self, key_t key): + return map_get(self.c_map, key) + + cpdef int inc(self, key_t key, count_t inc) except -1: + cdef count_t c = map_get(self.c_map, key) + c += inc + map_set(self.mem, self.c_map, key, c) + self.total += inc + return c + + def prob(self, key_t key): + cdef GaleSmoother smoother + cdef void* value = map_get(self.c_map, key) + if self.smoother is not None: + smoother = self.smoother + r_star = self.smoother(value) + return r_star / self.smoother.total + elif value == NULL: + return 0 + else: + return value / self.total + + def smooth(self): + self.smoother = GaleSmoother(self) + + +cdef class GaleSmoother: + cdef Pool mem + cdef count_t* Nr + cdef double gradient + cdef double intercept + cdef readonly count_t cutoff + cdef count_t Nr0 + cdef readonly double total + + def __init__(self, PreshCounter counts): + count_counts = PreshCounter() + cdef double total = 0 + for _, count in counts: + count_counts.inc(count, 1) + total += count + # If we have no items seen 1 or 2 times, this doesn't work. But, this + # won't be true in real data... + assert count_counts[1] != 0 and count_counts[2] != 0, "Cannot smooth your weird data" + # Extrapolate Nr0 from Nr1 and Nr2. + self.Nr0 = count_counts[1] + (count_counts[1] - count_counts[2]) + self.mem = Pool() + + cdef double[2] mb + + cdef int n_counts = 0 + for _ in count_counts: + n_counts += 1 + sorted_r = count_counts.mem.alloc(n_counts, sizeof(count_t)) + self.Nr = self.mem.alloc(n_counts, sizeof(count_t)) + for i, (count, count_count) in enumerate(sorted(count_counts)): + sorted_r[i] = count + self.Nr[i] = count_count + + _fit_loglinear_model(mb, sorted_r, self.Nr, n_counts) + + self.cutoff = _find_when_to_switch(sorted_r, self.Nr, mb[0], mb[1], + n_counts) + self.gradient = mb[0] + self.intercept = mb[1] + self.total = self(0) * self.Nr0 + for count, count_count in count_counts: + self.total += self(count) * count_count + + def __call__(self, count_t r): + if r == 0: + return self.Nr[1] / self.Nr0 + elif r < self.cutoff: + return turing_estimate_of_r(r, self.Nr[r-1], self.Nr[r]) + else: + return gale_estimate_of_r(r, self.gradient, self.intercept) + + def count_count(self, count_t r): + if r == 0: + return self.Nr0 + else: + return self.Nr[r-1] + + +@cython.cdivision(True) +cdef double turing_estimate_of_r(double r, double Nr, double Nr1) except -1: + return ((r + 1) * Nr1) / Nr + + +@cython.cdivision(True) +cdef double gale_estimate_of_r(double r, double gradient, double intercept) except -1: + cdef double e_nr = exp(gradient * log(r) + intercept) + cdef double e_nr1 = exp(gradient * log(r+1) + intercept) + return (r + 1) * (e_nr1 / e_nr) + + +@cython.cdivision(True) +cdef void _fit_loglinear_model(double* output, count_t* sorted_r, count_t* Nr, + int length) except *: + cdef double x_mean = 0.0 + cdef double y_mean = 0.0 + + cdef Pool mem = Pool() + x = mem.alloc(length, sizeof(double)) + y = mem.alloc(length, sizeof(double)) + + cdef int i + for i in range(length): + r = sorted_r[i] + x[i] = log(r) + y[i] = log(_get_zr(i, sorted_r, Nr[i], length)) + x_mean += x[i] + y_mean += y[i] + + x_mean /= length + y_mean /= length + + cdef double ss_xy = 0.0 + cdef double ss_xx = 0.0 + + for i in range(length): + x_dist = x[i] - x_mean + y_dist = y[i] - y_mean + # SS_xy = sum the product of the distances from the mean + ss_xy += x_dist * y_dist + # SS_xx = sum the squares of the x distance + ss_xx += x_dist * x_dist + # Gradient + output[0] = ss_xy / ss_xx + # Intercept + output[1] = y_mean - output[0] * x_mean + + +@cython.cdivision(True) +cdef double _get_zr(int j, count_t* sorted_r, count_t Nr_j, int n_counts) except -1: + cdef double r_i = sorted_r[j-1] if j >= 1 else 0 + cdef double r_j = sorted_r[j] + cdef double r_k = sorted_r[j+1] if (j+1) < n_counts else (2 * r_i - 1) + return 2 * Nr_j / (r_k - r_i) + + +@cython.cdivision(True) +cdef double _variance(double r, double Nr, double Nr1) noexcept nogil: + return 1.96 * sqrt((r+1)**2 * (Nr1 / Nr**2) * (1.0 + (Nr1 / Nr))) + + +@cython.cdivision(True) +cdef count_t _find_when_to_switch(count_t* sorted_r, count_t* Nr, double m, double b, + int length) except -1: + cdef int i + cdef count_t r + for i in range(length-1): + r = sorted_r[i] + if sorted_r[i+1] != r+1: + return r + g_r = gale_estimate_of_r(r, m, b) + t_r = turing_estimate_of_r(r, Nr[i], Nr[i+1]) + if abs(t_r - g_r) <= _variance(r, Nr[i], Nr[i+1]): + return r + else: + return length - 1 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/preshed/maps.pxd b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/preshed/maps.pxd new file mode 100644 index 0000000000000000000000000000000000000000..fb75265ddc1253f751a5574df01c0f97aa142411 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/preshed/maps.pxd @@ -0,0 +1,63 @@ +from libc.stdint cimport uint64_t +from cymem.cymem cimport Pool + + +# Low-level thread-unsafe C API. +# If you use this API and expose it to Python, you must provide external +# synchronization (e.g. with a lock or critical section). + +ctypedef uint64_t key_t + + +cdef struct Cell: + key_t key + void* value + + +cdef struct Result: + int found + void* value + + +cdef struct MapStruct: + Cell* cells + void* value_for_empty_key + void* value_for_del_key + key_t length + key_t filled + bint is_empty_key_set + bint is_del_key_set + +cdef void* map_bulk_get(const MapStruct* map_, const key_t* keys, void** values, + int n) noexcept nogil + + +cdef Result map_get_unless_missing(const MapStruct* map_, const key_t key) noexcept nogil + +cdef void* map_get(const MapStruct* map_, const key_t key) noexcept nogil + +cdef void map_set(Pool mem, MapStruct* map_, key_t key, void* value) except * + +cdef void map_init(Pool mem, MapStruct* pmap, size_t length) except * + +cdef bint map_iter(const MapStruct* map_, int* i, key_t* key, void** value) noexcept nogil + +cdef void* map_clear(MapStruct* map_, const key_t key) noexcept nogil + + +cdef class PreshMap: + cdef MapStruct* c_map + cdef Pool mem + + # these methods are thread-unsafe and require external synchronization + cdef inline void* get(self, key_t key) noexcept nogil + cdef void set(self, key_t key, void* value) except * + +# note: this class is thread-unsafe without external synchronization +cdef class PreshMapArray: + cdef Pool mem + cdef MapStruct* maps + cdef size_t length + + cdef inline void* get(self, size_t i, key_t key) noexcept nogil + cdef void set(self, size_t i, key_t key, void* value) except * diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/preshed/maps.pyx b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/preshed/maps.pyx new file mode 100644 index 0000000000000000000000000000000000000000..176756ef133c020623369feab3332a2f08eee8e6 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/preshed/maps.pyx @@ -0,0 +1,289 @@ +# cython: infer_types=True +# cython: cdivision=True +# +cimport cython + + +DEF EMPTY_KEY = 0 +DEF DELETED_KEY = 1 + + +cdef class PreshMap: + """Hash map that assumes keys come pre-hashed. Maps uint64_t --> uint64_t. + Uses open addressing with linear probing. + + Usage + map = PreshMap() # Create a table + map = PreshMap(initial_size=1024) # Create with initial size (efficiency) + map[key] = value # Set a value to a key + value = map[key] # Get a value given a key + for key, value in map.items(): # Iterate over items + len(map) # Get number of inserted keys + """ + def __init__(self, size_t initial_size=8): + # Size must be power of two + if initial_size == 0: + initial_size = 8 + if initial_size & (initial_size - 1) != 0: + power = 1 + while power < initial_size: + power *= 2 + initial_size = power + self.mem = Pool() + self.c_map = self.mem.alloc(1, sizeof(MapStruct)) + map_init(self.mem, self.c_map, initial_size) + + property capacity: + def __get__(self): + cdef key_t length + with cython.critical_section(self): + # This might be atomic on some architectures + # but not everywhere, so needs a lock + length = self.c_map.length + return length + + def items(self): + cdef key_t key + cdef void* value + cdef int i = 0 + while True: + with cython.critical_section(self): + it = map_iter(self.c_map, &i, &key, &value) + if it: + yield key, value + else: + break + + def keys(self): + for key, _ in self.items(): + yield key + + def values(self): + for _, value in self.items(): + yield value + + def pop(self, key_t key, default=None): + cdef Result result + with cython.critical_section(self): + result = map_get_unless_missing(self.c_map, key) + map_clear(self.c_map, key) + if result.found: + return result.value + else: + return default + + def __getitem__(self, key_t key): + cdef Result result + with cython.critical_section(self): + result = map_get_unless_missing(self.c_map, key) + if result.found: + return result.value + else: + return None + + def __setitem__(self, key_t key, size_t value): + with cython.critical_section(self): + map_set(self.mem, self.c_map, key, value) + + def __delitem__(self, key_t key): + with cython.critical_section(self): + map_clear(self.c_map, key) + + def __len__(self): + cdef key_t filled + with cython.critical_section(self): + # This might be atomic on some architectures + # but not everywhere, so needs a lock + filled = self.c_map.filled + return filled + + def __contains__(self, key_t key): + cdef Result result + with cython.critical_section(self): + result = map_get_unless_missing(self.c_map, key) + return True if result.found else False + + def __iter__(self): + for key in self.keys(): + yield key + + # thread-unsafe low-level API + cdef inline void* get(self, key_t key) noexcept nogil: + return map_get(self.c_map, key) + + cdef void set(self, key_t key, void* value) except *: + map_set(self.mem, self.c_map, key, value) + + +cdef class PreshMapArray: + """An array of hash tables that assume keys come pre-hashed. Each table + uses open addressing with linear probing. + """ + def __init__(self, size_t length, size_t initial_size=8): + self.mem = Pool() + self.length = length + self.maps = self.mem.alloc(length, sizeof(MapStruct)) + for i in range(length): + map_init(self.mem, &self.maps[i], initial_size) + + cdef inline void* get(self, size_t i, key_t key) noexcept nogil: + return map_get(&self.maps[i], key) + + cdef void set(self, size_t i, key_t key, void* value) except *: + map_set(self.mem, &self.maps[i], key, value) + + +cdef void map_init(Pool mem, MapStruct* map_, size_t length) except *: + map_.length = length + map_.filled = 0 + map_.cells = mem.alloc(length, sizeof(Cell)) + + +cdef void map_set(Pool mem, MapStruct* map_, key_t key, void* value) except *: + cdef Cell* cell + if key == EMPTY_KEY: + map_.value_for_empty_key = value + map_.is_empty_key_set = True + elif key == DELETED_KEY: + map_.value_for_del_key = value + map_.is_del_key_set = True + else: + cell = _find_cell_for_insertion(map_.cells, map_.length, key) + if cell.key == EMPTY_KEY: + map_.filled += 1 + cell.key = key + cell.value = value + if (map_.filled + 1) * 5 >= (map_.length * 3): + _resize(mem, map_) + + +cdef void* map_get(const MapStruct* map_, const key_t key) noexcept nogil: + if key == EMPTY_KEY: + return map_.value_for_empty_key + elif key == DELETED_KEY: + return map_.value_for_del_key + cdef Cell* cell = _find_cell(map_.cells, map_.length, key) + return cell.value + + +cdef Result map_get_unless_missing(const MapStruct* map_, const key_t key) noexcept nogil: + cdef Result result + cdef Cell* cell + result.found = 0 + result.value = NULL + if key == EMPTY_KEY: + if map_.is_empty_key_set: + result.found = 1 + result.value = map_.value_for_empty_key + elif key == DELETED_KEY: + if map_.is_del_key_set: + result.found = 1 + result.value = map_.value_for_del_key + else: + cell = _find_cell(map_.cells, map_.length, key) + if cell.key == key: + result.found = 1 + result.value = cell.value + return result + + +cdef void* map_clear(MapStruct* map_, const key_t key) noexcept nogil: + if key == EMPTY_KEY: + value = map_.value_for_empty_key if map_.is_empty_key_set else NULL + map_.is_empty_key_set = False + return value + elif key == DELETED_KEY: + value = map_.value_for_del_key if map_.is_del_key_set else NULL + map_.is_del_key_set = False + return value + else: + cell = _find_cell(map_.cells, map_.length, key) + cell.key = DELETED_KEY + # We shouldn't decrement the "filled" value here, as we're not actually + # making "empty" values -- deleted values aren't quite the same. + # Instead if we manage to insert into a deleted slot, we don't increment + # the fill rate. + return cell.value + + +cdef void* map_bulk_get(const MapStruct* map_, const key_t* keys, void** values, + int n) noexcept nogil: + cdef int i + for i in range(n): + values[i] = map_get(map_, keys[i]) + + +cdef bint map_iter(const MapStruct* map_, int* i, key_t* key, void** value) noexcept nogil: + '''Iterate over the filled items, setting the current place in i, and the + key and value. Return False when iteration finishes. + ''' + cdef const Cell* cell + while i[0] < map_.length: + cell = &map_.cells[i[0]] + i[0] += 1 + if cell[0].key != EMPTY_KEY and cell[0].key != DELETED_KEY: + key[0] = cell[0].key + value[0] = cell[0].value + return True + # Remember to check for cells keyed by the special empty and deleted keys + if i[0] == map_.length: + i[0] += 1 + if map_.is_empty_key_set: + key[0] = EMPTY_KEY + value[0] = map_.value_for_empty_key + return True + if i[0] == map_.length + 1: + i[0] += 1 + if map_.is_del_key_set: + key[0] = DELETED_KEY + value[0] = map_.value_for_del_key + return True + return False + + +@cython.cdivision +cdef inline Cell* _find_cell(Cell* cells, const key_t size, const key_t key) noexcept nogil: + # Modulo for powers-of-two via bitwise & + cdef key_t i = (key & (size - 1)) + while cells[i].key != EMPTY_KEY and cells[i].key != key: + i = (i + 1) & (size - 1) + return &cells[i] + + +@cython.cdivision +cdef inline Cell* _find_cell_for_insertion(Cell* cells, const key_t size, const key_t key) noexcept nogil: + """Find the correct cell to insert a value, which could be a previously + deleted cell. If we cross a deleted cell and the key is in the table, we + mark the later cell as deleted, and return the earlier one.""" + cdef Cell* deleted = NULL + # Modulo for powers-of-two via bitwise & + cdef key_t i = (key & (size - 1)) + while cells[i].key != EMPTY_KEY and cells[i].key != key: + if cells[i].key == DELETED_KEY: + deleted = &cells[i] + i = (i + 1) & (size - 1) + if deleted is not NULL: + if cells[i].key == key: + # We need to ensure we don't end up with the key in the table twice. + # If we're using a deleted cell and we also have the key, we mark + # the later cell as deleted. + cells[i].key = DELETED_KEY + return deleted + return &cells[i] + + +cdef void _resize(Pool mem, MapStruct* map_) except *: + cdef size_t new_size = map_.length * 2 + cdef Cell* old_cells = map_.cells + cdef size_t old_size = map_.length + + map_.length = new_size + map_.filled = 0 + map_.cells = mem.alloc(new_size, sizeof(Cell)) + + cdef size_t i + cdef size_t slot + for i in range(old_size): + if old_cells[i].key != EMPTY_KEY and old_cells[i].key != DELETED_KEY: + map_set(mem, map_, old_cells[i].key, old_cells[i].value) + mem.free(old_cells) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pyasn1/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pyasn1/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..78c62baa60611af5489d88364b3c34ce7c0e1408 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pyasn1/__init__.py @@ -0,0 +1,2 @@ +# https://www.python.org/dev/peps/pep-0396/ +__version__ = '0.6.3' diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pyasn1/debug.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pyasn1/debug.py new file mode 100644 index 0000000000000000000000000000000000000000..07194235466a40c96ed0bb81f4874793e7680cbf --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pyasn1/debug.py @@ -0,0 +1,146 @@ +# +# This file is part of pyasn1 software. +# +# Copyright (c) 2005-2020, Ilya Etingof +# License: https://pyasn1.readthedocs.io/en/latest/license.html +# +import logging +import sys + +from pyasn1 import __version__ +from pyasn1 import error + +__all__ = ['Debug', 'setLogger', 'hexdump'] + +DEBUG_NONE = 0x0000 +DEBUG_ENCODER = 0x0001 +DEBUG_DECODER = 0x0002 +DEBUG_ALL = 0xffff + +FLAG_MAP = { + 'none': DEBUG_NONE, + 'encoder': DEBUG_ENCODER, + 'decoder': DEBUG_DECODER, + 'all': DEBUG_ALL +} + +LOGGEE_MAP = {} + + +class Printer(object): + # noinspection PyShadowingNames + def __init__(self, logger=None, handler=None, formatter=None): + if logger is None: + logger = logging.getLogger('pyasn1') + + logger.setLevel(logging.DEBUG) + + if handler is None: + handler = logging.StreamHandler() + + if formatter is None: + formatter = logging.Formatter('%(asctime)s %(name)s: %(message)s') + + handler.setFormatter(formatter) + handler.setLevel(logging.DEBUG) + logger.addHandler(handler) + + self.__logger = logger + + def __call__(self, msg): + self.__logger.debug(msg) + + def __str__(self): + return '' + + +class Debug(object): + defaultPrinter = Printer() + + def __init__(self, *flags, **options): + self._flags = DEBUG_NONE + + if 'loggerName' in options: + # route our logs to parent logger + self._printer = Printer( + logger=logging.getLogger(options['loggerName']), + handler=logging.NullHandler() + ) + + elif 'printer' in options: + self._printer = options.get('printer') + + else: + self._printer = self.defaultPrinter + + self._printer('running pyasn1 %s, debug flags %s' % (__version__, ', '.join(flags))) + + for flag in flags: + inverse = flag and flag[0] in ('!', '~') + if inverse: + flag = flag[1:] + try: + if inverse: + self._flags &= ~FLAG_MAP[flag] + else: + self._flags |= FLAG_MAP[flag] + except KeyError: + raise error.PyAsn1Error('bad debug flag %s' % flag) + + self._printer("debug category '%s' %s" % (flag, inverse and 'disabled' or 'enabled')) + + def __str__(self): + return 'logger %s, flags %x' % (self._printer, self._flags) + + def __call__(self, msg): + self._printer(msg) + + def __and__(self, flag): + return self._flags & flag + + def __rand__(self, flag): + return flag & self._flags + +_LOG = DEBUG_NONE + + +def setLogger(userLogger): + global _LOG + + if userLogger: + _LOG = userLogger + else: + _LOG = DEBUG_NONE + + # Update registered logging clients + for module, (name, flags) in LOGGEE_MAP.items(): + setattr(module, name, _LOG & flags and _LOG or DEBUG_NONE) + + +def registerLoggee(module, name='LOG', flags=DEBUG_NONE): + LOGGEE_MAP[sys.modules[module]] = name, flags + setLogger(_LOG) + return _LOG + + +def hexdump(octets): + return ' '.join( + ['%s%.2X' % (n % 16 == 0 and ('\n%.5d: ' % n) or '', x) + for n, x in zip(range(len(octets)), octets)] + ) + + +class Scope(object): + def __init__(self): + self._list = [] + + def __str__(self): return '.'.join(self._list) + + def push(self, token): + self._list.append(token) + + def pop(self): + return self._list.pop() + + +scope = Scope() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pyasn1/error.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pyasn1/error.py new file mode 100644 index 0000000000000000000000000000000000000000..75c9a3f4cd09dd531f7eea8738d9ba4191389b78 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pyasn1/error.py @@ -0,0 +1,116 @@ +# +# This file is part of pyasn1 software. +# +# Copyright (c) 2005-2020, Ilya Etingof +# License: https://pyasn1.readthedocs.io/en/latest/license.html +# + + +class PyAsn1Error(Exception): + """Base pyasn1 exception + + `PyAsn1Error` is the base exception class (based on + :class:`Exception`) that represents all possible ASN.1 related + errors. + + Parameters + ---------- + args: + Opaque positional parameters + + Keyword Args + ------------ + kwargs: + Opaque keyword parameters + + """ + def __init__(self, *args, **kwargs): + self._args = args + self._kwargs = kwargs + + @property + def context(self): + """Return exception context + + When exception object is created, the caller can supply some opaque + context for the upper layers to better understand the cause of the + exception. + + Returns + ------- + : :py:class:`dict` + Dict holding context specific data + """ + return self._kwargs.get('context', {}) + + +class ValueConstraintError(PyAsn1Error): + """ASN.1 type constraints violation exception + + The `ValueConstraintError` exception indicates an ASN.1 value + constraint violation. + + It might happen on value object instantiation (for scalar types) or on + serialization (for constructed types). + """ + + +class SubstrateUnderrunError(PyAsn1Error): + """ASN.1 data structure deserialization error + + The `SubstrateUnderrunError` exception indicates insufficient serialised + data on input of a de-serialization codec. + """ + + +class EndOfStreamError(SubstrateUnderrunError): + """ASN.1 data structure deserialization error + + The `EndOfStreamError` exception indicates the condition of the input + stream has been closed. + """ + + +class UnsupportedSubstrateError(PyAsn1Error): + """Unsupported substrate type to parse as ASN.1 data.""" + + +class PyAsn1UnicodeError(PyAsn1Error, UnicodeError): + """Unicode text processing error + + The `PyAsn1UnicodeError` exception is a base class for errors relating to + unicode text de/serialization. + + Apart from inheriting from :class:`PyAsn1Error`, it also inherits from + :class:`UnicodeError` to help the caller catching unicode-related errors. + """ + def __init__(self, message, unicode_error=None): + if isinstance(unicode_error, UnicodeError): + UnicodeError.__init__(self, *unicode_error.args) + PyAsn1Error.__init__(self, message) + + +class PyAsn1UnicodeDecodeError(PyAsn1UnicodeError, UnicodeDecodeError): + """Unicode text decoding error + + The `PyAsn1UnicodeDecodeError` exception represents a failure to + deserialize unicode text. + + Apart from inheriting from :class:`PyAsn1UnicodeError`, it also inherits + from :class:`UnicodeDecodeError` to help the caller catching unicode-related + errors. + """ + + +class PyAsn1UnicodeEncodeError(PyAsn1UnicodeError, UnicodeEncodeError): + """Unicode text encoding error + + The `PyAsn1UnicodeEncodeError` exception represents a failure to + serialize unicode text. + + Apart from inheriting from :class:`PyAsn1UnicodeError`, it also inherits + from :class:`UnicodeEncodeError` to help the caller catching + unicode-related errors. + """ + + diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pycparser-3.0.dist-info/INSTALLER b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pycparser-3.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pycparser-3.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pycparser-3.0.dist-info/METADATA b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pycparser-3.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..b94a88bb3f4d9b5d41bd639b818f79c01dce4fd1 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pycparser-3.0.dist-info/METADATA @@ -0,0 +1,244 @@ +Metadata-Version: 2.4 +Name: pycparser +Version: 3.0 +Summary: C parser in Python +Author-email: Eli Bendersky +Maintainer-email: Eli Bendersky +License-Expression: BSD-3-Clause +Project-URL: Homepage, https://github.com/eliben/pycparser +Classifier: Development Status :: 5 - Production/Stable +Classifier: Programming Language :: Python :: 3 +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 +Requires-Python: >=3.10 +Description-Content-Type: text/x-rst +License-File: LICENSE +Dynamic: license-file + +=============== +pycparser v3.00 +=============== + + +.. image:: https://github.com/eliben/pycparser/workflows/pycparser-tests/badge.svg + :align: center + :target: https://github.com/eliben/pycparser/actions + +---- + +.. contents:: + :backlinks: none + +.. sectnum:: + +Introduction +============ + +What is pycparser? +------------------ + +**pycparser** is a parser for the C language, written in pure Python. It is a +module designed to be easily integrated into applications that need to parse +C source code. + +What is it good for? +-------------------- + +Anything that needs C code to be parsed. The following are some uses for +**pycparser**, taken from real user reports: + +* C code obfuscator +* Front-end for various specialized C compilers +* Static code checker +* Automatic unit-test discovery +* Adding specialized extensions to the C language + +One of the most popular uses of **pycparser** is in the `cffi +`_ library, which uses it to parse the +declarations of C functions and types in order to auto-generate FFIs. + +**pycparser** is unique in the sense that it's written in pure Python - a very +high level language that's easy to experiment with and tweak. To people familiar +with Lex and Yacc, **pycparser**'s code will be simple to understand. It also +has no external dependencies (except for a Python interpreter), making it very +simple to install and deploy. + +Which version of C does pycparser support? +------------------------------------------ + +**pycparser** aims to support the full C99 language (according to the standard +ISO/IEC 9899). Some features from C11 are also supported, and patches to support +more are welcome. + +**pycparser** supports very few GCC extensions, but it's fairly easy to set +things up so that it parses code with a lot of GCC-isms successfully. See the +`FAQ `_ for more details. + +What grammar does pycparser follow? +----------------------------------- + +**pycparser** very closely follows the C grammar provided in Annex A of the C99 +standard (ISO/IEC 9899). + +How is pycparser licensed? +-------------------------- + +`BSD license `_. + +Contact details +--------------- + +For reporting problems with **pycparser** or submitting feature requests, please +open an `issue `_, or submit a +pull request. + + +Installing +========== + +Prerequisites +------------- + +**pycparser** is being tested with modern versions of Python on +Linux, macOS and Windows. See `the CI dashboard `__ +for details. + +**pycparser** has no external dependencies. + +Installation process +-------------------- + +The recommended way to install **pycparser** is with ``pip``:: + + > pip install pycparser + +Using +===== + +Interaction with the C preprocessor +----------------------------------- + +In order to be compilable, C code must be preprocessed by the C preprocessor - +``cpp``. A compatible ``cpp`` handles preprocessing directives like ``#include`` and +``#define``, removes comments, and performs other minor tasks that prepare the C +code for compilation. + +For all but the most trivial snippets of C code **pycparser**, like a C +compiler, must receive preprocessed C code in order to function correctly. If +you import the top-level ``parse_file`` function from the **pycparser** package, +it will interact with ``cpp`` for you, as long as it's in your PATH, or you +provide a path to it. + +Note also that you can use ``gcc -E`` or ``clang -E`` instead of ``cpp``. See +the ``using_gcc_E_libc.py`` example for more details. Windows users can download +and install a binary build of Clang for Windows `from this website +`_. + +What about the standard C library headers? +------------------------------------------ + +C code almost always ``#include``\s various header files from the standard C +library, like ``stdio.h``. While (with some effort) **pycparser** can be made to +parse the standard headers from any C compiler, it's much simpler to use the +provided "fake" standard includes for C11 in ``utils/fake_libc_include``. These +are standard C header files that contain only the bare necessities to allow +valid parsing of the files that use them. As a bonus, since they're minimal, it +can significantly improve the performance of parsing large C files. + +The key point to understand here is that **pycparser** doesn't really care about +the semantics of types. It only needs to know whether some token encountered in +the source is a previously defined type. This is essential in order to be able +to parse C correctly. + +See `this blog post +`_ +for more details. + +Note that the fake headers are not included in the ``pip`` package nor installed +via the package build (`#224 `_). + +Basic usage +----------- + +Take a look at the |examples|_ directory of the distribution for a few examples +of using **pycparser**. These should be enough to get you started. Please note +that most realistic C code samples would require running the C preprocessor +before passing the code to **pycparser**; see the previous sections for more +details. + +.. |examples| replace:: ``examples`` +.. _examples: examples + + +Advanced usage +-------------- + +The public interface of **pycparser** is well documented with comments in +``pycparser/c_parser.py``. For a detailed overview of the various AST nodes +created by the parser, see ``pycparser/_c_ast.cfg``. + +There's also a `FAQ available here `_. +In any case, you can always drop me an `email `_ for help. + + +Modifying +========= + +There are a few points to keep in mind when modifying **pycparser**: + +* The code for **pycparser**'s AST nodes is automatically generated from a + configuration file - ``_c_ast.cfg``, by ``_ast_gen.py``. If you modify the AST + configuration, make sure to re-generate the code. This can be done by running + the ``_ast_gen.py`` script (from the repository root or the + ``pycparser`` directory). +* Read the docstring in the constructor of the ``CParser`` class for details + on configuration and compatibility arguments. + + +Package contents +================ + +Once you unzip the ``pycparser`` package, you'll see the following files and +directories: + +README.rst: + This README file. + +LICENSE: + The pycparser license + +setup.py: + Legacy installation script (build metadata lives in ``pyproject.toml``). + +pyproject.toml: + Package metadata and build configuration. + +examples/: + A directory with some examples of using **pycparser** + +pycparser/: + The **pycparser** module source code. + +tests/: + Unit tests. + +utils/fake_libc_include: + Minimal standard C library include files that should allow to parse any C code. + Note that these headers now include C11 code, so they may not work when the + preprocessor is configured to an earlier C standard (like ``-std=c99``). + +utils/internal/: + Internal utilities for my own use. You probably don't need them. + + +Contributors +============ + +Some people have contributed to **pycparser** by opening issues on bugs they've +found and/or submitting patches. The list of contributors is in the CONTRIBUTORS +file in the source distribution. After **pycparser** moved to Github I stopped +updating this list because Github does a much better job at tracking +contributions. diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pycparser-3.0.dist-info/RECORD b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pycparser-3.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..41b22833e279d8292f51fdcfcfa185a877b4c923 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pycparser-3.0.dist-info/RECORD @@ -0,0 +1,21 @@ +pycparser-3.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +pycparser-3.0.dist-info/METADATA,sha256=9UemCwq1TMLyQiE9H4eWCtgN991d_rmNF6RE1Iv7a5M,8229 +pycparser-3.0.dist-info/RECORD,, +pycparser-3.0.dist-info/WHEEL,sha256=qELbo2s1Yzl39ZmrAibXA2jjPLUYfnVhUNTlyF1rq0Y,92 +pycparser-3.0.dist-info/licenses/LICENSE,sha256=DIRjmTaep23de1xE_m0WSXQV_PAV9cu1CMJL-YuBxbE,1543 +pycparser-3.0.dist-info/top_level.txt,sha256=c-lPcS74L_8KoH7IE6PQF5ofyirRQNV4VhkbSFIPeWM,10 +pycparser/__init__.py,sha256=phViRyAuUmgqE4kNmaCqpm5WVEBIvzUSFapBv4XX3xo,2829 +pycparser/__pycache__/__init__.cpython-310.pyc,, +pycparser/__pycache__/_ast_gen.cpython-310.pyc,, +pycparser/__pycache__/ast_transforms.cpython-310.pyc,, +pycparser/__pycache__/c_ast.cpython-310.pyc,, +pycparser/__pycache__/c_generator.cpython-310.pyc,, +pycparser/__pycache__/c_lexer.cpython-310.pyc,, +pycparser/__pycache__/c_parser.cpython-310.pyc,, +pycparser/_ast_gen.py,sha256=ExH5Ym4pk7dQPEIkQr9RJim5feztdBQwSBPvpvE-5BM,11292 +pycparser/_c_ast.cfg,sha256=ld5ezE9yzIJFIVAUfw7ezJSlMi4nXKNCzfmqjOyQTNo,4255 +pycparser/ast_transforms.py,sha256=XwMsarc5aDddNWgIiKm4-jOWMRYib96yNQUo0_u28WA,5899 +pycparser/c_ast.py,sha256=uwkcZWHfXDQIw6WDvCL17iWM_-0R-URDqEMmPjXLOAc,32954 +pycparser/c_generator.py,sha256=RVKJPguv2CvovHHSfQkqimckUr9wGU9PofxCGj251QA,20661 +pycparser/c_lexer.py,sha256=B1VoqbYhPWkOJJWCem4OY4zj0IxrPktBZZFe2Y87kUg,25155 +pycparser/c_parser.py,sha256=3FBKGLjjlC3v8afwD_cnMR67ImoYIy73a4WKQR6hX7g,89798 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pycparser-3.0.dist-info/WHEEL b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pycparser-3.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..fbbd86cb272bc6e329803bf67f442f2a124caa95 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pycparser-3.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.10.1) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pycparser-3.0.dist-info/top_level.txt b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pycparser-3.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..dc1c9e101ad9ccd943b359338ef42c342ebc84a1 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pycparser-3.0.dist-info/top_level.txt @@ -0,0 +1 @@ +pycparser diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pycparser/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pycparser/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0606c03e205a154bb751de57fe8e03e277491fb0 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pycparser/__init__.py @@ -0,0 +1,99 @@ +# ----------------------------------------------------------------- +# pycparser: __init__.py +# +# This package file exports some convenience functions for +# interacting with pycparser +# +# Eli Bendersky [https://eli.thegreenplace.net/] +# License: BSD +# ----------------------------------------------------------------- +__all__ = ["c_lexer", "c_parser", "c_ast"] +__version__ = "3.00" + +import io +from subprocess import check_output + +from . import c_parser + +CParser = c_parser.CParser + + +def preprocess_file(filename, cpp_path="cpp", cpp_args=""): + """Preprocess a file using cpp. + + filename: + Name of the file you want to preprocess. + + cpp_path: + cpp_args: + Refer to the documentation of parse_file for the meaning of these + arguments. + + When successful, returns the preprocessed file's contents. + Errors from cpp will be printed out. + """ + path_list = [cpp_path] + if isinstance(cpp_args, list): + path_list += cpp_args + elif cpp_args != "": + path_list += [cpp_args] + path_list += [filename] + + try: + # Note the use of universal_newlines to treat all newlines + # as \n for Python's purpose + text = check_output(path_list, universal_newlines=True) + except OSError as e: + raise RuntimeError( + "Unable to invoke 'cpp'. " + + "Make sure its path was passed correctly\n" + + f"Original error: {e}" + ) + + return text + + +def parse_file( + filename, use_cpp=False, cpp_path="cpp", cpp_args="", parser=None, encoding=None +): + """Parse a C file using pycparser. + + filename: + Name of the file you want to parse. + + use_cpp: + Set to True if you want to execute the C pre-processor + on the file prior to parsing it. + + cpp_path: + If use_cpp is True, this is the path to 'cpp' on your + system. If no path is provided, it attempts to just + execute 'cpp', so it must be in your PATH. + + cpp_args: + If use_cpp is True, set this to the command line arguments strings + to cpp. Be careful with quotes - it's best to pass a raw string + (r'') here. For example: + r'-I../utils/fake_libc_include' + If several arguments are required, pass a list of strings. + + encoding: + Encoding to use for the file to parse + + parser: + Optional parser object to be used instead of the default CParser + + When successful, an AST is returned. ParseError can be + thrown if the file doesn't parse successfully. + + Errors from cpp will be printed out. + """ + if use_cpp: + text = preprocess_file(filename, cpp_path, cpp_args) + else: + with io.open(filename, encoding=encoding) as f: + text = f.read() + + if parser is None: + parser = CParser() + return parser.parse(text, filename) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pycparser/_ast_gen.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pycparser/_ast_gen.py new file mode 100644 index 0000000000000000000000000000000000000000..6df0b6a9b37e4cfc70a49c20c42b8a5e1828827c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pycparser/_ast_gen.py @@ -0,0 +1,355 @@ +# ----------------------------------------------------------------- +# _ast_gen.py +# +# Generates the AST Node classes from a specification given in +# a configuration file. This module can also be run as a script to +# regenerate c_ast.py from _c_ast.cfg (from the repo root or the +# pycparser/ directory). Use 'make check' to reformat the generated +# file after running this script. +# +# The design of this module was inspired by astgen.py from the +# Python 2.5 code-base. +# +# Eli Bendersky [https://eli.thegreenplace.net/] +# License: BSD +# ----------------------------------------------------------------- +from string import Template +import os +from typing import IO + + +class ASTCodeGenerator: + def __init__(self, cfg_filename="_c_ast.cfg"): + """Initialize the code generator from a configuration + file. + """ + self.cfg_filename = cfg_filename + self.node_cfg = [ + NodeCfg(name, contents) + for (name, contents) in self.parse_cfgfile(cfg_filename) + ] + + def generate(self, file: IO[str]) -> None: + """Generates the code into file, an open file buffer.""" + src = Template(_PROLOGUE_COMMENT).substitute(cfg_filename=self.cfg_filename) + + src += _PROLOGUE_CODE + for node_cfg in self.node_cfg: + src += node_cfg.generate_source() + "\n\n" + + file.write(src) + + def parse_cfgfile(self, filename): + """Parse the configuration file and yield pairs of + (name, contents) for each node. + """ + with open(filename, "r") as f: + for line in f: + line = line.strip() + if not line or line.startswith("#"): + continue + colon_i = line.find(":") + lbracket_i = line.find("[") + rbracket_i = line.find("]") + if colon_i < 1 or lbracket_i <= colon_i or rbracket_i <= lbracket_i: + raise RuntimeError(f"Invalid line in {filename}:\n{line}\n") + + name = line[:colon_i] + val = line[lbracket_i + 1 : rbracket_i] + vallist = [v.strip() for v in val.split(",")] if val else [] + yield name, vallist + + +class NodeCfg: + """Node configuration. + + name: node name + contents: a list of contents - attributes and child nodes + See comment at the top of the configuration file for details. + """ + + def __init__(self, name, contents): + self.name = name + self.all_entries = [] + self.attr = [] + self.child = [] + self.seq_child = [] + + for entry in contents: + clean_entry = entry.rstrip("*") + self.all_entries.append(clean_entry) + + if entry.endswith("**"): + self.seq_child.append(clean_entry) + elif entry.endswith("*"): + self.child.append(clean_entry) + else: + self.attr.append(entry) + + def generate_source(self): + src = self._gen_init() + src += "\n" + self._gen_children() + src += "\n" + self._gen_iter() + src += "\n" + self._gen_attr_names() + return src + + def _gen_init(self): + src = f"class {self.name}(Node):\n" + + if self.all_entries: + args = ", ".join(self.all_entries) + slots = ", ".join(f"'{e}'" for e in self.all_entries) + slots += ", 'coord', '__weakref__'" + arglist = f"(self, {args}, coord=None)" + else: + slots = "'coord', '__weakref__'" + arglist = "(self, coord=None)" + + src += f" __slots__ = ({slots})\n" + src += f" def __init__{arglist}:\n" + + for name in self.all_entries + ["coord"]: + src += f" self.{name} = {name}\n" + + return src + + def _gen_children(self): + src = " def children(self):\n" + + if self.all_entries: + src += " nodelist = []\n" + + for child in self.child: + src += f" if self.{child} is not None:\n" + src += f' nodelist.append(("{child}", self.{child}))\n' + + for seq_child in self.seq_child: + src += f" for i, child in enumerate(self.{seq_child} or []):\n" + src += f' nodelist.append((f"{seq_child}[{{i}}]", child))\n' + + src += " return tuple(nodelist)\n" + else: + src += " return ()\n" + + return src + + def _gen_iter(self): + src = " def __iter__(self):\n" + + if self.all_entries: + for child in self.child: + src += f" if self.{child} is not None:\n" + src += f" yield self.{child}\n" + + for seq_child in self.seq_child: + src += f" for child in (self.{seq_child} or []):\n" + src += " yield child\n" + + if not (self.child or self.seq_child): + # Empty generator + src += " return\n" + " yield\n" + else: + # Empty generator + src += " return\n" + " yield\n" + + return src + + def _gen_attr_names(self): + src = " attr_names = (" + "".join(f"{nm!r}, " for nm in self.attr) + ")" + return src + + +_PROLOGUE_COMMENT = r"""#----------------------------------------------------------------- +# ** ATTENTION ** +# This code was automatically generated from _c_ast.cfg +# +# Do not modify it directly. Modify the configuration file and +# run the generator again. +# ** ** *** ** ** +# +# pycparser: c_ast.py +# +# AST Node classes. +# +# Eli Bendersky [https://eli.thegreenplace.net/] +# License: BSD +#----------------------------------------------------------------- + +""" +_PROLOGUE_CODE = r''' +import sys +from typing import Any, ClassVar, IO, Optional + +def _repr(obj): + """ + Get the representation of an object, with dedicated pprint-like format for lists. + """ + if isinstance(obj, list): + return '[' + (',\n '.join((_repr(e).replace('\n', '\n ') for e in obj))) + '\n]' + else: + return repr(obj) + +class Node: + __slots__ = () + """ Abstract base class for AST nodes. + """ + attr_names: ClassVar[tuple[str, ...]] = () + coord: Optional[Any] + def __repr__(self): + """ Generates a python representation of the current node + """ + result = self.__class__.__name__ + '(' + + indent = '' + separator = '' + for name in self.__slots__[:-2]: + result += separator + result += indent + result += name + '=' + (_repr(getattr(self, name)).replace('\n', '\n ' + (' ' * (len(name) + len(self.__class__.__name__))))) + + separator = ',' + indent = '\n ' + (' ' * len(self.__class__.__name__)) + + result += indent + ')' + + return result + + def children(self): + """ A sequence of all children that are Nodes + """ + pass + + def show( + self, + buf: IO[str] = sys.stdout, + offset: int = 0, + attrnames: bool = False, + showemptyattrs: bool = True, + nodenames: bool = False, + showcoord: bool = False, + _my_node_name: Optional[str] = None, + ): + """ Pretty print the Node and all its attributes and + children (recursively) to a buffer. + + buf: + Open IO buffer into which the Node is printed. + + offset: + Initial offset (amount of leading spaces) + + attrnames: + True if you want to see the attribute names in + name=value pairs. False to only see the values. + + showemptyattrs: + False if you want to suppress printing empty attributes. + + nodenames: + True if you want to see the actual node names + within their parents. + + showcoord: + Do you want the coordinates of each Node to be + displayed. + """ + lead = ' ' * offset + if nodenames and _my_node_name is not None: + buf.write(lead + self.__class__.__name__+ ' <' + _my_node_name + '>: ') + else: + buf.write(lead + self.__class__.__name__+ ': ') + + if self.attr_names: + def is_empty(v): + v is None or (hasattr(v, '__len__') and len(v) == 0) + nvlist = [(n, getattr(self,n)) for n in self.attr_names \ + if showemptyattrs or not is_empty(getattr(self,n))] + if attrnames: + attrstr = ', '.join(f'{name}={value}' for name, value in nvlist) + else: + attrstr = ', '.join(f'{value}' for _, value in nvlist) + buf.write(attrstr) + + if showcoord: + buf.write(f' (at {self.coord})') + buf.write('\n') + + for (child_name, child) in self.children(): + child.show( + buf, + offset=offset + 2, + attrnames=attrnames, + showemptyattrs=showemptyattrs, + nodenames=nodenames, + showcoord=showcoord, + _my_node_name=child_name) + + +class NodeVisitor: + """ A base NodeVisitor class for visiting c_ast nodes. + Subclass it and define your own visit_XXX methods, where + XXX is the class name you want to visit with these + methods. + + For example: + + class ConstantVisitor(NodeVisitor): + def __init__(self): + self.values = [] + + def visit_Constant(self, node): + self.values.append(node.value) + + Creates a list of values of all the constant nodes + encountered below the given node. To use it: + + cv = ConstantVisitor() + cv.visit(node) + + Notes: + + * generic_visit() will be called for AST nodes for which + no visit_XXX method was defined. + * The children of nodes for which a visit_XXX was + defined will not be visited - if you need this, call + generic_visit() on the node. + You can use: + NodeVisitor.generic_visit(self, node) + * Modeled after Python's own AST visiting facilities + (the ast module of Python 3.0) + """ + + _method_cache = None + + def visit(self, node: Node): + """ Visit a node. + """ + + if self._method_cache is None: + self._method_cache = {} + + visitor = self._method_cache.get(node.__class__.__name__, None) + if visitor is None: + method = 'visit_' + node.__class__.__name__ + visitor = getattr(self, method, self.generic_visit) + self._method_cache[node.__class__.__name__] = visitor + + return visitor(node) + + def generic_visit(self, node: Node): + """ Called if no explicit visitor function exists for a + node. Implements preorder visiting of the node. + """ + for _, c in node.children(): + self.visit(c) + +''' + + +if __name__ == "__main__": + base_dir = os.path.dirname(os.path.abspath(__file__)) + cfg_path = os.path.join(base_dir, "_c_ast.cfg") + out_path = os.path.join(base_dir, "c_ast.py") + ast_gen = ASTCodeGenerator(cfg_path) + with open(out_path, "w") as out: + ast_gen.generate(out) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pycparser/_c_ast.cfg b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pycparser/_c_ast.cfg new file mode 100644 index 0000000000000000000000000000000000000000..0626533e8adf517da897ec047c8deb6ad41c38c9 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pycparser/_c_ast.cfg @@ -0,0 +1,195 @@ +#----------------------------------------------------------------- +# pycparser: _c_ast.cfg +# +# Defines the AST Node classes used in pycparser. +# +# Each entry is a Node sub-class name, listing the attributes +# and child nodes of the class: +# * - a child node +# ** - a sequence of child nodes +# - an attribute +# +# Eli Bendersky [https://eli.thegreenplace.net/] +# License: BSD +#----------------------------------------------------------------- + +# ArrayDecl is a nested declaration of an array with the given type. +# dim: the dimension (for example, constant 42) +# dim_quals: list of dimension qualifiers, to support C99's allowing 'const' +# and 'static' within the array dimension in function declarations. +ArrayDecl: [type*, dim*, dim_quals] + +ArrayRef: [name*, subscript*] + +# op: =, +=, /= etc. +# +Assignment: [op, lvalue*, rvalue*] + +Alignas: [alignment*] + +BinaryOp: [op, left*, right*] + +Break: [] + +Case: [expr*, stmts**] + +Cast: [to_type*, expr*] + +# Compound statement in C99 is a list of block items (declarations or +# statements). +# +Compound: [block_items**] + +# Compound literal (anonymous aggregate) for C99. +# (type-name) {initializer_list} +# type: the typename +# init: InitList for the initializer list +# +CompoundLiteral: [type*, init*] + +# type: int, char, float, string, etc. +# +Constant: [type, value] + +Continue: [] + +# name: the variable being declared +# quals: list of qualifiers (const, volatile) +# funcspec: list function specifiers (i.e. inline in C99) +# storage: list of storage specifiers (extern, register, etc.) +# type: declaration type (probably nested with all the modifiers) +# init: initialization value, or None +# bitsize: bit field size, or None +# +Decl: [name, quals, align, storage, funcspec, type*, init*, bitsize*] + +DeclList: [decls**] + +Default: [stmts**] + +DoWhile: [cond*, stmt*] + +# Represents the ellipsis (...) parameter in a function +# declaration +# +EllipsisParam: [] + +# An empty statement (a semicolon ';' on its own) +# +EmptyStatement: [] + +# Enumeration type specifier +# name: an optional ID +# values: an EnumeratorList +# +Enum: [name, values*] + +# A name/value pair for enumeration values +# +Enumerator: [name, value*] + +# A list of enumerators +# +EnumeratorList: [enumerators**] + +# A list of expressions separated by the comma operator. +# +ExprList: [exprs**] + +# This is the top of the AST, representing a single C file (a +# translation unit in K&R jargon). It contains a list of +# "external-declaration"s, which is either declarations (Decl), +# Typedef or function definitions (FuncDef). +# +FileAST: [ext**] + +# for (init; cond; next) stmt +# +For: [init*, cond*, next*, stmt*] + +# name: Id +# args: ExprList +# +FuncCall: [name*, args*] + +# type (args) +# +FuncDecl: [args*, type*] + +# Function definition: a declarator for the function name and +# a body, which is a compound statement. +# There's an optional list of parameter declarations for old +# K&R-style definitions +# +FuncDef: [decl*, param_decls**, body*] + +Goto: [name] + +ID: [name] + +# Holder for types that are a simple identifier (e.g. the built +# ins void, char etc. and typedef-defined types) +# +IdentifierType: [names] + +If: [cond*, iftrue*, iffalse*] + +# An initialization list used for compound literals. +# +InitList: [exprs**] + +Label: [name, stmt*] + +# A named initializer for C99. +# The name of a NamedInitializer is a sequence of Nodes, because +# names can be hierarchical and contain constant expressions. +# +NamedInitializer: [name**, expr*] + +# a list of comma separated function parameter declarations +# +ParamList: [params**] + +PtrDecl: [quals, type*] + +Return: [expr*] + +StaticAssert: [cond*, message*] + +# name: struct tag name +# decls: declaration of members +# +Struct: [name, decls**] + +# type: . or -> +# name.field or name->field +# +StructRef: [name*, type, field*] + +Switch: [cond*, stmt*] + +# cond ? iftrue : iffalse +# +TernaryOp: [cond*, iftrue*, iffalse*] + +# A base type declaration +# +TypeDecl: [declname, quals, align, type*] + +# A typedef declaration. +# Very similar to Decl, but without some attributes +# +Typedef: [name, quals, storage, type*] + +Typename: [name, quals, align, type*] + +UnaryOp: [op, expr*] + +# name: union tag name +# decls: declaration of members +# +Union: [name, decls**] + +While: [cond*, stmt*] + +Pragma: [string] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pycparser/ast_transforms.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pycparser/ast_transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..1051737f65d106e23acf8685b57dfd12c811b934 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pycparser/ast_transforms.py @@ -0,0 +1,174 @@ +# ------------------------------------------------------------------------------ +# pycparser: ast_transforms.py +# +# Some utilities used by the parser to create a friendlier AST. +# +# Eli Bendersky [https://eli.thegreenplace.net/] +# License: BSD +# ------------------------------------------------------------------------------ + +from typing import Any, List, Tuple, cast + +from . import c_ast + + +def fix_switch_cases(switch_node: c_ast.Switch) -> c_ast.Switch: + """The 'case' statements in a 'switch' come out of parsing with one + child node, so subsequent statements are just tucked to the parent + Compound. Additionally, consecutive (fall-through) case statements + come out messy. This is a peculiarity of the C grammar. The following: + + switch (myvar) { + case 10: + k = 10; + p = k + 1; + return 10; + case 20: + case 30: + return 20; + default: + break; + } + + Creates this tree (pseudo-dump): + + Switch + ID: myvar + Compound: + Case 10: + k = 10 + p = k + 1 + return 10 + Case 20: + Case 30: + return 20 + Default: + break + + The goal of this transform is to fix this mess, turning it into the + following: + + Switch + ID: myvar + Compound: + Case 10: + k = 10 + p = k + 1 + return 10 + Case 20: + Case 30: + return 20 + Default: + break + + A fixed AST node is returned. The argument may be modified. + """ + assert isinstance(switch_node, c_ast.Switch) + if not isinstance(switch_node.stmt, c_ast.Compound): + return switch_node + + # The new Compound child for the Switch, which will collect children in the + # correct order + new_compound = c_ast.Compound([], switch_node.stmt.coord) + + # The last Case/Default node + last_case: c_ast.Case | c_ast.Default | None = None + + # Goes over the children of the Compound below the Switch, adding them + # either directly below new_compound or below the last Case as appropriate + # (for `switch(cond) {}`, block_items would have been None) + for child in switch_node.stmt.block_items or []: + if isinstance(child, (c_ast.Case, c_ast.Default)): + # If it's a Case/Default: + # 1. Add it to the Compound and mark as "last case" + # 2. If its immediate child is also a Case or Default, promote it + # to a sibling. + new_compound.block_items.append(child) + _extract_nested_case(child, new_compound.block_items) + last_case = new_compound.block_items[-1] + else: + # Other statements are added as children to the last case, if it + # exists. + if last_case is None: + new_compound.block_items.append(child) + else: + last_case.stmts.append(child) + + switch_node.stmt = new_compound + return switch_node + + +def _extract_nested_case( + case_node: c_ast.Case | c_ast.Default, stmts_list: List[c_ast.Node] +) -> None: + """Recursively extract consecutive Case statements that are made nested + by the parser and add them to the stmts_list. + """ + if isinstance(case_node.stmts[0], (c_ast.Case, c_ast.Default)): + nested = case_node.stmts.pop() + stmts_list.append(nested) + _extract_nested_case(cast(Any, nested), stmts_list) + + +def fix_atomic_specifiers( + decl: c_ast.Decl | c_ast.Typedef, +) -> c_ast.Decl | c_ast.Typedef: + """Atomic specifiers like _Atomic(type) are unusually structured, + conferring a qualifier upon the contained type. + + This function fixes a decl with atomic specifiers to have a sane AST + structure, by removing spurious Typename->TypeDecl pairs and attaching + the _Atomic qualifier in the right place. + """ + # There can be multiple levels of _Atomic in a decl; fix them until a + # fixed point is reached. + while True: + decl, found = _fix_atomic_specifiers_once(decl) + if not found: + break + + # Make sure to add an _Atomic qual on the topmost decl if needed. Also + # restore the declname on the innermost TypeDecl (it gets placed in the + # wrong place during construction). + typ: Any = decl + while not isinstance(typ, c_ast.TypeDecl): + try: + typ = typ.type + except AttributeError: + return decl + if "_Atomic" in typ.quals and "_Atomic" not in decl.quals: + decl.quals.append("_Atomic") + if typ.declname is None: + typ.declname = decl.name + + return decl + + +def _fix_atomic_specifiers_once( + decl: c_ast.Decl | c_ast.Typedef, +) -> Tuple[c_ast.Decl | c_ast.Typedef, bool]: + """Performs one 'fix' round of atomic specifiers. + Returns (modified_decl, found) where found is True iff a fix was made. + """ + parent: Any = decl + grandparent: Any = None + node: Any = decl.type + while node is not None: + if isinstance(node, c_ast.Typename) and "_Atomic" in node.quals: + break + try: + grandparent = parent + parent = node + node = node.type + except AttributeError: + # If we've reached a node without a `type` field, it means we won't + # find what we're looking for at this point; give up the search + # and return the original decl unmodified. + return decl, False + + assert isinstance(parent, c_ast.TypeDecl) + assert grandparent is not None + cast(Any, grandparent).type = node.type + if "_Atomic" not in node.type.quals: + node.type.quals.append("_Atomic") + return decl, True diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pycparser/c_ast.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pycparser/c_ast.py new file mode 100644 index 0000000000000000000000000000000000000000..b6f42af8a183ee61b9ff8f2d85c60cd3eb18afc4 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pycparser/c_ast.py @@ -0,0 +1,1341 @@ +# ----------------------------------------------------------------- +# ** ATTENTION ** +# This code was automatically generated from _c_ast.cfg +# +# Do not modify it directly. Modify the configuration file and +# run the generator again. +# ** ** *** ** ** +# +# pycparser: c_ast.py +# +# AST Node classes. +# +# Eli Bendersky [https://eli.thegreenplace.net/] +# License: BSD +# ----------------------------------------------------------------- + + +import sys +from typing import Any, ClassVar, IO, Optional + + +def _repr(obj): + """ + Get the representation of an object, with dedicated pprint-like format for lists. + """ + if isinstance(obj, list): + return "[" + (",\n ".join((_repr(e).replace("\n", "\n ") for e in obj))) + "\n]" + else: + return repr(obj) + + +class Node: + __slots__ = () + """ Abstract base class for AST nodes. + """ + attr_names: ClassVar[tuple[str, ...]] = () + coord: Optional[Any] + + def __repr__(self): + """Generates a python representation of the current node""" + result = self.__class__.__name__ + "(" + + indent = "" + separator = "" + for name in self.__slots__[:-2]: + result += separator + result += indent + result += ( + name + + "=" + + ( + _repr(getattr(self, name)).replace( + "\n", + "\n " + (" " * (len(name) + len(self.__class__.__name__))), + ) + ) + ) + + separator = "," + indent = "\n " + (" " * len(self.__class__.__name__)) + + result += indent + ")" + + return result + + def children(self): + """A sequence of all children that are Nodes""" + pass + + def show( + self, + buf: IO[str] = sys.stdout, + offset: int = 0, + attrnames: bool = False, + showemptyattrs: bool = True, + nodenames: bool = False, + showcoord: bool = False, + _my_node_name: Optional[str] = None, + ): + """Pretty print the Node and all its attributes and + children (recursively) to a buffer. + + buf: + Open IO buffer into which the Node is printed. + + offset: + Initial offset (amount of leading spaces) + + attrnames: + True if you want to see the attribute names in + name=value pairs. False to only see the values. + + showemptyattrs: + False if you want to suppress printing empty attributes. + + nodenames: + True if you want to see the actual node names + within their parents. + + showcoord: + Do you want the coordinates of each Node to be + displayed. + """ + lead = " " * offset + if nodenames and _my_node_name is not None: + buf.write(lead + self.__class__.__name__ + " <" + _my_node_name + ">: ") + else: + buf.write(lead + self.__class__.__name__ + ": ") + + if self.attr_names: + + def is_empty(v): + v is None or (hasattr(v, "__len__") and len(v) == 0) + + nvlist = [ + (n, getattr(self, n)) + for n in self.attr_names + if showemptyattrs or not is_empty(getattr(self, n)) + ] + if attrnames: + attrstr = ", ".join(f"{name}={value}" for name, value in nvlist) + else: + attrstr = ", ".join(f"{value}" for _, value in nvlist) + buf.write(attrstr) + + if showcoord: + buf.write(f" (at {self.coord})") + buf.write("\n") + + for child_name, child in self.children(): + child.show( + buf, + offset=offset + 2, + attrnames=attrnames, + showemptyattrs=showemptyattrs, + nodenames=nodenames, + showcoord=showcoord, + _my_node_name=child_name, + ) + + +class NodeVisitor: + """A base NodeVisitor class for visiting c_ast nodes. + Subclass it and define your own visit_XXX methods, where + XXX is the class name you want to visit with these + methods. + + For example: + + class ConstantVisitor(NodeVisitor): + def __init__(self): + self.values = [] + + def visit_Constant(self, node): + self.values.append(node.value) + + Creates a list of values of all the constant nodes + encountered below the given node. To use it: + + cv = ConstantVisitor() + cv.visit(node) + + Notes: + + * generic_visit() will be called for AST nodes for which + no visit_XXX method was defined. + * The children of nodes for which a visit_XXX was + defined will not be visited - if you need this, call + generic_visit() on the node. + You can use: + NodeVisitor.generic_visit(self, node) + * Modeled after Python's own AST visiting facilities + (the ast module of Python 3.0) + """ + + _method_cache = None + + def visit(self, node: Node): + """Visit a node.""" + + if self._method_cache is None: + self._method_cache = {} + + visitor = self._method_cache.get(node.__class__.__name__, None) + if visitor is None: + method = "visit_" + node.__class__.__name__ + visitor = getattr(self, method, self.generic_visit) + self._method_cache[node.__class__.__name__] = visitor + + return visitor(node) + + def generic_visit(self, node: Node): + """Called if no explicit visitor function exists for a + node. Implements preorder visiting of the node. + """ + for _, c in node.children(): + self.visit(c) + + +class ArrayDecl(Node): + __slots__ = ("type", "dim", "dim_quals", "coord", "__weakref__") + + def __init__(self, type, dim, dim_quals, coord=None): + self.type = type + self.dim = dim + self.dim_quals = dim_quals + self.coord = coord + + def children(self): + nodelist = [] + if self.type is not None: + nodelist.append(("type", self.type)) + if self.dim is not None: + nodelist.append(("dim", self.dim)) + return tuple(nodelist) + + def __iter__(self): + if self.type is not None: + yield self.type + if self.dim is not None: + yield self.dim + + attr_names = ("dim_quals",) + + +class ArrayRef(Node): + __slots__ = ("name", "subscript", "coord", "__weakref__") + + def __init__(self, name, subscript, coord=None): + self.name = name + self.subscript = subscript + self.coord = coord + + def children(self): + nodelist = [] + if self.name is not None: + nodelist.append(("name", self.name)) + if self.subscript is not None: + nodelist.append(("subscript", self.subscript)) + return tuple(nodelist) + + def __iter__(self): + if self.name is not None: + yield self.name + if self.subscript is not None: + yield self.subscript + + attr_names = () + + +class Assignment(Node): + __slots__ = ("op", "lvalue", "rvalue", "coord", "__weakref__") + + def __init__(self, op, lvalue, rvalue, coord=None): + self.op = op + self.lvalue = lvalue + self.rvalue = rvalue + self.coord = coord + + def children(self): + nodelist = [] + if self.lvalue is not None: + nodelist.append(("lvalue", self.lvalue)) + if self.rvalue is not None: + nodelist.append(("rvalue", self.rvalue)) + return tuple(nodelist) + + def __iter__(self): + if self.lvalue is not None: + yield self.lvalue + if self.rvalue is not None: + yield self.rvalue + + attr_names = ("op",) + + +class Alignas(Node): + __slots__ = ("alignment", "coord", "__weakref__") + + def __init__(self, alignment, coord=None): + self.alignment = alignment + self.coord = coord + + def children(self): + nodelist = [] + if self.alignment is not None: + nodelist.append(("alignment", self.alignment)) + return tuple(nodelist) + + def __iter__(self): + if self.alignment is not None: + yield self.alignment + + attr_names = () + + +class BinaryOp(Node): + __slots__ = ("op", "left", "right", "coord", "__weakref__") + + def __init__(self, op, left, right, coord=None): + self.op = op + self.left = left + self.right = right + self.coord = coord + + def children(self): + nodelist = [] + if self.left is not None: + nodelist.append(("left", self.left)) + if self.right is not None: + nodelist.append(("right", self.right)) + return tuple(nodelist) + + def __iter__(self): + if self.left is not None: + yield self.left + if self.right is not None: + yield self.right + + attr_names = ("op",) + + +class Break(Node): + __slots__ = ("coord", "__weakref__") + + def __init__(self, coord=None): + self.coord = coord + + def children(self): + return () + + def __iter__(self): + return + yield + + attr_names = () + + +class Case(Node): + __slots__ = ("expr", "stmts", "coord", "__weakref__") + + def __init__(self, expr, stmts, coord=None): + self.expr = expr + self.stmts = stmts + self.coord = coord + + def children(self): + nodelist = [] + if self.expr is not None: + nodelist.append(("expr", self.expr)) + for i, child in enumerate(self.stmts or []): + nodelist.append((f"stmts[{i}]", child)) + return tuple(nodelist) + + def __iter__(self): + if self.expr is not None: + yield self.expr + for child in self.stmts or []: + yield child + + attr_names = () + + +class Cast(Node): + __slots__ = ("to_type", "expr", "coord", "__weakref__") + + def __init__(self, to_type, expr, coord=None): + self.to_type = to_type + self.expr = expr + self.coord = coord + + def children(self): + nodelist = [] + if self.to_type is not None: + nodelist.append(("to_type", self.to_type)) + if self.expr is not None: + nodelist.append(("expr", self.expr)) + return tuple(nodelist) + + def __iter__(self): + if self.to_type is not None: + yield self.to_type + if self.expr is not None: + yield self.expr + + attr_names = () + + +class Compound(Node): + __slots__ = ("block_items", "coord", "__weakref__") + + def __init__(self, block_items, coord=None): + self.block_items = block_items + self.coord = coord + + def children(self): + nodelist = [] + for i, child in enumerate(self.block_items or []): + nodelist.append((f"block_items[{i}]", child)) + return tuple(nodelist) + + def __iter__(self): + for child in self.block_items or []: + yield child + + attr_names = () + + +class CompoundLiteral(Node): + __slots__ = ("type", "init", "coord", "__weakref__") + + def __init__(self, type, init, coord=None): + self.type = type + self.init = init + self.coord = coord + + def children(self): + nodelist = [] + if self.type is not None: + nodelist.append(("type", self.type)) + if self.init is not None: + nodelist.append(("init", self.init)) + return tuple(nodelist) + + def __iter__(self): + if self.type is not None: + yield self.type + if self.init is not None: + yield self.init + + attr_names = () + + +class Constant(Node): + __slots__ = ("type", "value", "coord", "__weakref__") + + def __init__(self, type, value, coord=None): + self.type = type + self.value = value + self.coord = coord + + def children(self): + nodelist = [] + return tuple(nodelist) + + def __iter__(self): + return + yield + + attr_names = ( + "type", + "value", + ) + + +class Continue(Node): + __slots__ = ("coord", "__weakref__") + + def __init__(self, coord=None): + self.coord = coord + + def children(self): + return () + + def __iter__(self): + return + yield + + attr_names = () + + +class Decl(Node): + __slots__ = ( + "name", + "quals", + "align", + "storage", + "funcspec", + "type", + "init", + "bitsize", + "coord", + "__weakref__", + ) + + def __init__( + self, name, quals, align, storage, funcspec, type, init, bitsize, coord=None + ): + self.name = name + self.quals = quals + self.align = align + self.storage = storage + self.funcspec = funcspec + self.type = type + self.init = init + self.bitsize = bitsize + self.coord = coord + + def children(self): + nodelist = [] + if self.type is not None: + nodelist.append(("type", self.type)) + if self.init is not None: + nodelist.append(("init", self.init)) + if self.bitsize is not None: + nodelist.append(("bitsize", self.bitsize)) + return tuple(nodelist) + + def __iter__(self): + if self.type is not None: + yield self.type + if self.init is not None: + yield self.init + if self.bitsize is not None: + yield self.bitsize + + attr_names = ( + "name", + "quals", + "align", + "storage", + "funcspec", + ) + + +class DeclList(Node): + __slots__ = ("decls", "coord", "__weakref__") + + def __init__(self, decls, coord=None): + self.decls = decls + self.coord = coord + + def children(self): + nodelist = [] + for i, child in enumerate(self.decls or []): + nodelist.append((f"decls[{i}]", child)) + return tuple(nodelist) + + def __iter__(self): + for child in self.decls or []: + yield child + + attr_names = () + + +class Default(Node): + __slots__ = ("stmts", "coord", "__weakref__") + + def __init__(self, stmts, coord=None): + self.stmts = stmts + self.coord = coord + + def children(self): + nodelist = [] + for i, child in enumerate(self.stmts or []): + nodelist.append((f"stmts[{i}]", child)) + return tuple(nodelist) + + def __iter__(self): + for child in self.stmts or []: + yield child + + attr_names = () + + +class DoWhile(Node): + __slots__ = ("cond", "stmt", "coord", "__weakref__") + + def __init__(self, cond, stmt, coord=None): + self.cond = cond + self.stmt = stmt + self.coord = coord + + def children(self): + nodelist = [] + if self.cond is not None: + nodelist.append(("cond", self.cond)) + if self.stmt is not None: + nodelist.append(("stmt", self.stmt)) + return tuple(nodelist) + + def __iter__(self): + if self.cond is not None: + yield self.cond + if self.stmt is not None: + yield self.stmt + + attr_names = () + + +class EllipsisParam(Node): + __slots__ = ("coord", "__weakref__") + + def __init__(self, coord=None): + self.coord = coord + + def children(self): + return () + + def __iter__(self): + return + yield + + attr_names = () + + +class EmptyStatement(Node): + __slots__ = ("coord", "__weakref__") + + def __init__(self, coord=None): + self.coord = coord + + def children(self): + return () + + def __iter__(self): + return + yield + + attr_names = () + + +class Enum(Node): + __slots__ = ("name", "values", "coord", "__weakref__") + + def __init__(self, name, values, coord=None): + self.name = name + self.values = values + self.coord = coord + + def children(self): + nodelist = [] + if self.values is not None: + nodelist.append(("values", self.values)) + return tuple(nodelist) + + def __iter__(self): + if self.values is not None: + yield self.values + + attr_names = ("name",) + + +class Enumerator(Node): + __slots__ = ("name", "value", "coord", "__weakref__") + + def __init__(self, name, value, coord=None): + self.name = name + self.value = value + self.coord = coord + + def children(self): + nodelist = [] + if self.value is not None: + nodelist.append(("value", self.value)) + return tuple(nodelist) + + def __iter__(self): + if self.value is not None: + yield self.value + + attr_names = ("name",) + + +class EnumeratorList(Node): + __slots__ = ("enumerators", "coord", "__weakref__") + + def __init__(self, enumerators, coord=None): + self.enumerators = enumerators + self.coord = coord + + def children(self): + nodelist = [] + for i, child in enumerate(self.enumerators or []): + nodelist.append((f"enumerators[{i}]", child)) + return tuple(nodelist) + + def __iter__(self): + for child in self.enumerators or []: + yield child + + attr_names = () + + +class ExprList(Node): + __slots__ = ("exprs", "coord", "__weakref__") + + def __init__(self, exprs, coord=None): + self.exprs = exprs + self.coord = coord + + def children(self): + nodelist = [] + for i, child in enumerate(self.exprs or []): + nodelist.append((f"exprs[{i}]", child)) + return tuple(nodelist) + + def __iter__(self): + for child in self.exprs or []: + yield child + + attr_names = () + + +class FileAST(Node): + __slots__ = ("ext", "coord", "__weakref__") + + def __init__(self, ext, coord=None): + self.ext = ext + self.coord = coord + + def children(self): + nodelist = [] + for i, child in enumerate(self.ext or []): + nodelist.append((f"ext[{i}]", child)) + return tuple(nodelist) + + def __iter__(self): + for child in self.ext or []: + yield child + + attr_names = () + + +class For(Node): + __slots__ = ("init", "cond", "next", "stmt", "coord", "__weakref__") + + def __init__(self, init, cond, next, stmt, coord=None): + self.init = init + self.cond = cond + self.next = next + self.stmt = stmt + self.coord = coord + + def children(self): + nodelist = [] + if self.init is not None: + nodelist.append(("init", self.init)) + if self.cond is not None: + nodelist.append(("cond", self.cond)) + if self.next is not None: + nodelist.append(("next", self.next)) + if self.stmt is not None: + nodelist.append(("stmt", self.stmt)) + return tuple(nodelist) + + def __iter__(self): + if self.init is not None: + yield self.init + if self.cond is not None: + yield self.cond + if self.next is not None: + yield self.next + if self.stmt is not None: + yield self.stmt + + attr_names = () + + +class FuncCall(Node): + __slots__ = ("name", "args", "coord", "__weakref__") + + def __init__(self, name, args, coord=None): + self.name = name + self.args = args + self.coord = coord + + def children(self): + nodelist = [] + if self.name is not None: + nodelist.append(("name", self.name)) + if self.args is not None: + nodelist.append(("args", self.args)) + return tuple(nodelist) + + def __iter__(self): + if self.name is not None: + yield self.name + if self.args is not None: + yield self.args + + attr_names = () + + +class FuncDecl(Node): + __slots__ = ("args", "type", "coord", "__weakref__") + + def __init__(self, args, type, coord=None): + self.args = args + self.type = type + self.coord = coord + + def children(self): + nodelist = [] + if self.args is not None: + nodelist.append(("args", self.args)) + if self.type is not None: + nodelist.append(("type", self.type)) + return tuple(nodelist) + + def __iter__(self): + if self.args is not None: + yield self.args + if self.type is not None: + yield self.type + + attr_names = () + + +class FuncDef(Node): + __slots__ = ("decl", "param_decls", "body", "coord", "__weakref__") + + def __init__(self, decl, param_decls, body, coord=None): + self.decl = decl + self.param_decls = param_decls + self.body = body + self.coord = coord + + def children(self): + nodelist = [] + if self.decl is not None: + nodelist.append(("decl", self.decl)) + if self.body is not None: + nodelist.append(("body", self.body)) + for i, child in enumerate(self.param_decls or []): + nodelist.append((f"param_decls[{i}]", child)) + return tuple(nodelist) + + def __iter__(self): + if self.decl is not None: + yield self.decl + if self.body is not None: + yield self.body + for child in self.param_decls or []: + yield child + + attr_names = () + + +class Goto(Node): + __slots__ = ("name", "coord", "__weakref__") + + def __init__(self, name, coord=None): + self.name = name + self.coord = coord + + def children(self): + nodelist = [] + return tuple(nodelist) + + def __iter__(self): + return + yield + + attr_names = ("name",) + + +class ID(Node): + __slots__ = ("name", "coord", "__weakref__") + + def __init__(self, name, coord=None): + self.name = name + self.coord = coord + + def children(self): + nodelist = [] + return tuple(nodelist) + + def __iter__(self): + return + yield + + attr_names = ("name",) + + +class IdentifierType(Node): + __slots__ = ("names", "coord", "__weakref__") + + def __init__(self, names, coord=None): + self.names = names + self.coord = coord + + def children(self): + nodelist = [] + return tuple(nodelist) + + def __iter__(self): + return + yield + + attr_names = ("names",) + + +class If(Node): + __slots__ = ("cond", "iftrue", "iffalse", "coord", "__weakref__") + + def __init__(self, cond, iftrue, iffalse, coord=None): + self.cond = cond + self.iftrue = iftrue + self.iffalse = iffalse + self.coord = coord + + def children(self): + nodelist = [] + if self.cond is not None: + nodelist.append(("cond", self.cond)) + if self.iftrue is not None: + nodelist.append(("iftrue", self.iftrue)) + if self.iffalse is not None: + nodelist.append(("iffalse", self.iffalse)) + return tuple(nodelist) + + def __iter__(self): + if self.cond is not None: + yield self.cond + if self.iftrue is not None: + yield self.iftrue + if self.iffalse is not None: + yield self.iffalse + + attr_names = () + + +class InitList(Node): + __slots__ = ("exprs", "coord", "__weakref__") + + def __init__(self, exprs, coord=None): + self.exprs = exprs + self.coord = coord + + def children(self): + nodelist = [] + for i, child in enumerate(self.exprs or []): + nodelist.append((f"exprs[{i}]", child)) + return tuple(nodelist) + + def __iter__(self): + for child in self.exprs or []: + yield child + + attr_names = () + + +class Label(Node): + __slots__ = ("name", "stmt", "coord", "__weakref__") + + def __init__(self, name, stmt, coord=None): + self.name = name + self.stmt = stmt + self.coord = coord + + def children(self): + nodelist = [] + if self.stmt is not None: + nodelist.append(("stmt", self.stmt)) + return tuple(nodelist) + + def __iter__(self): + if self.stmt is not None: + yield self.stmt + + attr_names = ("name",) + + +class NamedInitializer(Node): + __slots__ = ("name", "expr", "coord", "__weakref__") + + def __init__(self, name, expr, coord=None): + self.name = name + self.expr = expr + self.coord = coord + + def children(self): + nodelist = [] + if self.expr is not None: + nodelist.append(("expr", self.expr)) + for i, child in enumerate(self.name or []): + nodelist.append((f"name[{i}]", child)) + return tuple(nodelist) + + def __iter__(self): + if self.expr is not None: + yield self.expr + for child in self.name or []: + yield child + + attr_names = () + + +class ParamList(Node): + __slots__ = ("params", "coord", "__weakref__") + + def __init__(self, params, coord=None): + self.params = params + self.coord = coord + + def children(self): + nodelist = [] + for i, child in enumerate(self.params or []): + nodelist.append((f"params[{i}]", child)) + return tuple(nodelist) + + def __iter__(self): + for child in self.params or []: + yield child + + attr_names = () + + +class PtrDecl(Node): + __slots__ = ("quals", "type", "coord", "__weakref__") + + def __init__(self, quals, type, coord=None): + self.quals = quals + self.type = type + self.coord = coord + + def children(self): + nodelist = [] + if self.type is not None: + nodelist.append(("type", self.type)) + return tuple(nodelist) + + def __iter__(self): + if self.type is not None: + yield self.type + + attr_names = ("quals",) + + +class Return(Node): + __slots__ = ("expr", "coord", "__weakref__") + + def __init__(self, expr, coord=None): + self.expr = expr + self.coord = coord + + def children(self): + nodelist = [] + if self.expr is not None: + nodelist.append(("expr", self.expr)) + return tuple(nodelist) + + def __iter__(self): + if self.expr is not None: + yield self.expr + + attr_names = () + + +class StaticAssert(Node): + __slots__ = ("cond", "message", "coord", "__weakref__") + + def __init__(self, cond, message, coord=None): + self.cond = cond + self.message = message + self.coord = coord + + def children(self): + nodelist = [] + if self.cond is not None: + nodelist.append(("cond", self.cond)) + if self.message is not None: + nodelist.append(("message", self.message)) + return tuple(nodelist) + + def __iter__(self): + if self.cond is not None: + yield self.cond + if self.message is not None: + yield self.message + + attr_names = () + + +class Struct(Node): + __slots__ = ("name", "decls", "coord", "__weakref__") + + def __init__(self, name, decls, coord=None): + self.name = name + self.decls = decls + self.coord = coord + + def children(self): + nodelist = [] + for i, child in enumerate(self.decls or []): + nodelist.append((f"decls[{i}]", child)) + return tuple(nodelist) + + def __iter__(self): + for child in self.decls or []: + yield child + + attr_names = ("name",) + + +class StructRef(Node): + __slots__ = ("name", "type", "field", "coord", "__weakref__") + + def __init__(self, name, type, field, coord=None): + self.name = name + self.type = type + self.field = field + self.coord = coord + + def children(self): + nodelist = [] + if self.name is not None: + nodelist.append(("name", self.name)) + if self.field is not None: + nodelist.append(("field", self.field)) + return tuple(nodelist) + + def __iter__(self): + if self.name is not None: + yield self.name + if self.field is not None: + yield self.field + + attr_names = ("type",) + + +class Switch(Node): + __slots__ = ("cond", "stmt", "coord", "__weakref__") + + def __init__(self, cond, stmt, coord=None): + self.cond = cond + self.stmt = stmt + self.coord = coord + + def children(self): + nodelist = [] + if self.cond is not None: + nodelist.append(("cond", self.cond)) + if self.stmt is not None: + nodelist.append(("stmt", self.stmt)) + return tuple(nodelist) + + def __iter__(self): + if self.cond is not None: + yield self.cond + if self.stmt is not None: + yield self.stmt + + attr_names = () + + +class TernaryOp(Node): + __slots__ = ("cond", "iftrue", "iffalse", "coord", "__weakref__") + + def __init__(self, cond, iftrue, iffalse, coord=None): + self.cond = cond + self.iftrue = iftrue + self.iffalse = iffalse + self.coord = coord + + def children(self): + nodelist = [] + if self.cond is not None: + nodelist.append(("cond", self.cond)) + if self.iftrue is not None: + nodelist.append(("iftrue", self.iftrue)) + if self.iffalse is not None: + nodelist.append(("iffalse", self.iffalse)) + return tuple(nodelist) + + def __iter__(self): + if self.cond is not None: + yield self.cond + if self.iftrue is not None: + yield self.iftrue + if self.iffalse is not None: + yield self.iffalse + + attr_names = () + + +class TypeDecl(Node): + __slots__ = ("declname", "quals", "align", "type", "coord", "__weakref__") + + def __init__(self, declname, quals, align, type, coord=None): + self.declname = declname + self.quals = quals + self.align = align + self.type = type + self.coord = coord + + def children(self): + nodelist = [] + if self.type is not None: + nodelist.append(("type", self.type)) + return tuple(nodelist) + + def __iter__(self): + if self.type is not None: + yield self.type + + attr_names = ( + "declname", + "quals", + "align", + ) + + +class Typedef(Node): + __slots__ = ("name", "quals", "storage", "type", "coord", "__weakref__") + + def __init__(self, name, quals, storage, type, coord=None): + self.name = name + self.quals = quals + self.storage = storage + self.type = type + self.coord = coord + + def children(self): + nodelist = [] + if self.type is not None: + nodelist.append(("type", self.type)) + return tuple(nodelist) + + def __iter__(self): + if self.type is not None: + yield self.type + + attr_names = ( + "name", + "quals", + "storage", + ) + + +class Typename(Node): + __slots__ = ("name", "quals", "align", "type", "coord", "__weakref__") + + def __init__(self, name, quals, align, type, coord=None): + self.name = name + self.quals = quals + self.align = align + self.type = type + self.coord = coord + + def children(self): + nodelist = [] + if self.type is not None: + nodelist.append(("type", self.type)) + return tuple(nodelist) + + def __iter__(self): + if self.type is not None: + yield self.type + + attr_names = ( + "name", + "quals", + "align", + ) + + +class UnaryOp(Node): + __slots__ = ("op", "expr", "coord", "__weakref__") + + def __init__(self, op, expr, coord=None): + self.op = op + self.expr = expr + self.coord = coord + + def children(self): + nodelist = [] + if self.expr is not None: + nodelist.append(("expr", self.expr)) + return tuple(nodelist) + + def __iter__(self): + if self.expr is not None: + yield self.expr + + attr_names = ("op",) + + +class Union(Node): + __slots__ = ("name", "decls", "coord", "__weakref__") + + def __init__(self, name, decls, coord=None): + self.name = name + self.decls = decls + self.coord = coord + + def children(self): + nodelist = [] + for i, child in enumerate(self.decls or []): + nodelist.append((f"decls[{i}]", child)) + return tuple(nodelist) + + def __iter__(self): + for child in self.decls or []: + yield child + + attr_names = ("name",) + + +class While(Node): + __slots__ = ("cond", "stmt", "coord", "__weakref__") + + def __init__(self, cond, stmt, coord=None): + self.cond = cond + self.stmt = stmt + self.coord = coord + + def children(self): + nodelist = [] + if self.cond is not None: + nodelist.append(("cond", self.cond)) + if self.stmt is not None: + nodelist.append(("stmt", self.stmt)) + return tuple(nodelist) + + def __iter__(self): + if self.cond is not None: + yield self.cond + if self.stmt is not None: + yield self.stmt + + attr_names = () + + +class Pragma(Node): + __slots__ = ("string", "coord", "__weakref__") + + def __init__(self, string, coord=None): + self.string = string + self.coord = coord + + def children(self): + nodelist = [] + return tuple(nodelist) + + def __iter__(self): + return + yield + + attr_names = ("string",) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pycparser/c_generator.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pycparser/c_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..424e00e06bec67f6285e51947a3896a81592ae49 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pycparser/c_generator.py @@ -0,0 +1,573 @@ +# ------------------------------------------------------------------------------ +# pycparser: c_generator.py +# +# C code generator from pycparser AST nodes. +# +# Eli Bendersky [https://eli.thegreenplace.net/] +# License: BSD +# ------------------------------------------------------------------------------ +from typing import Callable, List, Optional + +from . import c_ast + + +class CGenerator: + """Uses the same visitor pattern as c_ast.NodeVisitor, but modified to + return a value from each visit method, using string accumulation in + generic_visit. + """ + + indent_level: int + reduce_parentheses: bool + + def __init__(self, reduce_parentheses: bool = False) -> None: + """Constructs C-code generator + + reduce_parentheses: + if True, eliminates needless parentheses on binary operators + """ + # Statements start with indentation of self.indent_level spaces, using + # the _make_indent method. + self.indent_level = 0 + self.reduce_parentheses = reduce_parentheses + + def _make_indent(self) -> str: + return " " * self.indent_level + + def visit(self, node: c_ast.Node) -> str: + method = "visit_" + node.__class__.__name__ + return getattr(self, method, self.generic_visit)(node) + + def generic_visit(self, node: Optional[c_ast.Node]) -> str: + if node is None: + return "" + else: + return "".join(self.visit(c) for c_name, c in node.children()) + + def visit_Constant(self, n: c_ast.Constant) -> str: + return n.value + + def visit_ID(self, n: c_ast.ID) -> str: + return n.name + + def visit_Pragma(self, n: c_ast.Pragma) -> str: + ret = "#pragma" + if n.string: + ret += " " + n.string + return ret + + def visit_ArrayRef(self, n: c_ast.ArrayRef) -> str: + arrref = self._parenthesize_unless_simple(n.name) + return arrref + "[" + self.visit(n.subscript) + "]" + + def visit_StructRef(self, n: c_ast.StructRef) -> str: + sref = self._parenthesize_unless_simple(n.name) + return sref + n.type + self.visit(n.field) + + def visit_FuncCall(self, n: c_ast.FuncCall) -> str: + fref = self._parenthesize_unless_simple(n.name) + args = self.visit(n.args) if n.args is not None else "" + return fref + "(" + args + ")" + + def visit_UnaryOp(self, n: c_ast.UnaryOp) -> str: + match n.op: + case "sizeof": + # Always parenthesize the argument of sizeof since it can be + # a name. + return f"sizeof({self.visit(n.expr)})" + case "p++": + operand = self._parenthesize_unless_simple(n.expr) + return f"{operand}++" + case "p--": + operand = self._parenthesize_unless_simple(n.expr) + return f"{operand}--" + case _: + operand = self._parenthesize_unless_simple(n.expr) + return f"{n.op}{operand}" + + # Precedence map of binary operators: + precedence_map = { + # Should be in sync with c_parser.CParser.precedence + # Higher numbers are stronger binding + "||": 0, # weakest binding + "&&": 1, + "|": 2, + "^": 3, + "&": 4, + "==": 5, + "!=": 5, + ">": 6, + ">=": 6, + "<": 6, + "<=": 6, + ">>": 7, + "<<": 7, + "+": 8, + "-": 8, + "*": 9, + "/": 9, + "%": 9, # strongest binding + } + + def visit_BinaryOp(self, n: c_ast.BinaryOp) -> str: + # Note: all binary operators are left-to-right associative + # + # If `n.left.op` has a stronger or equally binding precedence in + # comparison to `n.op`, no parenthesis are needed for the left: + # e.g., `(a*b) + c` is equivalent to `a*b + c`, as well as + # `(a+b) - c` is equivalent to `a+b - c` (same precedence). + # If the left operator is weaker binding than the current, then + # parentheses are necessary: + # e.g., `(a+b) * c` is NOT equivalent to `a+b * c`. + lval_str = self._parenthesize_if( + n.left, + lambda d: not ( + self._is_simple_node(d) + or self.reduce_parentheses + and isinstance(d, c_ast.BinaryOp) + and self.precedence_map[d.op] >= self.precedence_map[n.op] + ), + ) + # If `n.right.op` has a stronger -but not equal- binding precedence, + # parenthesis can be omitted on the right: + # e.g., `a + (b*c)` is equivalent to `a + b*c`. + # If the right operator is weaker or equally binding, then parentheses + # are necessary: + # e.g., `a * (b+c)` is NOT equivalent to `a * b+c` and + # `a - (b+c)` is NOT equivalent to `a - b+c` (same precedence). + rval_str = self._parenthesize_if( + n.right, + lambda d: not ( + self._is_simple_node(d) + or self.reduce_parentheses + and isinstance(d, c_ast.BinaryOp) + and self.precedence_map[d.op] > self.precedence_map[n.op] + ), + ) + return f"{lval_str} {n.op} {rval_str}" + + def visit_Assignment(self, n: c_ast.Assignment) -> str: + rval_str = self._parenthesize_if( + n.rvalue, lambda n: isinstance(n, c_ast.Assignment) + ) + return f"{self.visit(n.lvalue)} {n.op} {rval_str}" + + def visit_IdentifierType(self, n: c_ast.IdentifierType) -> str: + return " ".join(n.names) + + def _visit_expr(self, n: c_ast.Node) -> str: + match n: + case c_ast.InitList(): + return "{" + self.visit(n) + "}" + case c_ast.ExprList() | c_ast.Compound(): + return "(" + self.visit(n) + ")" + case _: + return self.visit(n) + + def visit_Decl(self, n: c_ast.Decl, no_type: bool = False) -> str: + # no_type is used when a Decl is part of a DeclList, where the type is + # explicitly only for the first declaration in a list. + # + s = n.name if no_type else self._generate_decl(n) + if n.bitsize: + s += " : " + self.visit(n.bitsize) + if n.init: + s += " = " + self._visit_expr(n.init) + return s + + def visit_DeclList(self, n: c_ast.DeclList) -> str: + s = self.visit(n.decls[0]) + if len(n.decls) > 1: + s += ", " + ", ".join( + self.visit_Decl(decl, no_type=True) for decl in n.decls[1:] + ) + return s + + def visit_Typedef(self, n: c_ast.Typedef) -> str: + s = "" + if n.storage: + s += " ".join(n.storage) + " " + s += self._generate_type(n.type) + return s + + def visit_Cast(self, n: c_ast.Cast) -> str: + s = "(" + self._generate_type(n.to_type, emit_declname=False) + ")" + return s + " " + self._parenthesize_unless_simple(n.expr) + + def visit_ExprList(self, n: c_ast.ExprList) -> str: + visited_subexprs = [] + for expr in n.exprs: + visited_subexprs.append(self._visit_expr(expr)) + return ", ".join(visited_subexprs) + + def visit_InitList(self, n: c_ast.InitList) -> str: + visited_subexprs = [] + for expr in n.exprs: + visited_subexprs.append(self._visit_expr(expr)) + return ", ".join(visited_subexprs) + + def visit_Enum(self, n: c_ast.Enum) -> str: + return self._generate_struct_union_enum(n, name="enum") + + def visit_Alignas(self, n: c_ast.Alignas) -> str: + return "_Alignas({})".format(self.visit(n.alignment)) + + def visit_Enumerator(self, n: c_ast.Enumerator) -> str: + if not n.value: + return "{indent}{name},\n".format( + indent=self._make_indent(), + name=n.name, + ) + else: + return "{indent}{name} = {value},\n".format( + indent=self._make_indent(), + name=n.name, + value=self.visit(n.value), + ) + + def visit_FuncDef(self, n: c_ast.FuncDef) -> str: + decl = self.visit(n.decl) + self.indent_level = 0 + body = self.visit(n.body) + if n.param_decls: + knrdecls = ";\n".join(self.visit(p) for p in n.param_decls) + return decl + "\n" + knrdecls + ";\n" + body + "\n" + else: + return decl + "\n" + body + "\n" + + def visit_FileAST(self, n: c_ast.FileAST) -> str: + s = "" + for ext in n.ext: + match ext: + case c_ast.FuncDef(): + s += self.visit(ext) + case c_ast.Pragma(): + s += self.visit(ext) + "\n" + case _: + s += self.visit(ext) + ";\n" + return s + + def visit_Compound(self, n: c_ast.Compound) -> str: + s = self._make_indent() + "{\n" + self.indent_level += 2 + if n.block_items: + s += "".join(self._generate_stmt(stmt) for stmt in n.block_items) + self.indent_level -= 2 + s += self._make_indent() + "}\n" + return s + + def visit_CompoundLiteral(self, n: c_ast.CompoundLiteral) -> str: + return "(" + self.visit(n.type) + "){" + self.visit(n.init) + "}" + + def visit_EmptyStatement(self, n: c_ast.EmptyStatement) -> str: + return ";" + + def visit_ParamList(self, n: c_ast.ParamList) -> str: + return ", ".join(self.visit(param) for param in n.params) + + def visit_Return(self, n: c_ast.Return) -> str: + s = "return" + if n.expr: + s += " " + self.visit(n.expr) + return s + ";" + + def visit_Break(self, n: c_ast.Break) -> str: + return "break;" + + def visit_Continue(self, n: c_ast.Continue) -> str: + return "continue;" + + def visit_TernaryOp(self, n: c_ast.TernaryOp) -> str: + s = "(" + self._visit_expr(n.cond) + ") ? " + s += "(" + self._visit_expr(n.iftrue) + ") : " + s += "(" + self._visit_expr(n.iffalse) + ")" + return s + + def visit_If(self, n: c_ast.If) -> str: + s = "if (" + if n.cond: + s += self.visit(n.cond) + s += ")\n" + s += self._generate_stmt(n.iftrue, add_indent=True) + if n.iffalse: + s += self._make_indent() + "else\n" + s += self._generate_stmt(n.iffalse, add_indent=True) + return s + + def visit_For(self, n: c_ast.For) -> str: + s = "for (" + if n.init: + s += self.visit(n.init) + s += ";" + if n.cond: + s += " " + self.visit(n.cond) + s += ";" + if n.next: + s += " " + self.visit(n.next) + s += ")\n" + s += self._generate_stmt(n.stmt, add_indent=True) + return s + + def visit_While(self, n: c_ast.While) -> str: + s = "while (" + if n.cond: + s += self.visit(n.cond) + s += ")\n" + s += self._generate_stmt(n.stmt, add_indent=True) + return s + + def visit_DoWhile(self, n: c_ast.DoWhile) -> str: + s = "do\n" + s += self._generate_stmt(n.stmt, add_indent=True) + s += self._make_indent() + "while (" + if n.cond: + s += self.visit(n.cond) + s += ");" + return s + + def visit_StaticAssert(self, n: c_ast.StaticAssert) -> str: + s = "_Static_assert(" + s += self.visit(n.cond) + if n.message: + s += "," + s += self.visit(n.message) + s += ")" + return s + + def visit_Switch(self, n: c_ast.Switch) -> str: + s = "switch (" + self.visit(n.cond) + ")\n" + s += self._generate_stmt(n.stmt, add_indent=True) + return s + + def visit_Case(self, n: c_ast.Case) -> str: + s = "case " + self.visit(n.expr) + ":\n" + for stmt in n.stmts: + s += self._generate_stmt(stmt, add_indent=True) + return s + + def visit_Default(self, n: c_ast.Default) -> str: + s = "default:\n" + for stmt in n.stmts: + s += self._generate_stmt(stmt, add_indent=True) + return s + + def visit_Label(self, n: c_ast.Label) -> str: + return n.name + ":\n" + self._generate_stmt(n.stmt) + + def visit_Goto(self, n: c_ast.Goto) -> str: + return "goto " + n.name + ";" + + def visit_EllipsisParam(self, n: c_ast.EllipsisParam) -> str: + return "..." + + def visit_Struct(self, n: c_ast.Struct) -> str: + return self._generate_struct_union_enum(n, "struct") + + def visit_Typename(self, n: c_ast.Typename) -> str: + return self._generate_type(n.type) + + def visit_Union(self, n: c_ast.Union) -> str: + return self._generate_struct_union_enum(n, "union") + + def visit_NamedInitializer(self, n: c_ast.NamedInitializer) -> str: + s = "" + for name in n.name: + if isinstance(name, c_ast.ID): + s += "." + name.name + else: + s += "[" + self.visit(name) + "]" + s += " = " + self._visit_expr(n.expr) + return s + + def visit_FuncDecl(self, n: c_ast.FuncDecl) -> str: + return self._generate_type(n) + + def visit_ArrayDecl(self, n: c_ast.ArrayDecl) -> str: + return self._generate_type(n, emit_declname=False) + + def visit_TypeDecl(self, n: c_ast.TypeDecl) -> str: + return self._generate_type(n, emit_declname=False) + + def visit_PtrDecl(self, n: c_ast.PtrDecl) -> str: + return self._generate_type(n, emit_declname=False) + + def _generate_struct_union_enum( + self, n: c_ast.Struct | c_ast.Union | c_ast.Enum, name: str + ) -> str: + """Generates code for structs, unions, and enums. name should be + 'struct', 'union', or 'enum'. + """ + if name in ("struct", "union"): + assert isinstance(n, (c_ast.Struct, c_ast.Union)) + members = n.decls + body_function = self._generate_struct_union_body + else: + assert name == "enum" + assert isinstance(n, c_ast.Enum) + members = None if n.values is None else n.values.enumerators + body_function = self._generate_enum_body + s = name + " " + (n.name or "") + if members is not None: + # None means no members + # Empty sequence means an empty list of members + s += "\n" + s += self._make_indent() + self.indent_level += 2 + s += "{\n" + s += body_function(members) + self.indent_level -= 2 + s += self._make_indent() + "}" + return s + + def _generate_struct_union_body(self, members: List[c_ast.Node]) -> str: + return "".join(self._generate_stmt(decl) for decl in members) + + def _generate_enum_body(self, members: List[c_ast.Enumerator]) -> str: + # `[:-2] + '\n'` removes the final `,` from the enumerator list + return "".join(self.visit(value) for value in members)[:-2] + "\n" + + def _generate_stmt(self, n: c_ast.Node, add_indent: bool = False) -> str: + """Generation from a statement node. This method exists as a wrapper + for individual visit_* methods to handle different treatment of + some statements in this context. + """ + if add_indent: + self.indent_level += 2 + indent = self._make_indent() + if add_indent: + self.indent_level -= 2 + + match n: + case ( + c_ast.Decl() + | c_ast.Assignment() + | c_ast.Cast() + | c_ast.UnaryOp() + | c_ast.BinaryOp() + | c_ast.TernaryOp() + | c_ast.FuncCall() + | c_ast.ArrayRef() + | c_ast.StructRef() + | c_ast.Constant() + | c_ast.ID() + | c_ast.Typedef() + | c_ast.ExprList() + ): + # These can also appear in an expression context so no semicolon + # is added to them automatically + # + return indent + self.visit(n) + ";\n" + case c_ast.Compound(): + # No extra indentation required before the opening brace of a + # compound - because it consists of multiple lines it has to + # compute its own indentation. + # + return self.visit(n) + case c_ast.If(): + return indent + self.visit(n) + case _: + return indent + self.visit(n) + "\n" + + def _generate_decl(self, n: c_ast.Decl) -> str: + """Generation from a Decl node.""" + s = "" + if n.funcspec: + s = " ".join(n.funcspec) + " " + if n.storage: + s += " ".join(n.storage) + " " + if n.align: + s += self.visit(n.align[0]) + " " + s += self._generate_type(n.type) + return s + + def _generate_type( + self, + n: c_ast.Node, + modifiers: List[c_ast.Node] = [], + emit_declname: bool = True, + ) -> str: + """Recursive generation from a type node. n is the type node. + modifiers collects the PtrDecl, ArrayDecl and FuncDecl modifiers + encountered on the way down to a TypeDecl, to allow proper + generation from it. + """ + # ~ print(n, modifiers) + match n: + case c_ast.TypeDecl(): + s = "" + if n.quals: + s += " ".join(n.quals) + " " + s += self.visit(n.type) + + nstr = n.declname if n.declname and emit_declname else "" + # Resolve modifiers. + # Wrap in parens to distinguish pointer to array and pointer to + # function syntax. + # + for i, modifier in enumerate(modifiers): + match modifier: + case c_ast.ArrayDecl(): + if i != 0 and isinstance(modifiers[i - 1], c_ast.PtrDecl): + nstr = "(" + nstr + ")" + nstr += "[" + if modifier.dim_quals: + nstr += " ".join(modifier.dim_quals) + " " + if modifier.dim is not None: + nstr += self.visit(modifier.dim) + nstr += "]" + case c_ast.FuncDecl(): + if i != 0 and isinstance(modifiers[i - 1], c_ast.PtrDecl): + nstr = "(" + nstr + ")" + args = ( + self.visit(modifier.args) + if modifier.args is not None + else "" + ) + nstr += "(" + args + ")" + case c_ast.PtrDecl(): + if modifier.quals: + quals = " ".join(modifier.quals) + suffix = f" {nstr}" if nstr else "" + nstr = f"* {quals}{suffix}" + else: + nstr = "*" + nstr + if nstr: + s += " " + nstr + return s + case c_ast.Decl(): + return self._generate_decl(n.type) + case c_ast.Typename(): + return self._generate_type(n.type, emit_declname=emit_declname) + case c_ast.IdentifierType(): + return " ".join(n.names) + " " + case c_ast.ArrayDecl() | c_ast.PtrDecl() | c_ast.FuncDecl(): + return self._generate_type( + n.type, modifiers + [n], emit_declname=emit_declname + ) + case _: + return self.visit(n) + + def _parenthesize_if( + self, n: c_ast.Node, condition: Callable[[c_ast.Node], bool] + ) -> str: + """Visits 'n' and returns its string representation, parenthesized + if the condition function applied to the node returns True. + """ + s = self._visit_expr(n) + if condition(n): + return "(" + s + ")" + else: + return s + + def _parenthesize_unless_simple(self, n: c_ast.Node) -> str: + """Common use case for _parenthesize_if""" + return self._parenthesize_if(n, lambda d: not self._is_simple_node(d)) + + def _is_simple_node(self, n: c_ast.Node) -> bool: + """Returns True for nodes that are "simple" - i.e. nodes that always + have higher precedence than operators. + """ + return isinstance( + n, + (c_ast.Constant, c_ast.ID, c_ast.ArrayRef, c_ast.StructRef, c_ast.FuncCall), + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pycparser/c_lexer.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pycparser/c_lexer.py new file mode 100644 index 0000000000000000000000000000000000000000..ef59d695448751017f34fb033196a0217f48e5f0 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pycparser/c_lexer.py @@ -0,0 +1,706 @@ +# ------------------------------------------------------------------------------ +# pycparser: c_lexer.py +# +# CLexer class: lexer for the C language +# +# Eli Bendersky [https://eli.thegreenplace.net/] +# License: BSD +# ------------------------------------------------------------------------------ +import re +from dataclasses import dataclass +from enum import Enum +from typing import Callable, Dict, List, Optional, Tuple + + +@dataclass(slots=True) +class _Token: + type: str + value: str + lineno: int + column: int + + +class CLexer: + """A standalone lexer for C. + + Parameters for construction: + error_func: + Called with (msg, line, column) on lexing errors. + on_lbrace_func: + Called when an LBRACE token is produced (used for scope tracking). + on_rbrace_func: + Called when an RBRACE token is produced (used for scope tracking). + type_lookup_func: + Called with an identifier name; expected to return True if it is + a typedef name and should be tokenized as TYPEID. + + Call input(text) to initialize lexing, and then keep calling token() to + get the next token, until it returns None (at end of input). + """ + + def __init__( + self, + error_func: Callable[[str, int, int], None], + on_lbrace_func: Callable[[], None], + on_rbrace_func: Callable[[], None], + type_lookup_func: Callable[[str], bool], + ) -> None: + self.error_func = error_func + self.on_lbrace_func = on_lbrace_func + self.on_rbrace_func = on_rbrace_func + self.type_lookup_func = type_lookup_func + self._init_state() + + def input(self, text: str, filename: str = "") -> None: + """Initialize the lexer to the given input text. + + filename is an optional name identifying the file from which the input + comes. The lexer can modify it if #line directives are encountered. + """ + self._init_state() + self._lexdata = text + self._filename = filename + + def _init_state(self) -> None: + self._lexdata = "" + self._filename = "" + self._pos = 0 + self._line_start = 0 + self._pending_tok: Optional[_Token] = None + self._lineno = 1 + + @property + def filename(self) -> str: + return self._filename + + def token(self) -> Optional[_Token]: + # Lexing strategy overview: + # + # - We maintain a current position (self._pos), line number, and the + # byte offset of the current line start. The lexer is a simple loop + # that skips whitespace/newlines and emits one token per call. + # - A small amount of logic is handled manually before regex matching: + # + # * Preprocessor-style directives: if we see '#', we check whether + # it's a #line or #pragma directive and consume it inline. #line + # updates lineno/filename and produces no tokens. #pragma can yield + # both PPPRAGMA and PPPRAGMASTR, but token() returns a single token, + # so we stash the PPPRAGMASTR as _pending_tok to return on the next + # token() call. Otherwise we return PPHASH. + # * Newlines update lineno/line-start tracking so tokens can record + # accurate columns. + # + # - The bulk of tokens are recognized in _match_token: + # + # * _regex_rules: regex patterns for identifiers, literals, and other + # complex tokens (including error-producing patterns). The lexer + # uses a combined _regex_master to scan options at the same time. + # * _fixed_tokens: exact string matches for operators and punctuation, + # resolved by longest match. + # + # - Error patterns call the error callback and advance minimally, which + # keeps lexing resilient while reporting useful diagnostics. + text = self._lexdata + n = len(text) + + if self._pending_tok is not None: + tok = self._pending_tok + self._pending_tok = None + return tok + + while self._pos < n: + match text[self._pos]: + case " " | "\t": + self._pos += 1 + case "\n": + self._lineno += 1 + self._pos += 1 + self._line_start = self._pos + case "#": + if _line_pattern.match(text, self._pos + 1): + self._pos += 1 + self._handle_ppline() + continue + if _pragma_pattern.match(text, self._pos + 1): + self._pos += 1 + toks = self._handle_pppragma() + if len(toks) > 1: + self._pending_tok = toks[1] + if len(toks) > 0: + return toks[0] + continue + tok = self._make_token("PPHASH", "#", self._pos) + self._pos += 1 + return tok + case _: + if tok := self._match_token(): + return tok + else: + continue + + def _match_token(self) -> Optional[_Token]: + """Match one token at the current position. + + Returns a Token on success, or None if no token could be matched and + an error was reported. This method always advances _pos by the matched + length, or by 1 on error/no-match. + """ + text = self._lexdata + pos = self._pos + # We pick the longest match between: + # - the master regex (identifiers, literals, error patterns, etc.) + # - fixed operator/punctuator literals from the bucket for text[pos] + # + # The longest match is required to ensure we properly lex something + # like ".123" (a floating-point constant) as a single entity (with + # FLOAT_CONST), rather than a PERIOD followed by a number. + # + # The fixed-literal buckets are already length-sorted, so within that + # bucket we can take the first match. However, we still compare its + # length to the regex match because the regex may have matched a longer + # token that should take precedence. + best = None + + if m := _regex_master.match(text, pos): + tok_type = m.lastgroup + # All master-regex alternatives are named; lastgroup shouldn't be None. + assert tok_type is not None + value = m.group(tok_type) + length = len(value) + action, msg = _regex_actions[tok_type] + best = (length, tok_type, value, action, msg) + + if bucket := _fixed_tokens_by_first.get(text[pos]): + for entry in bucket: + if text.startswith(entry.literal, pos): + length = len(entry.literal) + if best is None or length > best[0]: + best = ( + length, + entry.tok_type, + entry.literal, + _RegexAction.TOKEN, + None, + ) + break + + if best is None: + msg = f"Illegal character {repr(text[pos])}" + self._error(msg, pos) + self._pos += 1 + return None + + length, tok_type, value, action, msg = best + if action == _RegexAction.ERROR: + if tok_type == "BAD_CHAR_CONST": + msg = f"Invalid char constant {value}" + # All other ERROR rules provide a message. + assert msg is not None + self._error(msg, pos) + self._pos += max(1, length) + return None + + if action == _RegexAction.ID: + tok_type = _keyword_map.get(value, "ID") + if tok_type == "ID" and self.type_lookup_func(value): + tok_type = "TYPEID" + + tok = self._make_token(tok_type, value, pos) + self._pos += length + + if tok.type == "LBRACE": + self.on_lbrace_func() + elif tok.type == "RBRACE": + self.on_rbrace_func() + + return tok + + def _make_token(self, tok_type: str, value: str, pos: int) -> _Token: + """Create a Token at an absolute input position. + + Expects tok_type/value and the absolute byte offset pos in the current + input. Does not advance lexer state; callers manage _pos themselves. + Returns a Token with lineno/column computed from current line tracking. + """ + column = pos - self._line_start + 1 + tok = _Token(tok_type, value, self._lineno, column) + return tok + + def _error(self, msg: str, pos: int) -> None: + column = pos - self._line_start + 1 + self.error_func(msg, self._lineno, column) + + def _handle_ppline(self) -> None: + # Since #line directives aren't supposed to return tokens but should + # only affect the lexer's state (update line/filename for coords), this + # method does a bit of parsing on its own. It doesn't return anything, + # but its side effect is to update self._pos past the directive, and + # potentially update self._lineno and self._filename, based on the + # directive's contents. + # + # Accepted #line forms from preprocessors: + # - "#line 66 \"kwas\\df.h\"" + # - "# 9" + # - "#line 10 \"include/me.h\" 1 2 3" (extra numeric flags) + # - "# 1 \"file.h\" 3" + # Errors we must report: + # - "#line \"file.h\"" (filename before line number) + # - "#line df" (garbage instead of number/string) + # + # We scan the directive line once (after an optional 'line' keyword), + # validating the order: NUMBER, optional STRING, then any NUMBERs. + # The NUMBERs tail is only accepted if a filename STRING was present. + text = self._lexdata + n = len(text) + line_end = text.find("\n", self._pos) + if line_end == -1: + line_end = n + line = text[self._pos : line_end] + pos = 0 + line_len = len(line) + + def skip_ws() -> None: + nonlocal pos + while pos < line_len and line[pos] in " \t": + pos += 1 + + skip_ws() + if line.startswith("line", pos): + pos += 4 + + def success(pp_line: Optional[str], pp_filename: Optional[str]) -> None: + if pp_line is None: + self._error("line number missing in #line", self._pos + line_len) + else: + self._lineno = int(pp_line) + if pp_filename is not None: + self._filename = pp_filename + self._pos = line_end + 1 + self._line_start = self._pos + + def fail(msg: str, offset: int) -> None: + self._error(msg, self._pos + offset) + self._pos = line_end + 1 + self._line_start = self._pos + + skip_ws() + if pos >= line_len: + success(None, None) + return + if line[pos] == '"': + fail("filename before line number in #line", pos) + return + + m = re.match(_decimal_constant, line[pos:]) + if not m: + fail("invalid #line directive", pos) + return + + pp_line = m.group(0) + pos += len(pp_line) + skip_ws() + if pos >= line_len: + success(pp_line, None) + return + + if line[pos] != '"': + fail("invalid #line directive", pos) + return + + m = re.match(_string_literal, line[pos:]) + if not m: + fail("invalid #line directive", pos) + return + + pp_filename = m.group(0).lstrip('"').rstrip('"') + pos += len(m.group(0)) + + # Consume arbitrary sequence of numeric flags after the directive + while True: + skip_ws() + if pos >= line_len: + break + m = re.match(_decimal_constant, line[pos:]) + if not m: + fail("invalid #line directive", pos) + return + pos += len(m.group(0)) + + success(pp_line, pp_filename) + + def _handle_pppragma(self) -> List[_Token]: + # Parse a full #pragma line; returns a list of tokens with 1 or 2 + # tokens - PPPRAGMA and an optional PPPRAGMASTR. If an empty list is + # returned, it means an error occurred, or we're at the end of input. + # + # Examples: + # - "#pragma" -> PPPRAGMA only + # - "#pragma once" -> PPPRAGMA, PPPRAGMASTR("once") + # - "# pragma omp parallel private(th_id)" -> PPPRAGMA, PPPRAGMASTR("omp parallel private(th_id)") + # - "#\tpragma {pack: 2, smack: 3}" -> PPPRAGMA, PPPRAGMASTR("{pack: 2, smack: 3}") + text = self._lexdata + n = len(text) + pos = self._pos + + while pos < n and text[pos] in " \t": + pos += 1 + if pos >= n: + self._pos = pos + return [] + + if not text.startswith("pragma", pos): + self._error("invalid #pragma directive", pos) + self._pos = pos + 1 + return [] + + pragma_pos = pos + pos += len("pragma") + toks = [self._make_token("PPPRAGMA", "pragma", pragma_pos)] + + while pos < n and text[pos] in " \t": + pos += 1 + + start = pos + while pos < n and text[pos] != "\n": + pos += 1 + if pos > start: + toks.append(self._make_token("PPPRAGMASTR", text[start:pos], start)) + if pos < n and text[pos] == "\n": + self._lineno += 1 + pos += 1 + self._line_start = pos + self._pos = pos + return toks + + +## +## Reserved keywords +## +_keywords: Tuple[str, ...] = ( + "AUTO", + "BREAK", + "CASE", + "CHAR", + "CONST", + "CONTINUE", + "DEFAULT", + "DO", + "DOUBLE", + "ELSE", + "ENUM", + "EXTERN", + "FLOAT", + "FOR", + "GOTO", + "IF", + "INLINE", + "INT", + "LONG", + "REGISTER", + "OFFSETOF", + "RESTRICT", + "RETURN", + "SHORT", + "SIGNED", + "SIZEOF", + "STATIC", + "STRUCT", + "SWITCH", + "TYPEDEF", + "UNION", + "UNSIGNED", + "VOID", + "VOLATILE", + "WHILE", + "__INT128", + "_BOOL", + "_COMPLEX", + "_NORETURN", + "_THREAD_LOCAL", + "_STATIC_ASSERT", + "_ATOMIC", + "_ALIGNOF", + "_ALIGNAS", + "_PRAGMA", +) + +_keyword_map: Dict[str, str] = {} + +for keyword in _keywords: + # Keywords from new C standard are mixed-case, like _Bool, _Alignas, etc. + if keyword.startswith("_") and len(keyword) > 1 and keyword[1].isalpha(): + _keyword_map[keyword[:2].upper() + keyword[2:].lower()] = keyword + else: + _keyword_map[keyword.lower()] = keyword + +## +## Regexes for use in tokens +## + +# valid C identifiers (K&R2: A.2.3), plus '$' (supported by some compilers) +_identifier = r"[a-zA-Z_$][0-9a-zA-Z_$]*" + +_hex_prefix = "0[xX]" +_hex_digits = "[0-9a-fA-F]+" +_bin_prefix = "0[bB]" +_bin_digits = "[01]+" + +# integer constants (K&R2: A.2.5.1) +_integer_suffix_opt = ( + r"(([uU]ll)|([uU]LL)|(ll[uU]?)|(LL[uU]?)|([uU][lL])|([lL][uU]?)|[uU])?" +) +_decimal_constant = ( + "(0" + _integer_suffix_opt + ")|([1-9][0-9]*" + _integer_suffix_opt + ")" +) +_octal_constant = "0[0-7]*" + _integer_suffix_opt +_hex_constant = _hex_prefix + _hex_digits + _integer_suffix_opt +_bin_constant = _bin_prefix + _bin_digits + _integer_suffix_opt + +_bad_octal_constant = "0[0-7]*[89]" + +# comments are not supported +_unsupported_c_style_comment = r"\/\*" +_unsupported_cxx_style_comment = r"\/\/" + +# character constants (K&R2: A.2.5.2) +# Note: a-zA-Z and '.-~^_!=&;,' are allowed as escape chars to support #line +# directives with Windows paths as filenames (..\..\dir\file) +# For the same reason, decimal_escape allows all digit sequences. We want to +# parse all correct code, even if it means to sometimes parse incorrect +# code. +# +# The original regexes were taken verbatim from the C syntax definition, +# and were later modified to avoid worst-case exponential running time. +# +# simple_escape = r"""([a-zA-Z._~!=&\^\-\\?'"])""" +# decimal_escape = r"""(\d+)""" +# hex_escape = r"""(x[0-9a-fA-F]+)""" +# bad_escape = r"""([\\][^a-zA-Z._~^!=&\^\-\\?'"x0-7])""" +# +# The following modifications were made to avoid the ambiguity that allowed +# backtracking: (https://github.com/eliben/pycparser/issues/61) +# +# - \x was removed from simple_escape, unless it was not followed by a hex +# digit, to avoid ambiguity with hex_escape. +# - hex_escape allows one or more hex characters, but requires that the next +# character(if any) is not hex +# - decimal_escape allows one or more decimal characters, but requires that the +# next character(if any) is not a decimal +# - bad_escape does not allow any decimals (8-9), to avoid conflicting with the +# permissive decimal_escape. +# +# Without this change, python's `re` module would recursively try parsing each +# ambiguous escape sequence in multiple ways. e.g. `\123` could be parsed as +# `\1`+`23`, `\12`+`3`, and `\123`. + +_simple_escape = r"""([a-wyzA-Z._~!=&\^\-\\?'"]|x(?![0-9a-fA-F]))""" +_decimal_escape = r"""(\d+)(?!\d)""" +_hex_escape = r"""(x[0-9a-fA-F]+)(?![0-9a-fA-F])""" +_bad_escape = r"""([\\][^a-zA-Z._~^!=&\^\-\\?'"x0-9])""" + +_escape_sequence = ( + r"""(\\(""" + _simple_escape + "|" + _decimal_escape + "|" + _hex_escape + "))" +) + +# This complicated regex with lookahead might be slow for strings, so because +# all of the valid escapes (including \x) allowed +# 0 or more non-escaped characters after the first character, +# simple_escape+decimal_escape+hex_escape got simplified to + +_escape_sequence_start_in_string = r"""(\\[0-9a-zA-Z._~!=&\^\-\\?'"])""" + +_cconst_char = r"""([^'\\\n]|""" + _escape_sequence + ")" +_char_const = "'" + _cconst_char + "'" +_wchar_const = "L" + _char_const +_u8char_const = "u8" + _char_const +_u16char_const = "u" + _char_const +_u32char_const = "U" + _char_const +_multicharacter_constant = "'" + _cconst_char + "{2,4}'" +_unmatched_quote = "('" + _cconst_char + "*\\n)|('" + _cconst_char + "*$)" +_bad_char_const = ( + r"""('""" + _cconst_char + """[^'\n]+')|('')|('""" + _bad_escape + r"""[^'\n]*')""" +) + +# string literals (K&R2: A.2.6) +_string_char = r"""([^"\\\n]|""" + _escape_sequence_start_in_string + ")" +_string_literal = '"' + _string_char + '*"' +_wstring_literal = "L" + _string_literal +_u8string_literal = "u8" + _string_literal +_u16string_literal = "u" + _string_literal +_u32string_literal = "U" + _string_literal +_bad_string_literal = '"' + _string_char + "*" + _bad_escape + _string_char + '*"' + +# floating constants (K&R2: A.2.5.3) +_exponent_part = r"""([eE][-+]?[0-9]+)""" +_fractional_constant = r"""([0-9]*\.[0-9]+)|([0-9]+\.)""" +_floating_constant = ( + "((((" + + _fractional_constant + + ")" + + _exponent_part + + "?)|([0-9]+" + + _exponent_part + + "))[FfLl]?)" +) +_binary_exponent_part = r"""([pP][+-]?[0-9]+)""" +_hex_fractional_constant = ( + "(((" + _hex_digits + r""")?\.""" + _hex_digits + ")|(" + _hex_digits + r"""\.))""" +) +_hex_floating_constant = ( + "(" + + _hex_prefix + + "(" + + _hex_digits + + "|" + + _hex_fractional_constant + + ")" + + _binary_exponent_part + + "[FfLl]?)" +) + + +class _RegexAction(Enum): + TOKEN = 0 + ID = 1 + ERROR = 2 + + +@dataclass(frozen=True) +class _RegexRule: + # tok_type: name of the token emitted for a match + # regex_pattern: the raw regex (no anchors) to match at the current position + # action: TOKEN for normal tokens, ID for identifiers, ERROR to report + # error_message: message used for ERROR entries + tok_type: str + regex_pattern: str + action: _RegexAction + error_message: Optional[str] + + +_regex_rules: List[_RegexRule] = [ + _RegexRule( + "UNSUPPORTED_C_STYLE_COMMENT", + _unsupported_c_style_comment, + _RegexAction.ERROR, + "Comments are not supported, see https://github.com/eliben/pycparser#3using.", + ), + _RegexRule( + "UNSUPPORTED_CXX_STYLE_COMMENT", + _unsupported_cxx_style_comment, + _RegexAction.ERROR, + "Comments are not supported, see https://github.com/eliben/pycparser#3using.", + ), + _RegexRule( + "BAD_STRING_LITERAL", + _bad_string_literal, + _RegexAction.ERROR, + "String contains invalid escape code", + ), + _RegexRule("WSTRING_LITERAL", _wstring_literal, _RegexAction.TOKEN, None), + _RegexRule("U8STRING_LITERAL", _u8string_literal, _RegexAction.TOKEN, None), + _RegexRule("U16STRING_LITERAL", _u16string_literal, _RegexAction.TOKEN, None), + _RegexRule("U32STRING_LITERAL", _u32string_literal, _RegexAction.TOKEN, None), + _RegexRule("STRING_LITERAL", _string_literal, _RegexAction.TOKEN, None), + _RegexRule("HEX_FLOAT_CONST", _hex_floating_constant, _RegexAction.TOKEN, None), + _RegexRule("FLOAT_CONST", _floating_constant, _RegexAction.TOKEN, None), + _RegexRule("INT_CONST_HEX", _hex_constant, _RegexAction.TOKEN, None), + _RegexRule("INT_CONST_BIN", _bin_constant, _RegexAction.TOKEN, None), + _RegexRule( + "BAD_CONST_OCT", + _bad_octal_constant, + _RegexAction.ERROR, + "Invalid octal constant", + ), + _RegexRule("INT_CONST_OCT", _octal_constant, _RegexAction.TOKEN, None), + _RegexRule("INT_CONST_DEC", _decimal_constant, _RegexAction.TOKEN, None), + _RegexRule("INT_CONST_CHAR", _multicharacter_constant, _RegexAction.TOKEN, None), + _RegexRule("CHAR_CONST", _char_const, _RegexAction.TOKEN, None), + _RegexRule("WCHAR_CONST", _wchar_const, _RegexAction.TOKEN, None), + _RegexRule("U8CHAR_CONST", _u8char_const, _RegexAction.TOKEN, None), + _RegexRule("U16CHAR_CONST", _u16char_const, _RegexAction.TOKEN, None), + _RegexRule("U32CHAR_CONST", _u32char_const, _RegexAction.TOKEN, None), + _RegexRule("UNMATCHED_QUOTE", _unmatched_quote, _RegexAction.ERROR, "Unmatched '"), + _RegexRule("BAD_CHAR_CONST", _bad_char_const, _RegexAction.ERROR, None), + _RegexRule("ID", _identifier, _RegexAction.ID, None), +] + +_regex_actions: Dict[str, Tuple[_RegexAction, Optional[str]]] = {} +_regex_pattern_parts: List[str] = [] +for _rule in _regex_rules: + _regex_actions[_rule.tok_type] = (_rule.action, _rule.error_message) + _regex_pattern_parts.append(f"(?P<{_rule.tok_type}>{_rule.regex_pattern})") +# The master regex is a single alternation of all token patterns, each wrapped +# in a named group. We match once at the current position and then use +# `lastgroup` to recover which token kind fired; this avoids iterating over all +# regexes on every character while keeping the same token-level semantics. +_regex_master: re.Pattern[str] = re.compile("|".join(_regex_pattern_parts)) + + +@dataclass(frozen=True) +class _FixedToken: + tok_type: str + literal: str + + +_fixed_tokens: List[_FixedToken] = [ + _FixedToken("ELLIPSIS", "..."), + _FixedToken("LSHIFTEQUAL", "<<="), + _FixedToken("RSHIFTEQUAL", ">>="), + _FixedToken("PLUSPLUS", "++"), + _FixedToken("MINUSMINUS", "--"), + _FixedToken("ARROW", "->"), + _FixedToken("LAND", "&&"), + _FixedToken("LOR", "||"), + _FixedToken("LSHIFT", "<<"), + _FixedToken("RSHIFT", ">>"), + _FixedToken("LE", "<="), + _FixedToken("GE", ">="), + _FixedToken("EQ", "=="), + _FixedToken("NE", "!="), + _FixedToken("TIMESEQUAL", "*="), + _FixedToken("DIVEQUAL", "/="), + _FixedToken("MODEQUAL", "%="), + _FixedToken("PLUSEQUAL", "+="), + _FixedToken("MINUSEQUAL", "-="), + _FixedToken("ANDEQUAL", "&="), + _FixedToken("OREQUAL", "|="), + _FixedToken("XOREQUAL", "^="), + _FixedToken("EQUALS", "="), + _FixedToken("PLUS", "+"), + _FixedToken("MINUS", "-"), + _FixedToken("TIMES", "*"), + _FixedToken("DIVIDE", "/"), + _FixedToken("MOD", "%"), + _FixedToken("OR", "|"), + _FixedToken("AND", "&"), + _FixedToken("NOT", "~"), + _FixedToken("XOR", "^"), + _FixedToken("LNOT", "!"), + _FixedToken("LT", "<"), + _FixedToken("GT", ">"), + _FixedToken("CONDOP", "?"), + _FixedToken("LPAREN", "("), + _FixedToken("RPAREN", ")"), + _FixedToken("LBRACKET", "["), + _FixedToken("RBRACKET", "]"), + _FixedToken("LBRACE", "{"), + _FixedToken("RBRACE", "}"), + _FixedToken("COMMA", ","), + _FixedToken("PERIOD", "."), + _FixedToken("SEMI", ";"), + _FixedToken("COLON", ":"), +] + +# To avoid scanning all fixed tokens on every character, we bucket them by the +# first character. When matching at position i, we only look at the bucket for +# text[i], and we pre-sort that bucket by token length so the first match is +# also the longest. This preserves longest-match semantics (e.g. '>>=' before +# '>>' before '>') while reducing the number of comparisons. +_fixed_tokens_by_first: Dict[str, List[_FixedToken]] = {} +for _entry in _fixed_tokens: + _fixed_tokens_by_first.setdefault(_entry.literal[0], []).append(_entry) +for _bucket in _fixed_tokens_by_first.values(): + _bucket.sort(key=lambda item: len(item.literal), reverse=True) + +_line_pattern: re.Pattern[str] = re.compile(r"([ \t]*line\W)|([ \t]*\d+)") +_pragma_pattern: re.Pattern[str] = re.compile(r"[ \t]*pragma\W") diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pycparser/c_parser.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pycparser/c_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..f980672cf5eeccea5dc2e60b264d17dd1fbcd058 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pycparser/c_parser.py @@ -0,0 +1,2376 @@ +# ------------------------------------------------------------------------------ +# pycparser: c_parser.py +# +# Recursive-descent parser for the C language. +# +# Eli Bendersky [https://eli.thegreenplace.net/] +# License: BSD +# ------------------------------------------------------------------------------ +from dataclasses import dataclass +from typing import ( + Any, + Dict, + List, + Literal, + NoReturn, + Optional, + Tuple, + TypedDict, + cast, +) + +from . import c_ast +from .c_lexer import CLexer, _Token +from .ast_transforms import fix_switch_cases, fix_atomic_specifiers + + +@dataclass +class Coord: + """Coordinates of a syntactic element. Consists of: + - File name + - Line number + - Column number + """ + + file: str + line: int + column: Optional[int] = None + + def __str__(self) -> str: + text = f"{self.file}:{self.line}" + if self.column: + text += f":{self.column}" + return text + + +class ParseError(Exception): + pass + + +class CParser: + """Recursive-descent C parser. + + Usage: + parser = CParser() + ast = parser.parse(text, filename) + + The `lexer` parameter lets you inject a lexer class (defaults to CLexer). + The parameters after `lexer` are accepted for backward compatibility with + the old PLY-based parser and are otherwise unused. + """ + + def __init__( + self, + lex_optimize: bool = True, + lexer: type[CLexer] = CLexer, + lextab: str = "pycparser.lextab", + yacc_optimize: bool = True, + yacctab: str = "pycparser.yacctab", + yacc_debug: bool = False, + taboutputdir: str = "", + ) -> None: + self.clex: CLexer = lexer( + error_func=self._lex_error_func, + on_lbrace_func=self._lex_on_lbrace_func, + on_rbrace_func=self._lex_on_rbrace_func, + type_lookup_func=self._lex_type_lookup_func, + ) + + # Stack of scopes for keeping track of symbols. _scope_stack[-1] is + # the current (topmost) scope. Each scope is a dictionary that + # specifies whether a name is a type. If _scope_stack[n][name] is + # True, 'name' is currently a type in the scope. If it's False, + # 'name' is used in the scope but not as a type (for instance, if we + # saw: int name; + # If 'name' is not a key in _scope_stack[n] then 'name' was not defined + # in this scope at all. + self._scope_stack: List[Dict[str, bool]] = [dict()] + self._tokens: _TokenStream = _TokenStream(self.clex) + + def parse( + self, text: str, filename: str = "", debug: bool = False + ) -> c_ast.FileAST: + """Parses C code and returns an AST. + + text: + A string containing the C source code + + filename: + Name of the file being parsed (for meaningful + error messages) + + debug: + Deprecated debug flag (unused); for backwards compatibility. + """ + self._scope_stack = [dict()] + self.clex.input(text, filename) + self._tokens = _TokenStream(self.clex) + + ast = self._parse_translation_unit_or_empty() + tok = self._peek() + if tok is not None: + self._parse_error(f"before: {tok.value}", self._tok_coord(tok)) + return ast + + # ------------------------------------------------------------------ + # Scope and declaration helpers + # ------------------------------------------------------------------ + def _coord(self, lineno: int, column: Optional[int] = None) -> Coord: + return Coord(file=self.clex.filename, line=lineno, column=column) + + def _parse_error(self, msg: str, coord: Coord | str | None) -> NoReturn: + raise ParseError(f"{coord}: {msg}") + + def _push_scope(self) -> None: + self._scope_stack.append(dict()) + + def _pop_scope(self) -> None: + assert len(self._scope_stack) > 1 + self._scope_stack.pop() + + def _add_typedef_name(self, name: str, coord: Optional[Coord]) -> None: + """Add a new typedef name (ie a TYPEID) to the current scope""" + if not self._scope_stack[-1].get(name, True): + self._parse_error( + f"Typedef {name!r} previously declared as non-typedef in this scope", + coord, + ) + self._scope_stack[-1][name] = True + + def _add_identifier(self, name: str, coord: Optional[Coord]) -> None: + """Add a new object, function, or enum member name (ie an ID) to the + current scope + """ + if self._scope_stack[-1].get(name, False): + self._parse_error( + f"Non-typedef {name!r} previously declared as typedef in this scope", + coord, + ) + self._scope_stack[-1][name] = False + + def _is_type_in_scope(self, name: str) -> bool: + """Is *name* a typedef-name in the current scope?""" + for scope in reversed(self._scope_stack): + # If name is an identifier in this scope it shadows typedefs in + # higher scopes. + in_scope = scope.get(name) + if in_scope is not None: + return in_scope + return False + + def _lex_error_func(self, msg: str, line: int, column: int) -> None: + self._parse_error(msg, self._coord(line, column)) + + def _lex_on_lbrace_func(self) -> None: + self._push_scope() + + def _lex_on_rbrace_func(self) -> None: + self._pop_scope() + + def _lex_type_lookup_func(self, name: str) -> bool: + """Looks up types that were previously defined with + typedef. + Passed to the lexer for recognizing identifiers that + are types. + """ + return self._is_type_in_scope(name) + + # To understand what's going on here, read sections A.8.5 and + # A.8.6 of K&R2 very carefully. + # + # A C type consists of a basic type declaration, with a list + # of modifiers. For example: + # + # int *c[5]; + # + # The basic declaration here is 'int c', and the pointer and + # the array are the modifiers. + # + # Basic declarations are represented by TypeDecl (from module c_ast) and the + # modifiers are FuncDecl, PtrDecl and ArrayDecl. + # + # The standard states that whenever a new modifier is parsed, it should be + # added to the end of the list of modifiers. For example: + # + # K&R2 A.8.6.2: Array Declarators + # + # In a declaration T D where D has the form + # D1 [constant-expression-opt] + # and the type of the identifier in the declaration T D1 is + # "type-modifier T", the type of the + # identifier of D is "type-modifier array of T" + # + # This is what this method does. The declarator it receives + # can be a list of declarators ending with TypeDecl. It + # tacks the modifier to the end of this list, just before + # the TypeDecl. + # + # Additionally, the modifier may be a list itself. This is + # useful for pointers, that can come as a chain from the rule + # p_pointer. In this case, the whole modifier list is spliced + # into the new location. + def _type_modify_decl(self, decl: Any, modifier: Any) -> c_ast.Node: + """Tacks a type modifier on a declarator, and returns + the modified declarator. + + Note: the declarator and modifier may be modified + """ + modifier_head = modifier + modifier_tail = modifier + + # The modifier may be a nested list. Reach its tail. + while modifier_tail.type: + modifier_tail = modifier_tail.type + + # If the decl is a basic type, just tack the modifier onto it. + if isinstance(decl, c_ast.TypeDecl): + modifier_tail.type = decl + return modifier + else: + # Otherwise, the decl is a list of modifiers. Reach + # its tail and splice the modifier onto the tail, + # pointing to the underlying basic type. + decl_tail = decl + while not isinstance(decl_tail.type, c_ast.TypeDecl): + decl_tail = decl_tail.type + + modifier_tail.type = decl_tail.type + decl_tail.type = modifier_head + return decl + + # Due to the order in which declarators are constructed, + # they have to be fixed in order to look like a normal AST. + # + # When a declaration arrives from syntax construction, it has + # these problems: + # * The innermost TypeDecl has no type (because the basic + # type is only known at the uppermost declaration level) + # * The declaration has no variable name, since that is saved + # in the innermost TypeDecl + # * The typename of the declaration is a list of type + # specifiers, and not a node. Here, basic identifier types + # should be separated from more complex types like enums + # and structs. + # + # This method fixes these problems. + def _fix_decl_name_type( + self, + decl: c_ast.Decl | c_ast.Typedef | c_ast.Typename, + typename: List[Any], + ) -> c_ast.Decl | c_ast.Typedef | c_ast.Typename: + """Fixes a declaration. Modifies decl.""" + # Reach the underlying basic type + typ = decl + while not isinstance(typ, c_ast.TypeDecl): + typ = typ.type + + decl.name = typ.declname + typ.quals = decl.quals[:] + + # The typename is a list of types. If any type in this + # list isn't an IdentifierType, it must be the only + # type in the list (it's illegal to declare "int enum ..") + # If all the types are basic, they're collected in the + # IdentifierType holder. + for tn in typename: + if not isinstance(tn, c_ast.IdentifierType): + if len(typename) > 1: + self._parse_error("Invalid multiple types specified", tn.coord) + else: + typ.type = tn + return decl + + if not typename: + # Functions default to returning int + if not isinstance(decl.type, c_ast.FuncDecl): + self._parse_error("Missing type in declaration", decl.coord) + typ.type = c_ast.IdentifierType(["int"], coord=decl.coord) + else: + # At this point, we know that typename is a list of IdentifierType + # nodes. Concatenate all the names into a single list. + typ.type = c_ast.IdentifierType( + [name for id in typename for name in id.names], coord=typename[0].coord + ) + return decl + + def _add_declaration_specifier( + self, + declspec: Optional["_DeclSpec"], + newspec: Any, + kind: "_DeclSpecKind", + append: bool = False, + ) -> "_DeclSpec": + """See _DeclSpec for the specifier dictionary layout.""" + if declspec is None: + spec: _DeclSpec = dict( + qual=[], storage=[], type=[], function=[], alignment=[] + ) + else: + spec = declspec + + if append: + spec[kind].append(newspec) + else: + spec[kind].insert(0, newspec) + + return spec + + def _build_declarations( + self, + spec: "_DeclSpec", + decls: List["_DeclInfo"], + typedef_namespace: bool = False, + ) -> List[c_ast.Node]: + """Builds a list of declarations all sharing the given specifiers. + If typedef_namespace is true, each declared name is added + to the "typedef namespace", which also includes objects, + functions, and enum constants. + """ + is_typedef = "typedef" in spec["storage"] + declarations = [] + + # Bit-fields are allowed to be unnamed. + if decls[0].get("bitsize") is None: + # When redeclaring typedef names as identifiers in inner scopes, a + # problem can occur where the identifier gets grouped into + # spec['type'], leaving decl as None. This can only occur for the + # first declarator. + if decls[0]["decl"] is None: + if ( + len(spec["type"]) < 2 + or len(spec["type"][-1].names) != 1 + or not self._is_type_in_scope(spec["type"][-1].names[0]) + ): + coord = "?" + for t in spec["type"]: + if hasattr(t, "coord"): + coord = t.coord + break + self._parse_error("Invalid declaration", coord) + + # Make this look as if it came from "direct_declarator:ID" + decls[0]["decl"] = c_ast.TypeDecl( + declname=spec["type"][-1].names[0], + type=None, + quals=None, + align=spec["alignment"], + coord=spec["type"][-1].coord, + ) + # Remove the "new" type's name from the end of spec['type'] + del spec["type"][-1] + # A similar problem can occur where the declaration ends up + # looking like an abstract declarator. Give it a name if this is + # the case. + elif not isinstance( + decls[0]["decl"], + (c_ast.Enum, c_ast.Struct, c_ast.Union, c_ast.IdentifierType), + ): + decls_0_tail = cast(Any, decls[0]["decl"]) + while not isinstance(decls_0_tail, c_ast.TypeDecl): + decls_0_tail = decls_0_tail.type + if decls_0_tail.declname is None: + decls_0_tail.declname = spec["type"][-1].names[0] + del spec["type"][-1] + + for decl in decls: + assert decl["decl"] is not None + if is_typedef: + declaration = c_ast.Typedef( + name=None, + quals=spec["qual"], + storage=spec["storage"], + type=decl["decl"], + coord=decl["decl"].coord, + ) + else: + declaration = c_ast.Decl( + name=None, + quals=spec["qual"], + align=spec["alignment"], + storage=spec["storage"], + funcspec=spec["function"], + type=decl["decl"], + init=decl.get("init"), + bitsize=decl.get("bitsize"), + coord=decl["decl"].coord, + ) + + if isinstance( + declaration.type, + (c_ast.Enum, c_ast.Struct, c_ast.Union, c_ast.IdentifierType), + ): + fixed_decl = declaration + else: + fixed_decl = self._fix_decl_name_type(declaration, spec["type"]) + + # Add the type name defined by typedef to a + # symbol table (for usage in the lexer) + if typedef_namespace: + if is_typedef: + self._add_typedef_name(fixed_decl.name, fixed_decl.coord) + else: + self._add_identifier(fixed_decl.name, fixed_decl.coord) + + fixed_decl = fix_atomic_specifiers( + cast(c_ast.Decl | c_ast.Typedef, fixed_decl) + ) + declarations.append(fixed_decl) + + return declarations + + def _build_function_definition( + self, + spec: "_DeclSpec", + decl: c_ast.Node, + param_decls: Optional[List[c_ast.Node]], + body: c_ast.Node, + ) -> c_ast.Node: + """Builds a function definition.""" + if "typedef" in spec["storage"]: + self._parse_error("Invalid typedef", decl.coord) + + declaration = self._build_declarations( + spec=spec, + decls=[dict(decl=decl, init=None, bitsize=None)], + typedef_namespace=True, + )[0] + + return c_ast.FuncDef( + decl=declaration, param_decls=param_decls, body=body, coord=decl.coord + ) + + def _select_struct_union_class(self, token: str) -> type: + """Given a token (either STRUCT or UNION), selects the + appropriate AST class. + """ + if token == "struct": + return c_ast.Struct + else: + return c_ast.Union + + # ------------------------------------------------------------------ + # Token helpers + # ------------------------------------------------------------------ + def _peek(self, k: int = 1) -> Optional[_Token]: + """Return the k-th next token without consuming it (1-based).""" + return self._tokens.peek(k) + + def _peek_type(self, k: int = 1) -> Optional[str]: + """Return the type of the k-th next token, or None if absent (1-based).""" + tok = self._peek(k) + return tok.type if tok is not None else None + + def _advance(self) -> _Token: + tok = self._tokens.next() + if tok is None: + self._parse_error("At end of input", self.clex.filename) + else: + return tok + + def _accept(self, token_type: str) -> Optional[_Token]: + """Conditionally consume next token, only if it's of token_type. + + If it is of the expected type, consume and return it. + Otherwise, leaves the token intact and returns None. + """ + tok = self._peek() + if tok is not None and tok.type == token_type: + return self._advance() + return None + + def _expect(self, token_type: str) -> _Token: + tok = self._advance() + if tok.type != token_type: + self._parse_error(f"before: {tok.value}", self._tok_coord(tok)) + return tok + + def _mark(self) -> int: + return self._tokens.mark() + + def _reset(self, mark: int) -> None: + self._tokens.reset(mark) + + def _tok_coord(self, tok: _Token) -> Coord: + return self._coord(tok.lineno, tok.column) + + def _starts_declaration(self, tok: Optional[_Token] = None) -> bool: + tok = tok or self._peek() + if tok is None: + return False + return tok.type in _DECL_START + + def _starts_expression(self, tok: Optional[_Token] = None) -> bool: + tok = tok or self._peek() + if tok is None: + return False + return tok.type in _STARTS_EXPRESSION + + def _starts_statement(self) -> bool: + tok_type = self._peek_type() + if tok_type is None: + return False + if tok_type in _STARTS_STATEMENT: + return True + return self._starts_expression() + + def _starts_declarator(self, id_only: bool = False) -> bool: + tok_type = self._peek_type() + if tok_type is None: + return False + if tok_type in {"TIMES", "LPAREN"}: + return True + if id_only: + return tok_type == "ID" + return tok_type in {"ID", "TYPEID"} + + def _peek_declarator_name_info(self) -> Tuple[Optional[str], bool]: + mark = self._mark() + tok_type, saw_paren = self._scan_declarator_name_info() + self._reset(mark) + return tok_type, saw_paren + + def _parse_any_declarator( + self, allow_abstract: bool = False, typeid_paren_as_abstract: bool = False + ) -> Tuple[Optional[c_ast.Node], bool]: + # C declarators are ambiguous without lookahead. For example: + # int foo(int (aa)); -> aa is a name (ID) + # typedef char TT; + # int bar(int (TT)); -> TT is a type (TYPEID) in parens + name_type, saw_paren = self._peek_declarator_name_info() + if name_type is None or ( + typeid_paren_as_abstract and name_type == "TYPEID" and saw_paren + ): + if not allow_abstract: + tok = self._peek() + coord = self._tok_coord(tok) if tok is not None else self.clex.filename + self._parse_error("Invalid declarator", coord) + decl = self._parse_abstract_declarator_opt() + return decl, False + + if name_type == "TYPEID": + if typeid_paren_as_abstract: + decl = self._parse_typeid_noparen_declarator() + else: + decl = self._parse_typeid_declarator() + else: + decl = self._parse_id_declarator() + return decl, True + + def _scan_declarator_name_info(self) -> Tuple[Optional[str], bool]: + saw_paren = False + while self._accept("TIMES"): + while self._peek_type() in _TYPE_QUALIFIER: + self._advance() + + tok = self._peek() + if tok is None: + return None, saw_paren + if tok.type in {"ID", "TYPEID"}: + self._advance() + return tok.type, saw_paren + if tok.type == "LPAREN": + saw_paren = True + self._advance() + tok_type, nested_paren = self._scan_declarator_name_info() + if nested_paren: + saw_paren = True + depth = 1 + while True: + tok = self._peek() + if tok is None: + return None, saw_paren + if tok.type == "LPAREN": + depth += 1 + elif tok.type == "RPAREN": + depth -= 1 + self._advance() + if depth == 0: + break + continue + self._advance() + return tok_type, saw_paren + return None, saw_paren + + def _starts_direct_abstract_declarator(self) -> bool: + return self._peek_type() in {"LPAREN", "LBRACKET"} + + def _is_assignment_op(self) -> bool: + tok = self._peek() + return tok is not None and tok.type in _ASSIGNMENT_OPS + + def _try_parse_paren_type_name( + self, + ) -> Optional[Tuple[c_ast.Typename, int, _Token]]: + """Parse and return a parenthesized type name if present. + + Returns (typ, mark, lparen_tok) when the next tokens look like + '(' type_name ')', where typ is the parsed type name, mark is the + token-stream position before parsing, and lparen_tok is the LPAREN + token. Returns None if no parenthesized type name is present. + """ + mark = self._mark() + lparen_tok = self._accept("LPAREN") + if lparen_tok is None: + return None + if not self._starts_declaration(): + self._reset(mark) + return None + typ = self._parse_type_name() + if self._accept("RPAREN") is None: + self._reset(mark) + return None + return typ, mark, lparen_tok + + # ------------------------------------------------------------------ + # Top-level + # ------------------------------------------------------------------ + # BNF: translation_unit_or_empty : translation_unit | empty + def _parse_translation_unit_or_empty(self) -> c_ast.FileAST: + if self._peek() is None: + return c_ast.FileAST([]) + return c_ast.FileAST(self._parse_translation_unit()) + + # BNF: translation_unit : external_declaration+ + def _parse_translation_unit(self) -> List[c_ast.Node]: + ext = [] + while self._peek() is not None: + ext.extend(self._parse_external_declaration()) + return ext + + # BNF: external_declaration : function_definition + # | declaration + # | pp_directive + # | pppragma_directive + # | static_assert + # | ';' + def _parse_external_declaration(self) -> List[c_ast.Node]: + tok = self._peek() + if tok is None: + return [] + if tok.type == "PPHASH": + self._parse_pp_directive() + return [] + if tok.type in {"PPPRAGMA", "_PRAGMA"}: + return [self._parse_pppragma_directive()] + if self._accept("SEMI"): + return [] + if tok.type == "_STATIC_ASSERT": + return self._parse_static_assert() + + if not self._starts_declaration(tok): + # Special handling for old-style function definitions that have an + # implicit return type, e.g. + # + # foo() { + # return 5; + # } + # + # These get an implicit 'int' return type. + decl = self._parse_id_declarator() + param_decls = None + if self._peek_type() != "LBRACE": + self._parse_error("Invalid function definition", decl.coord) + spec: _DeclSpec = dict( + qual=[], + alignment=[], + storage=[], + type=[c_ast.IdentifierType(["int"], coord=decl.coord)], + function=[], + ) + func = self._build_function_definition( + spec=spec, + decl=decl, + param_decls=param_decls, + body=self._parse_compound_statement(), + ) + return [func] + + # From here on, parsing a standard declatation/definition. + spec, saw_type, spec_coord = self._parse_declaration_specifiers( + allow_no_type=True + ) + + name_type, _ = self._peek_declarator_name_info() + if name_type != "ID": + decls = self._parse_decl_body_with_spec(spec, saw_type) + self._expect("SEMI") + return decls + + decl = self._parse_id_declarator() + + if self._peek_type() == "LBRACE" or self._starts_declaration(): + param_decls = None + if self._starts_declaration(): + param_decls = self._parse_declaration_list() + if self._peek_type() != "LBRACE": + self._parse_error("Invalid function definition", decl.coord) + if not spec["type"]: + spec["type"] = [c_ast.IdentifierType(["int"], coord=spec_coord)] + func = self._build_function_definition( + spec=spec, + decl=decl, + param_decls=param_decls, + body=self._parse_compound_statement(), + ) + return [func] + + decl_dict: "_DeclInfo" = dict(decl=decl, init=None, bitsize=None) + if self._accept("EQUALS"): + decl_dict["init"] = self._parse_initializer() + decls = self._parse_init_declarator_list(first=decl_dict) + decls = self._build_declarations(spec=spec, decls=decls, typedef_namespace=True) + self._expect("SEMI") + return decls + + # ------------------------------------------------------------------ + # Declarations + # + # Declarations always come as lists (because they can be several in one + # line). When returning parsed declarations, a list is always returned - + # even if it contains a single element. + # ------------------------------------------------------------------ + def _parse_declaration(self) -> List[c_ast.Node]: + decls = self._parse_decl_body() + self._expect("SEMI") + return decls + + # BNF: decl_body : declaration_specifiers decl_body_with_spec + def _parse_decl_body(self) -> List[c_ast.Node]: + spec, saw_type, _ = self._parse_declaration_specifiers(allow_no_type=True) + return self._parse_decl_body_with_spec(spec, saw_type) + + # BNF: decl_body_with_spec : init_declarator_list + # | struct_or_union_or_enum_only + def _parse_decl_body_with_spec( + self, spec: "_DeclSpec", saw_type: bool + ) -> List[c_ast.Node]: + decls = None + if saw_type: + if self._starts_declarator(): + decls = self._parse_init_declarator_list() + else: + if self._starts_declarator(id_only=True): + decls = self._parse_init_declarator_list(id_only=True) + + if decls is None: + ty = spec["type"] + s_u_or_e = (c_ast.Struct, c_ast.Union, c_ast.Enum) + if len(ty) == 1 and isinstance(ty[0], s_u_or_e): + decls = [ + c_ast.Decl( + name=None, + quals=spec["qual"], + align=spec["alignment"], + storage=spec["storage"], + funcspec=spec["function"], + type=ty[0], + init=None, + bitsize=None, + coord=ty[0].coord, + ) + ] + else: + decls = self._build_declarations( + spec=spec, + decls=[dict(decl=None, init=None, bitsize=None)], + typedef_namespace=True, + ) + else: + decls = self._build_declarations( + spec=spec, decls=decls, typedef_namespace=True + ) + + return decls + + # BNF: declaration_list : declaration+ + def _parse_declaration_list(self) -> List[c_ast.Node]: + decls = [] + while self._starts_declaration(): + decls.extend(self._parse_declaration()) + return decls + + # BNF: declaration_specifiers : (storage_class_specifier + # | type_specifier + # | type_qualifier + # | function_specifier + # | alignment_specifier)+ + def _parse_declaration_specifiers( + self, allow_no_type: bool = False + ) -> Tuple["_DeclSpec", bool, Optional[Coord]]: + """Parse declaration-specifier sequence. + + allow_no_type: + If True, allow a missing type specifier without error. + + Returns: + (spec, saw_type, first_coord) where spec is a dict with + qual/storage/type/function/alignment entries, saw_type is True + if a type specifier was consumed, and first_coord is the coord + of the first specifier token (used for diagnostics). + """ + spec = None + saw_type = False + first_coord = None + + while True: + tok = self._peek() + if tok is None: + break + + if tok.type == "_ALIGNAS": + if first_coord is None: + first_coord = self._tok_coord(tok) + spec = self._add_declaration_specifier( + spec, self._parse_alignment_specifier(), "alignment", append=True + ) + continue + + if tok.type == "_ATOMIC" and self._peek_type(2) == "LPAREN": + if first_coord is None: + first_coord = self._tok_coord(tok) + spec = self._add_declaration_specifier( + spec, self._parse_atomic_specifier(), "type", append=True + ) + saw_type = True + continue + + if tok.type in _TYPE_QUALIFIER: + if first_coord is None: + first_coord = self._tok_coord(tok) + spec = self._add_declaration_specifier( + spec, self._advance().value, "qual", append=True + ) + continue + + if tok.type in _STORAGE_CLASS: + if first_coord is None: + first_coord = self._tok_coord(tok) + spec = self._add_declaration_specifier( + spec, self._advance().value, "storage", append=True + ) + continue + + if tok.type in _FUNCTION_SPEC: + if first_coord is None: + first_coord = self._tok_coord(tok) + spec = self._add_declaration_specifier( + spec, self._advance().value, "function", append=True + ) + continue + + if tok.type in _TYPE_SPEC_SIMPLE: + if first_coord is None: + first_coord = self._tok_coord(tok) + tok = self._advance() + spec = self._add_declaration_specifier( + spec, + c_ast.IdentifierType([tok.value], coord=self._tok_coord(tok)), + "type", + append=True, + ) + saw_type = True + continue + + if tok.type == "TYPEID": + if saw_type: + break + if first_coord is None: + first_coord = self._tok_coord(tok) + tok = self._advance() + spec = self._add_declaration_specifier( + spec, + c_ast.IdentifierType([tok.value], coord=self._tok_coord(tok)), + "type", + append=True, + ) + saw_type = True + continue + + if tok.type in {"STRUCT", "UNION"}: + if first_coord is None: + first_coord = self._tok_coord(tok) + spec = self._add_declaration_specifier( + spec, self._parse_struct_or_union_specifier(), "type", append=True + ) + saw_type = True + continue + + if tok.type == "ENUM": + if first_coord is None: + first_coord = self._tok_coord(tok) + spec = self._add_declaration_specifier( + spec, self._parse_enum_specifier(), "type", append=True + ) + saw_type = True + continue + + break + + if spec is None: + self._parse_error("Invalid declaration", self.clex.filename) + + if not saw_type and not allow_no_type: + self._parse_error("Missing type in declaration", first_coord) + + return spec, saw_type, first_coord + + # BNF: specifier_qualifier_list : (type_specifier + # | type_qualifier + # | alignment_specifier)+ + def _parse_specifier_qualifier_list(self) -> "_DeclSpec": + spec = None + saw_type = False + saw_alignment = False + first_coord = None + + while True: + tok = self._peek() + if tok is None: + break + + if tok.type == "_ALIGNAS": + if first_coord is None: + first_coord = self._tok_coord(tok) + spec = self._add_declaration_specifier( + spec, self._parse_alignment_specifier(), "alignment", append=True + ) + saw_alignment = True + continue + + if tok.type == "_ATOMIC" and self._peek_type(2) == "LPAREN": + if first_coord is None: + first_coord = self._tok_coord(tok) + spec = self._add_declaration_specifier( + spec, self._parse_atomic_specifier(), "type", append=True + ) + saw_type = True + continue + + if tok.type in _TYPE_QUALIFIER: + if first_coord is None: + first_coord = self._tok_coord(tok) + spec = self._add_declaration_specifier( + spec, self._advance().value, "qual", append=True + ) + continue + + if tok.type in _TYPE_SPEC_SIMPLE: + if first_coord is None: + first_coord = self._tok_coord(tok) + tok = self._advance() + spec = self._add_declaration_specifier( + spec, + c_ast.IdentifierType([tok.value], coord=self._tok_coord(tok)), + "type", + append=True, + ) + saw_type = True + continue + + if tok.type == "TYPEID": + if saw_type: + break + if first_coord is None: + first_coord = self._tok_coord(tok) + tok = self._advance() + spec = self._add_declaration_specifier( + spec, + c_ast.IdentifierType([tok.value], coord=self._tok_coord(tok)), + "type", + append=True, + ) + saw_type = True + continue + + if tok.type in {"STRUCT", "UNION"}: + if first_coord is None: + first_coord = self._tok_coord(tok) + spec = self._add_declaration_specifier( + spec, self._parse_struct_or_union_specifier(), "type", append=True + ) + saw_type = True + continue + + if tok.type == "ENUM": + if first_coord is None: + first_coord = self._tok_coord(tok) + spec = self._add_declaration_specifier( + spec, self._parse_enum_specifier(), "type", append=True + ) + saw_type = True + continue + + break + + if spec is None: + self._parse_error("Invalid specifier list", self.clex.filename) + + if not saw_type and not saw_alignment: + self._parse_error("Missing type in declaration", first_coord) + + if spec.get("storage") is None: + spec["storage"] = [] + if spec.get("function") is None: + spec["function"] = [] + + return spec + + # BNF: type_qualifier_list : type_qualifier+ + def _parse_type_qualifier_list(self) -> List[str]: + quals = [] + while self._peek_type() in _TYPE_QUALIFIER: + quals.append(self._advance().value) + return quals + + # BNF: alignment_specifier : _ALIGNAS '(' type_name | constant_expression ')' + def _parse_alignment_specifier(self) -> c_ast.Node: + tok = self._expect("_ALIGNAS") + self._expect("LPAREN") + + if self._starts_declaration(): + typ = self._parse_type_name() + self._expect("RPAREN") + return c_ast.Alignas(typ, self._tok_coord(tok)) + + expr = self._parse_constant_expression() + self._expect("RPAREN") + return c_ast.Alignas(expr, self._tok_coord(tok)) + + # BNF: atomic_specifier : _ATOMIC '(' type_name ')' + def _parse_atomic_specifier(self) -> c_ast.Node: + self._expect("_ATOMIC") + self._expect("LPAREN") + typ = self._parse_type_name() + self._expect("RPAREN") + typ.quals.append("_Atomic") + return typ + + # BNF: init_declarator_list : init_declarator (',' init_declarator)* + def _parse_init_declarator_list( + self, first: Optional["_DeclInfo"] = None, id_only: bool = False + ) -> List["_DeclInfo"]: + decls = ( + [first] + if first is not None + else [self._parse_init_declarator(id_only=id_only)] + ) + + while self._accept("COMMA"): + decls.append(self._parse_init_declarator(id_only=id_only)) + return decls + + # BNF: init_declarator : declarator ('=' initializer)? + def _parse_init_declarator(self, id_only: bool = False) -> "_DeclInfo": + decl = self._parse_id_declarator() if id_only else self._parse_declarator() + init = None + if self._accept("EQUALS"): + init = self._parse_initializer() + return dict(decl=decl, init=init, bitsize=None) + + # ------------------------------------------------------------------ + # Structs/unions/enums + # ------------------------------------------------------------------ + # BNF: struct_or_union_specifier : struct_or_union ID? '{' struct_declaration_list? '}' + # | struct_or_union ID + def _parse_struct_or_union_specifier(self) -> c_ast.Node: + tok = self._advance() + klass = self._select_struct_union_class(tok.value) + + if self._peek_type() in {"ID", "TYPEID"}: + name_tok = self._advance() + if self._peek_type() == "LBRACE": + self._advance() + if self._accept("RBRACE"): + return klass( + name=name_tok.value, decls=[], coord=self._tok_coord(name_tok) + ) + decls = self._parse_struct_declaration_list() + self._expect("RBRACE") + return klass( + name=name_tok.value, decls=decls, coord=self._tok_coord(name_tok) + ) + + return klass( + name=name_tok.value, decls=None, coord=self._tok_coord(name_tok) + ) + + if self._peek_type() == "LBRACE": + brace_tok = self._advance() + if self._accept("RBRACE"): + return klass(name=None, decls=[], coord=self._tok_coord(brace_tok)) + decls = self._parse_struct_declaration_list() + self._expect("RBRACE") + return klass(name=None, decls=decls, coord=self._tok_coord(brace_tok)) + + self._parse_error("Invalid struct/union declaration", self._tok_coord(tok)) + + # BNF: struct_declaration_list : struct_declaration+ + def _parse_struct_declaration_list(self) -> List[c_ast.Node]: + decls = [] + while self._peek_type() not in {None, "RBRACE"}: + items = self._parse_struct_declaration() + if items is None: + continue + decls.extend(items) + return decls + + # BNF: struct_declaration : specifier_qualifier_list struct_declarator_list? ';' + # | static_assert + # | pppragma_directive + def _parse_struct_declaration(self) -> Optional[List[c_ast.Node]]: + if self._peek_type() == "SEMI": + self._advance() + return None + if self._peek_type() in {"PPPRAGMA", "_PRAGMA"}: + return [self._parse_pppragma_directive()] + + spec = self._parse_specifier_qualifier_list() + assert "typedef" not in spec.get("storage", []) + + decls = None + if self._starts_declarator() or self._peek_type() == "COLON": + decls = self._parse_struct_declarator_list() + if decls is not None: + self._expect("SEMI") + return self._build_declarations(spec=spec, decls=decls) + + if len(spec["type"]) == 1: + node = spec["type"][0] + if isinstance(node, c_ast.Node): + decl_type = node + else: + decl_type = c_ast.IdentifierType(node) + self._expect("SEMI") + return self._build_declarations( + spec=spec, decls=[dict(decl=decl_type, init=None, bitsize=None)] + ) + + self._expect("SEMI") + return self._build_declarations( + spec=spec, decls=[dict(decl=None, init=None, bitsize=None)] + ) + + # BNF: struct_declarator_list : struct_declarator (',' struct_declarator)* + def _parse_struct_declarator_list(self) -> List["_DeclInfo"]: + decls = [self._parse_struct_declarator()] + while self._accept("COMMA"): + decls.append(self._parse_struct_declarator()) + return decls + + # BNF: struct_declarator : declarator? ':' constant_expression + # | declarator (':' constant_expression)? + def _parse_struct_declarator(self) -> "_DeclInfo": + if self._accept("COLON"): + bitsize = self._parse_constant_expression() + return { + "decl": c_ast.TypeDecl(None, None, None, None), + "init": None, + "bitsize": bitsize, + } + + decl = self._parse_declarator() + if self._accept("COLON"): + bitsize = self._parse_constant_expression() + return {"decl": decl, "init": None, "bitsize": bitsize} + + return {"decl": decl, "init": None, "bitsize": None} + + # BNF: enum_specifier : ENUM ID? '{' enumerator_list? '}' + # | ENUM ID + def _parse_enum_specifier(self) -> c_ast.Node: + tok = self._expect("ENUM") + if self._peek_type() in {"ID", "TYPEID"}: + name_tok = self._advance() + if self._peek_type() == "LBRACE": + self._advance() + enums = self._parse_enumerator_list() + self._expect("RBRACE") + return c_ast.Enum(name_tok.value, enums, self._tok_coord(tok)) + return c_ast.Enum(name_tok.value, None, self._tok_coord(tok)) + + self._expect("LBRACE") + enums = self._parse_enumerator_list() + self._expect("RBRACE") + return c_ast.Enum(None, enums, self._tok_coord(tok)) + + # BNF: enumerator_list : enumerator (',' enumerator)* ','? + def _parse_enumerator_list(self) -> c_ast.Node: + enum = self._parse_enumerator() + enum_list = c_ast.EnumeratorList([enum], enum.coord) + while self._accept("COMMA"): + if self._peek_type() == "RBRACE": + break + enum = self._parse_enumerator() + enum_list.enumerators.append(enum) + return enum_list + + # BNF: enumerator : ID ('=' constant_expression)? + def _parse_enumerator(self) -> c_ast.Node: + name_tok = self._expect("ID") + if self._accept("EQUALS"): + value = self._parse_constant_expression() + else: + value = None + enum = c_ast.Enumerator(name_tok.value, value, self._tok_coord(name_tok)) + self._add_identifier(enum.name, enum.coord) + return enum + + # ------------------------------------------------------------------ + # Declarators + # ------------------------------------------------------------------ + # BNF: declarator : pointer? direct_declarator + def _parse_declarator(self) -> c_ast.Node: + decl, _ = self._parse_any_declarator( + allow_abstract=False, typeid_paren_as_abstract=False + ) + assert decl is not None + return decl + + # BNF: id_declarator : declarator with ID name + def _parse_id_declarator(self) -> c_ast.Node: + return self._parse_declarator_kind(kind="id", allow_paren=True) + + # BNF: typeid_declarator : declarator with TYPEID name + def _parse_typeid_declarator(self) -> c_ast.Node: + return self._parse_declarator_kind(kind="typeid", allow_paren=True) + + # BNF: typeid_noparen_declarator : declarator without parenthesized name + def _parse_typeid_noparen_declarator(self) -> c_ast.Node: + return self._parse_declarator_kind(kind="typeid", allow_paren=False) + + # BNF: declarator_kind : pointer? direct_declarator(kind) + def _parse_declarator_kind(self, kind: str, allow_paren: bool) -> c_ast.Node: + ptr = None + if self._peek_type() == "TIMES": + ptr = self._parse_pointer() + direct = self._parse_direct_declarator(kind, allow_paren=allow_paren) + if ptr is not None: + return self._type_modify_decl(direct, ptr) + return direct + + # BNF: direct_declarator : ID | TYPEID | '(' declarator ')' + # | direct_declarator '[' ... ']' + # | direct_declarator '(' ... ')' + def _parse_direct_declarator( + self, kind: str, allow_paren: bool = True + ) -> c_ast.Node: + if allow_paren and self._accept("LPAREN"): + decl = self._parse_declarator_kind(kind, allow_paren=True) + self._expect("RPAREN") + else: + if kind == "id": + name_tok = self._expect("ID") + else: + name_tok = self._expect("TYPEID") + decl = c_ast.TypeDecl( + declname=name_tok.value, + type=None, + quals=None, + align=None, + coord=self._tok_coord(name_tok), + ) + + return self._parse_decl_suffixes(decl) + + def _parse_decl_suffixes(self, decl: c_ast.Node) -> c_ast.Node: + """Parse a chain of array/function suffixes and attach them to decl.""" + while True: + if self._peek_type() == "LBRACKET": + decl = self._type_modify_decl(decl, self._parse_array_decl(decl)) + continue + if self._peek_type() == "LPAREN": + func = self._parse_function_decl(decl) + decl = self._type_modify_decl(decl, func) + continue + break + return decl + + # BNF: array_decl : '[' array_specifiers? assignment_expression? ']' + def _parse_array_decl(self, base_decl: c_ast.Node) -> c_ast.Node: + return self._parse_array_decl_common(base_type=None, coord=base_decl.coord) + + def _parse_array_decl_common( + self, base_type: Optional[c_ast.Node], coord: Optional[Coord] = None + ) -> c_ast.Node: + """Parse an array declarator suffix and return an ArrayDecl node. + + base_type: + Base declarator node to attach (None for direct-declarator parsing, + TypeDecl for abstract declarators). + + coord: + Coordinate to use for the ArrayDecl. If None, uses the '[' token. + """ + lbrack_tok = self._expect("LBRACKET") + if coord is None: + coord = self._tok_coord(lbrack_tok) + + def make_array_decl(dim, dim_quals): + return c_ast.ArrayDecl( + type=base_type, dim=dim, dim_quals=dim_quals, coord=coord + ) + + if self._accept("STATIC"): + dim_quals = ["static"] + (self._parse_type_qualifier_list() or []) + dim = self._parse_assignment_expression() + self._expect("RBRACKET") + return make_array_decl(dim, dim_quals) + + if self._peek_type() in _TYPE_QUALIFIER: + dim_quals = self._parse_type_qualifier_list() or [] + if self._accept("STATIC"): + dim_quals = dim_quals + ["static"] + dim = self._parse_assignment_expression() + self._expect("RBRACKET") + return make_array_decl(dim, dim_quals) + times_tok = self._accept("TIMES") + if times_tok: + self._expect("RBRACKET") + dim = c_ast.ID(times_tok.value, self._tok_coord(times_tok)) + return make_array_decl(dim, dim_quals) + dim = None + if self._starts_expression(): + dim = self._parse_assignment_expression() + self._expect("RBRACKET") + return make_array_decl(dim, dim_quals) + + times_tok = self._accept("TIMES") + if times_tok: + self._expect("RBRACKET") + dim = c_ast.ID(times_tok.value, self._tok_coord(times_tok)) + return make_array_decl(dim, []) + + dim = None + if self._starts_expression(): + dim = self._parse_assignment_expression() + self._expect("RBRACKET") + return make_array_decl(dim, []) + + # BNF: function_decl : '(' parameter_type_list_opt | identifier_list_opt ')' + def _parse_function_decl(self, base_decl: c_ast.Node) -> c_ast.Node: + self._expect("LPAREN") + if self._accept("RPAREN"): + args = None + else: + args = ( + self._parse_parameter_type_list() + if self._starts_declaration() + else self._parse_identifier_list_opt() + ) + self._expect("RPAREN") + + func = c_ast.FuncDecl(args=args, type=None, coord=base_decl.coord) + + if self._peek_type() == "LBRACE": + if func.args is not None: + for param in func.args.params: + if isinstance(param, c_ast.EllipsisParam): + break + name = getattr(param, "name", None) + if name: + self._add_identifier(name, param.coord) + + return func + + # BNF: pointer : '*' type_qualifier_list? pointer? + def _parse_pointer(self) -> Optional[c_ast.Node]: + stars = [] + times_tok = self._accept("TIMES") + while times_tok: + quals = self._parse_type_qualifier_list() or [] + stars.append((quals, self._tok_coord(times_tok))) + times_tok = self._accept("TIMES") + + if not stars: + return None + + ptr = None + for quals, coord in stars: + ptr = c_ast.PtrDecl(quals=quals, type=ptr, coord=coord) + return ptr + + # BNF: parameter_type_list : parameter_list (',' ELLIPSIS)? + def _parse_parameter_type_list(self) -> c_ast.ParamList: + params = self._parse_parameter_list() + if self._peek_type() == "COMMA" and self._peek_type(2) == "ELLIPSIS": + self._advance() + ell_tok = self._advance() + params.params.append(c_ast.EllipsisParam(self._tok_coord(ell_tok))) + return params + + # BNF: parameter_list : parameter_declaration (',' parameter_declaration)* + def _parse_parameter_list(self) -> c_ast.ParamList: + first = self._parse_parameter_declaration() + params = c_ast.ParamList([first], first.coord) + while self._peek_type() == "COMMA" and self._peek_type(2) != "ELLIPSIS": + self._advance() + params.params.append(self._parse_parameter_declaration()) + return params + + # BNF: parameter_declaration : declaration_specifiers declarator? + # | declaration_specifiers abstract_declarator_opt + def _parse_parameter_declaration(self) -> c_ast.Node: + spec, _, spec_coord = self._parse_declaration_specifiers(allow_no_type=True) + + if not spec["type"]: + spec["type"] = [c_ast.IdentifierType(["int"], coord=spec_coord)] + + if self._starts_declarator(): + decl, is_named = self._parse_any_declarator( + allow_abstract=True, typeid_paren_as_abstract=True + ) + if is_named: + return self._build_declarations( + spec=spec, decls=[dict(decl=decl, init=None, bitsize=None)] + )[0] + return self._build_parameter_declaration(spec, decl, spec_coord) + + decl = self._parse_abstract_declarator_opt() + return self._build_parameter_declaration(spec, decl, spec_coord) + + def _build_parameter_declaration( + self, spec: "_DeclSpec", decl: Optional[c_ast.Node], spec_coord: Optional[Coord] + ) -> c_ast.Node: + if ( + len(spec["type"]) > 1 + and len(spec["type"][-1].names) == 1 + and self._is_type_in_scope(spec["type"][-1].names[0]) + ): + return self._build_declarations( + spec=spec, decls=[dict(decl=decl, init=None, bitsize=None)] + )[0] + + decl = c_ast.Typename( + name="", + quals=spec["qual"], + align=None, + type=decl or c_ast.TypeDecl(None, None, None, None), + coord=spec_coord, + ) + return self._fix_decl_name_type(decl, spec["type"]) + + # BNF: identifier_list_opt : identifier_list | empty + def _parse_identifier_list_opt(self) -> Optional[c_ast.Node]: + if self._peek_type() == "RPAREN": + return None + return self._parse_identifier_list() + + # BNF: identifier_list : identifier (',' identifier)* + def _parse_identifier_list(self) -> c_ast.Node: + first = self._parse_identifier() + params = c_ast.ParamList([first], first.coord) + while self._accept("COMMA"): + params.params.append(self._parse_identifier()) + return params + + # ------------------------------------------------------------------ + # Abstract declarators + # ------------------------------------------------------------------ + # BNF: type_name : specifier_qualifier_list abstract_declarator_opt + def _parse_type_name(self) -> c_ast.Typename: + spec = self._parse_specifier_qualifier_list() + decl = self._parse_abstract_declarator_opt() + + coord = None + if decl is not None: + coord = decl.coord + elif spec["type"]: + coord = spec["type"][0].coord + + typename = c_ast.Typename( + name="", + quals=spec["qual"][:], + align=None, + type=decl or c_ast.TypeDecl(None, None, None, None), + coord=coord, + ) + return cast(c_ast.Typename, self._fix_decl_name_type(typename, spec["type"])) + + # BNF: abstract_declarator_opt : pointer? direct_abstract_declarator? + def _parse_abstract_declarator_opt(self) -> Optional[c_ast.Node]: + if self._peek_type() == "TIMES": + ptr = self._parse_pointer() + if self._starts_direct_abstract_declarator(): + decl = self._parse_direct_abstract_declarator() + else: + decl = c_ast.TypeDecl(None, None, None, None) + assert ptr is not None + return self._type_modify_decl(decl, ptr) + + if self._starts_direct_abstract_declarator(): + return self._parse_direct_abstract_declarator() + + return None + + # BNF: direct_abstract_declarator : '(' parameter_type_list_opt ')' + # | '(' abstract_declarator ')' + # | '[' ... ']' + def _parse_direct_abstract_declarator(self) -> c_ast.Node: + lparen_tok = self._accept("LPAREN") + if lparen_tok: + if self._starts_declaration() or self._peek_type() == "RPAREN": + params = self._parse_parameter_type_list_opt() + self._expect("RPAREN") + decl = c_ast.FuncDecl( + args=params, + type=c_ast.TypeDecl(None, None, None, None), + coord=self._tok_coord(lparen_tok), + ) + else: + decl = self._parse_abstract_declarator_opt() + self._expect("RPAREN") + assert decl is not None + elif self._peek_type() == "LBRACKET": + decl = self._parse_abstract_array_base() + else: + self._parse_error("Invalid abstract declarator", self.clex.filename) + + return self._parse_decl_suffixes(decl) + + # BNF: parameter_type_list_opt : parameter_type_list | empty + def _parse_parameter_type_list_opt(self) -> Optional[c_ast.ParamList]: + if self._peek_type() == "RPAREN": + return None + return self._parse_parameter_type_list() + + # BNF: abstract_array_base : '[' array_specifiers? assignment_expression? ']' + def _parse_abstract_array_base(self) -> c_ast.Node: + return self._parse_array_decl_common( + base_type=c_ast.TypeDecl(None, None, None, None), coord=None + ) + + # ------------------------------------------------------------------ + # Statements + # ------------------------------------------------------------------ + # BNF: statement : labeled_statement | compound_statement + # | selection_statement | iteration_statement + # | jump_statement | expression_statement + # | static_assert | pppragma_directive + def _parse_statement(self) -> c_ast.Node | List[c_ast.Node]: + tok_type = self._peek_type() + match tok_type: + case "CASE" | "DEFAULT": + return self._parse_labeled_statement() + case "ID" if self._peek_type(2) == "COLON": + return self._parse_labeled_statement() + case "LBRACE": + return self._parse_compound_statement() + case "IF" | "SWITCH": + return self._parse_selection_statement() + case "WHILE" | "DO" | "FOR": + return self._parse_iteration_statement() + case "GOTO" | "BREAK" | "CONTINUE" | "RETURN": + return self._parse_jump_statement() + case "PPPRAGMA" | "_PRAGMA": + return self._parse_pppragma_directive() + case "_STATIC_ASSERT": + return self._parse_static_assert() + case _: + return self._parse_expression_statement() + + # BNF: pragmacomp_or_statement : pppragma_directive* statement + def _parse_pragmacomp_or_statement(self) -> c_ast.Node | List[c_ast.Node]: + if self._peek_type() in {"PPPRAGMA", "_PRAGMA"}: + pragmas = self._parse_pppragma_directive_list() + stmt = self._parse_statement() + return c_ast.Compound(block_items=pragmas + [stmt], coord=pragmas[0].coord) + return self._parse_statement() + + # BNF: block_item : declaration | statement + def _parse_block_item(self) -> c_ast.Node | List[c_ast.Node]: + if self._starts_declaration(): + return self._parse_declaration() + return self._parse_statement() + + # BNF: block_item_list : block_item+ + def _parse_block_item_list(self) -> List[c_ast.Node]: + items = [] + while self._peek_type() not in {"RBRACE", None}: + item = self._parse_block_item() + if isinstance(item, list): + if item == [None]: + continue + items.extend(item) + else: + items.append(item) + return items + + # BNF: compound_statement : '{' block_item_list? '}' + def _parse_compound_statement(self) -> c_ast.Node: + lbrace_tok = self._expect("LBRACE") + if self._accept("RBRACE"): + return c_ast.Compound(block_items=None, coord=self._tok_coord(lbrace_tok)) + block_items = self._parse_block_item_list() + self._expect("RBRACE") + return c_ast.Compound( + block_items=block_items, coord=self._tok_coord(lbrace_tok) + ) + + # BNF: labeled_statement : ID ':' statement + # | CASE constant_expression ':' statement + # | DEFAULT ':' statement + def _parse_labeled_statement(self) -> c_ast.Node: + tok_type = self._peek_type() + match tok_type: + case "ID": + name_tok = self._advance() + self._expect("COLON") + if self._starts_statement(): + stmt = self._parse_pragmacomp_or_statement() + else: + stmt = c_ast.EmptyStatement(self._tok_coord(name_tok)) + return c_ast.Label(name_tok.value, stmt, self._tok_coord(name_tok)) + case "CASE": + case_tok = self._advance() + expr = self._parse_constant_expression() + self._expect("COLON") + if self._starts_statement(): + stmt = self._parse_pragmacomp_or_statement() + else: + stmt = c_ast.EmptyStatement(self._tok_coord(case_tok)) + return c_ast.Case(expr, [stmt], self._tok_coord(case_tok)) + case "DEFAULT": + def_tok = self._advance() + self._expect("COLON") + if self._starts_statement(): + stmt = self._parse_pragmacomp_or_statement() + else: + stmt = c_ast.EmptyStatement(self._tok_coord(def_tok)) + return c_ast.Default([stmt], self._tok_coord(def_tok)) + case _: + self._parse_error("Invalid labeled statement", self.clex.filename) + + # BNF: selection_statement : IF '(' expression ')' statement (ELSE statement)? + # | SWITCH '(' expression ')' statement + def _parse_selection_statement(self) -> c_ast.Node: + tok = self._advance() + match tok.type: + case "IF": + self._expect("LPAREN") + cond = self._parse_expression() + self._expect("RPAREN") + then_stmt = self._parse_pragmacomp_or_statement() + if self._accept("ELSE"): + else_stmt = self._parse_pragmacomp_or_statement() + return c_ast.If(cond, then_stmt, else_stmt, self._tok_coord(tok)) + return c_ast.If(cond, then_stmt, None, self._tok_coord(tok)) + case "SWITCH": + self._expect("LPAREN") + expr = self._parse_expression() + self._expect("RPAREN") + stmt = self._parse_pragmacomp_or_statement() + return fix_switch_cases(c_ast.Switch(expr, stmt, self._tok_coord(tok))) + case _: + self._parse_error("Invalid selection statement", self._tok_coord(tok)) + + # BNF: iteration_statement : WHILE '(' expression ')' statement + # | DO statement WHILE '(' expression ')' ';' + # | FOR '(' (declaration | expression_opt) ';' + # expression_opt ';' expression_opt ')' statement + def _parse_iteration_statement(self) -> c_ast.Node: + tok = self._advance() + match tok.type: + case "WHILE": + self._expect("LPAREN") + cond = self._parse_expression() + self._expect("RPAREN") + stmt = self._parse_pragmacomp_or_statement() + return c_ast.While(cond, stmt, self._tok_coord(tok)) + case "DO": + stmt = self._parse_pragmacomp_or_statement() + self._expect("WHILE") + self._expect("LPAREN") + cond = self._parse_expression() + self._expect("RPAREN") + self._expect("SEMI") + return c_ast.DoWhile(cond, stmt, self._tok_coord(tok)) + case "FOR": + self._expect("LPAREN") + if self._starts_declaration(): + decls = self._parse_declaration() + init = c_ast.DeclList(decls, self._tok_coord(tok)) + cond = self._parse_expression_opt() + self._expect("SEMI") + next_expr = self._parse_expression_opt() + self._expect("RPAREN") + stmt = self._parse_pragmacomp_or_statement() + return c_ast.For(init, cond, next_expr, stmt, self._tok_coord(tok)) + + init = self._parse_expression_opt() + self._expect("SEMI") + cond = self._parse_expression_opt() + self._expect("SEMI") + next_expr = self._parse_expression_opt() + self._expect("RPAREN") + stmt = self._parse_pragmacomp_or_statement() + return c_ast.For(init, cond, next_expr, stmt, self._tok_coord(tok)) + case _: + self._parse_error("Invalid iteration statement", self._tok_coord(tok)) + + # BNF: jump_statement : GOTO ID ';' | BREAK ';' | CONTINUE ';' + # | RETURN expression? ';' + def _parse_jump_statement(self) -> c_ast.Node: + tok = self._advance() + match tok.type: + case "GOTO": + name_tok = self._expect("ID") + self._expect("SEMI") + return c_ast.Goto(name_tok.value, self._tok_coord(tok)) + case "BREAK": + self._expect("SEMI") + return c_ast.Break(self._tok_coord(tok)) + case "CONTINUE": + self._expect("SEMI") + return c_ast.Continue(self._tok_coord(tok)) + case "RETURN": + if self._accept("SEMI"): + return c_ast.Return(None, self._tok_coord(tok)) + expr = self._parse_expression() + self._expect("SEMI") + return c_ast.Return(expr, self._tok_coord(tok)) + case _: + self._parse_error("Invalid jump statement", self._tok_coord(tok)) + + # BNF: expression_statement : expression_opt ';' + def _parse_expression_statement(self) -> c_ast.Node: + expr = self._parse_expression_opt() + semi_tok = self._expect("SEMI") + if expr is None: + return c_ast.EmptyStatement(self._tok_coord(semi_tok)) + return expr + + # ------------------------------------------------------------------ + # Expressions + # ------------------------------------------------------------------ + # BNF: expression_opt : expression | empty + def _parse_expression_opt(self) -> Optional[c_ast.Node]: + if self._starts_expression(): + return self._parse_expression() + return None + + # BNF: expression : assignment_expression (',' assignment_expression)* + def _parse_expression(self) -> c_ast.Node: + expr = self._parse_assignment_expression() + if not self._accept("COMMA"): + return expr + exprs = [expr, self._parse_assignment_expression()] + while self._accept("COMMA"): + exprs.append(self._parse_assignment_expression()) + return c_ast.ExprList(exprs, expr.coord) + + # BNF: assignment_expression : conditional_expression + # | unary_expression assignment_op assignment_expression + def _parse_assignment_expression(self) -> c_ast.Node: + if self._peek_type() == "LPAREN" and self._peek_type(2) == "LBRACE": + self._advance() + comp = self._parse_compound_statement() + self._expect("RPAREN") + return comp + + expr = self._parse_conditional_expression() + if self._is_assignment_op(): + op = self._advance().value + rhs = self._parse_assignment_expression() + return c_ast.Assignment(op, expr, rhs, expr.coord) + return expr + + # BNF: conditional_expression : binary_expression + # | binary_expression '?' expression ':' conditional_expression + def _parse_conditional_expression(self) -> c_ast.Node: + expr = self._parse_binary_expression() + if self._accept("CONDOP"): + iftrue = self._parse_expression() + self._expect("COLON") + iffalse = self._parse_conditional_expression() + return c_ast.TernaryOp(expr, iftrue, iffalse, expr.coord) + return expr + + # BNF: binary_expression : cast_expression (binary_op cast_expression)* + def _parse_binary_expression( + self, min_prec: int = 0, lhs: Optional[c_ast.Node] = None + ) -> c_ast.Node: + if lhs is None: + lhs = self._parse_cast_expression() + + while True: + tok = self._peek() + if tok is None or tok.type not in _BINARY_PRECEDENCE: + break + prec = _BINARY_PRECEDENCE[tok.type] + if prec < min_prec: + break + + op = tok.value + self._advance() + rhs = self._parse_cast_expression() + + while True: + next_tok = self._peek() + if next_tok is None or next_tok.type not in _BINARY_PRECEDENCE: + break + next_prec = _BINARY_PRECEDENCE[next_tok.type] + if next_prec > prec: + rhs = self._parse_binary_expression(next_prec, rhs) + else: + break + + lhs = c_ast.BinaryOp(op, lhs, rhs, lhs.coord) + + return lhs + + # BNF: cast_expression : '(' type_name ')' cast_expression + # | unary_expression + def _parse_cast_expression(self) -> c_ast.Node: + result = self._try_parse_paren_type_name() + if result is not None: + typ, mark, lparen_tok = result + if self._peek_type() == "LBRACE": + # (type){...} is a compound literal, not a cast. Examples: + # (int){1} -> compound literal, handled in postfix + # (int) x -> cast, handled below + self._reset(mark) + else: + expr = self._parse_cast_expression() + return c_ast.Cast(typ, expr, self._tok_coord(lparen_tok)) + return self._parse_unary_expression() + + # BNF: unary_expression : postfix_expression + # | '++' unary_expression + # | '--' unary_expression + # | unary_op cast_expression + # | 'sizeof' unary_expression + # | 'sizeof' '(' type_name ')' + # | '_Alignof' '(' type_name ')' + def _parse_unary_expression(self) -> c_ast.Node: + tok_type = self._peek_type() + if tok_type in {"PLUSPLUS", "MINUSMINUS"}: + tok = self._advance() + expr = self._parse_unary_expression() + return c_ast.UnaryOp(tok.value, expr, expr.coord) + + if tok_type in {"AND", "TIMES", "PLUS", "MINUS", "NOT", "LNOT"}: + tok = self._advance() + expr = self._parse_cast_expression() + return c_ast.UnaryOp(tok.value, expr, expr.coord) + + if tok_type == "SIZEOF": + tok = self._advance() + result = self._try_parse_paren_type_name() + if result is not None: + typ, _, _ = result + return c_ast.UnaryOp(tok.value, typ, self._tok_coord(tok)) + expr = self._parse_unary_expression() + return c_ast.UnaryOp(tok.value, expr, self._tok_coord(tok)) + + if tok_type == "_ALIGNOF": + tok = self._advance() + self._expect("LPAREN") + typ = self._parse_type_name() + self._expect("RPAREN") + return c_ast.UnaryOp(tok.value, typ, self._tok_coord(tok)) + + return self._parse_postfix_expression() + + # BNF: postfix_expression : primary_expression postfix_suffix* + # | '(' type_name ')' '{' initializer_list ','? '}' + def _parse_postfix_expression(self) -> c_ast.Node: + result = self._try_parse_paren_type_name() + if result is not None: + typ, mark, _ = result + # Disambiguate between casts and compound literals: + # (int) x -> cast + # (int) {1} -> compound literal + if self._accept("LBRACE"): + init = self._parse_initializer_list() + self._accept("COMMA") + self._expect("RBRACE") + return c_ast.CompoundLiteral(typ, init) + else: + self._reset(mark) + + expr = self._parse_primary_expression() + while True: + if self._accept("LBRACKET"): + sub = self._parse_expression() + self._expect("RBRACKET") + expr = c_ast.ArrayRef(expr, sub, expr.coord) + continue + if self._accept("LPAREN"): + if self._peek_type() == "RPAREN": + self._advance() + args = None + else: + args = self._parse_argument_expression_list() + self._expect("RPAREN") + expr = c_ast.FuncCall(expr, args, expr.coord) + continue + if self._peek_type() in {"PERIOD", "ARROW"}: + op_tok = self._advance() + name_tok = self._advance() + if name_tok.type not in {"ID", "TYPEID"}: + self._parse_error( + "Invalid struct reference", self._tok_coord(name_tok) + ) + field = c_ast.ID(name_tok.value, self._tok_coord(name_tok)) + expr = c_ast.StructRef(expr, op_tok.value, field, expr.coord) + continue + if self._peek_type() in {"PLUSPLUS", "MINUSMINUS"}: + tok = self._advance() + expr = c_ast.UnaryOp("p" + tok.value, expr, expr.coord) + continue + break + return expr + + # BNF: primary_expression : ID | constant | string_literal + # | '(' expression ')' | offsetof + def _parse_primary_expression(self) -> c_ast.Node: + tok_type = self._peek_type() + if tok_type == "ID": + return self._parse_identifier() + if ( + tok_type in _INT_CONST + or tok_type in _FLOAT_CONST + or tok_type in _CHAR_CONST + ): + return self._parse_constant() + if tok_type in _STRING_LITERAL: + return self._parse_unified_string_literal() + if tok_type in _WSTR_LITERAL: + return self._parse_unified_wstring_literal() + if tok_type == "LPAREN": + self._advance() + expr = self._parse_expression() + self._expect("RPAREN") + return expr + if tok_type == "OFFSETOF": + off_tok = self._advance() + self._expect("LPAREN") + typ = self._parse_type_name() + self._expect("COMMA") + designator = self._parse_offsetof_member_designator() + self._expect("RPAREN") + coord = self._tok_coord(off_tok) + return c_ast.FuncCall( + c_ast.ID(off_tok.value, coord), + c_ast.ExprList([typ, designator], coord), + coord, + ) + + self._parse_error("Invalid expression", self.clex.filename) + + # BNF: offsetof_member_designator : identifier_or_typeid + # ('.' identifier_or_typeid | '[' expression ']')* + def _parse_offsetof_member_designator(self) -> c_ast.Node: + node = self._parse_identifier_or_typeid() + while True: + if self._accept("PERIOD"): + field = self._parse_identifier_or_typeid() + node = c_ast.StructRef(node, ".", field, node.coord) + continue + if self._accept("LBRACKET"): + expr = self._parse_expression() + self._expect("RBRACKET") + node = c_ast.ArrayRef(node, expr, node.coord) + continue + break + return node + + # BNF: argument_expression_list : assignment_expression (',' assignment_expression)* + def _parse_argument_expression_list(self) -> c_ast.Node: + expr = self._parse_assignment_expression() + exprs = [expr] + while self._accept("COMMA"): + exprs.append(self._parse_assignment_expression()) + return c_ast.ExprList(exprs, expr.coord) + + # BNF: constant_expression : conditional_expression + def _parse_constant_expression(self) -> c_ast.Node: + return self._parse_conditional_expression() + + # ------------------------------------------------------------------ + # Terminals + # ------------------------------------------------------------------ + # BNF: identifier : ID + def _parse_identifier(self) -> c_ast.Node: + tok = self._expect("ID") + return c_ast.ID(tok.value, self._tok_coord(tok)) + + # BNF: identifier_or_typeid : ID | TYPEID + def _parse_identifier_or_typeid(self) -> c_ast.Node: + tok = self._advance() + if tok.type not in {"ID", "TYPEID"}: + self._parse_error("Expected identifier", self._tok_coord(tok)) + return c_ast.ID(tok.value, self._tok_coord(tok)) + + # BNF: constant : INT_CONST | FLOAT_CONST | CHAR_CONST + def _parse_constant(self) -> c_ast.Node: + tok = self._advance() + if tok.type in _INT_CONST: + u_count = 0 + l_count = 0 + for ch in tok.value[-3:]: + if ch in ("l", "L"): + l_count += 1 + elif ch in ("u", "U"): + u_count += 1 + if u_count > 1: + raise ValueError("Constant cannot have more than one u/U suffix.") + if l_count > 2: + raise ValueError("Constant cannot have more than two l/L suffix.") + prefix = "unsigned " * u_count + "long " * l_count + return c_ast.Constant(prefix + "int", tok.value, self._tok_coord(tok)) + + if tok.type in _FLOAT_CONST: + if tok.value[-1] in ("f", "F"): + t = "float" + elif tok.value[-1] in ("l", "L"): + t = "long double" + else: + t = "double" + return c_ast.Constant(t, tok.value, self._tok_coord(tok)) + + if tok.type in _CHAR_CONST: + return c_ast.Constant("char", tok.value, self._tok_coord(tok)) + + self._parse_error("Invalid constant", self._tok_coord(tok)) + + # BNF: unified_string_literal : STRING_LITERAL+ + def _parse_unified_string_literal(self) -> c_ast.Node: + tok = self._expect("STRING_LITERAL") + node = c_ast.Constant("string", tok.value, self._tok_coord(tok)) + while self._peek_type() == "STRING_LITERAL": + tok2 = self._advance() + node.value = node.value[:-1] + tok2.value[1:] + return node + + # BNF: unified_wstring_literal : WSTRING_LITERAL+ + def _parse_unified_wstring_literal(self) -> c_ast.Node: + tok = self._advance() + if tok.type not in _WSTR_LITERAL: + self._parse_error("Invalid string literal", self._tok_coord(tok)) + node = c_ast.Constant("string", tok.value, self._tok_coord(tok)) + while self._peek_type() in _WSTR_LITERAL: + tok2 = self._advance() + node.value = node.value.rstrip()[:-1] + tok2.value[2:] + return node + + # ------------------------------------------------------------------ + # Initializers + # ------------------------------------------------------------------ + # BNF: initializer : assignment_expression + # | '{' initializer_list ','? '}' + # | '{' '}' + def _parse_initializer(self) -> c_ast.Node: + lbrace_tok = self._accept("LBRACE") + if lbrace_tok: + if self._accept("RBRACE"): + return c_ast.InitList([], self._tok_coord(lbrace_tok)) + init_list = self._parse_initializer_list() + self._accept("COMMA") + self._expect("RBRACE") + return init_list + + return self._parse_assignment_expression() + + # BNF: initializer_list : initializer_item (',' initializer_item)* ','? + def _parse_initializer_list(self) -> c_ast.Node: + items = [self._parse_initializer_item()] + while self._accept("COMMA"): + if self._peek_type() == "RBRACE": + break + items.append(self._parse_initializer_item()) + return c_ast.InitList(items, items[0].coord) + + # BNF: initializer_item : designation? initializer + def _parse_initializer_item(self) -> c_ast.Node: + designation = None + if self._peek_type() in {"LBRACKET", "PERIOD"}: + designation = self._parse_designation() + init = self._parse_initializer() + if designation is not None: + return c_ast.NamedInitializer(designation, init) + return init + + # BNF: designation : designator_list '=' + def _parse_designation(self) -> List[c_ast.Node]: + designators = self._parse_designator_list() + self._expect("EQUALS") + return designators + + # BNF: designator_list : designator+ + def _parse_designator_list(self) -> List[c_ast.Node]: + designators = [] + while self._peek_type() in {"LBRACKET", "PERIOD"}: + designators.append(self._parse_designator()) + return designators + + # BNF: designator : '[' constant_expression ']' + # | '.' identifier_or_typeid + def _parse_designator(self) -> c_ast.Node: + if self._accept("LBRACKET"): + expr = self._parse_constant_expression() + self._expect("RBRACKET") + return expr + if self._accept("PERIOD"): + return self._parse_identifier_or_typeid() + self._parse_error("Invalid designator", self.clex.filename) + + # ------------------------------------------------------------------ + # Preprocessor-like directives + # ------------------------------------------------------------------ + # BNF: pp_directive : '#' ... (unsupported) + def _parse_pp_directive(self) -> NoReturn: + tok = self._expect("PPHASH") + self._parse_error("Directives not supported yet", self._tok_coord(tok)) + + # BNF: pppragma_directive : PPPRAGMA PPPRAGMASTR? + # | _PRAGMA '(' string_literal ')' + def _parse_pppragma_directive(self) -> c_ast.Node: + if self._peek_type() == "PPPRAGMA": + tok = self._advance() + if self._peek_type() == "PPPRAGMASTR": + str_tok = self._advance() + return c_ast.Pragma(str_tok.value, self._tok_coord(str_tok)) + return c_ast.Pragma("", self._tok_coord(tok)) + + if self._peek_type() == "_PRAGMA": + tok = self._advance() + lparen = self._expect("LPAREN") + literal = self._parse_unified_string_literal() + self._expect("RPAREN") + return c_ast.Pragma(literal, self._tok_coord(lparen)) + + self._parse_error("Invalid pragma", self.clex.filename) + + # BNF: pppragma_directive_list : pppragma_directive+ + def _parse_pppragma_directive_list(self) -> List[c_ast.Node]: + pragmas = [] + while self._peek_type() in {"PPPRAGMA", "_PRAGMA"}: + pragmas.append(self._parse_pppragma_directive()) + return pragmas + + # BNF: static_assert : _STATIC_ASSERT '(' constant_expression (',' string_literal)? ')' + def _parse_static_assert(self) -> List[c_ast.Node]: + tok = self._expect("_STATIC_ASSERT") + self._expect("LPAREN") + cond = self._parse_constant_expression() + msg = None + if self._accept("COMMA"): + msg = self._parse_unified_string_literal() + self._expect("RPAREN") + return [c_ast.StaticAssert(cond, msg, self._tok_coord(tok))] + + +_ASSIGNMENT_OPS = { + "EQUALS", + "XOREQUAL", + "TIMESEQUAL", + "DIVEQUAL", + "MODEQUAL", + "PLUSEQUAL", + "MINUSEQUAL", + "LSHIFTEQUAL", + "RSHIFTEQUAL", + "ANDEQUAL", + "OREQUAL", +} + +# Precedence of operators (lower number = weather binding) +# If this changes, c_generator.CGenerator.precedence_map needs to change as +# well +_BINARY_PRECEDENCE = { + "LOR": 0, + "LAND": 1, + "OR": 2, + "XOR": 3, + "AND": 4, + "EQ": 5, + "NE": 5, + "GT": 6, + "GE": 6, + "LT": 6, + "LE": 6, + "RSHIFT": 7, + "LSHIFT": 7, + "PLUS": 8, + "MINUS": 8, + "TIMES": 9, + "DIVIDE": 9, + "MOD": 9, +} + +_STORAGE_CLASS = {"AUTO", "REGISTER", "STATIC", "EXTERN", "TYPEDEF", "_THREAD_LOCAL"} + +_FUNCTION_SPEC = {"INLINE", "_NORETURN"} + +_TYPE_QUALIFIER = {"CONST", "RESTRICT", "VOLATILE", "_ATOMIC"} + +_TYPE_SPEC_SIMPLE = { + "VOID", + "_BOOL", + "CHAR", + "SHORT", + "INT", + "LONG", + "FLOAT", + "DOUBLE", + "_COMPLEX", + "SIGNED", + "UNSIGNED", + "__INT128", +} + +_DECL_START = ( + _STORAGE_CLASS + | _FUNCTION_SPEC + | _TYPE_QUALIFIER + | _TYPE_SPEC_SIMPLE + | {"TYPEID", "STRUCT", "UNION", "ENUM", "_ALIGNAS", "_ATOMIC"} +) + +_EXPR_START = { + "ID", + "LPAREN", + "PLUSPLUS", + "MINUSMINUS", + "PLUS", + "MINUS", + "TIMES", + "AND", + "NOT", + "LNOT", + "SIZEOF", + "_ALIGNOF", + "OFFSETOF", +} + +_INT_CONST = { + "INT_CONST_DEC", + "INT_CONST_OCT", + "INT_CONST_HEX", + "INT_CONST_BIN", + "INT_CONST_CHAR", +} + +_FLOAT_CONST = {"FLOAT_CONST", "HEX_FLOAT_CONST"} + +_CHAR_CONST = { + "CHAR_CONST", + "WCHAR_CONST", + "U8CHAR_CONST", + "U16CHAR_CONST", + "U32CHAR_CONST", +} + +_STRING_LITERAL = {"STRING_LITERAL"} + +_WSTR_LITERAL = { + "WSTRING_LITERAL", + "U8STRING_LITERAL", + "U16STRING_LITERAL", + "U32STRING_LITERAL", +} + +_STARTS_EXPRESSION = ( + _EXPR_START + | _INT_CONST + | _FLOAT_CONST + | _CHAR_CONST + | _STRING_LITERAL + | _WSTR_LITERAL +) + +_STARTS_STATEMENT = { + "LBRACE", + "IF", + "SWITCH", + "WHILE", + "DO", + "FOR", + "GOTO", + "BREAK", + "CONTINUE", + "RETURN", + "CASE", + "DEFAULT", + "PPPRAGMA", + "_PRAGMA", + "_STATIC_ASSERT", + "SEMI", +} + + +class _TokenStream: + """Wraps a lexer to provide convenient, buffered access to the underlying + token stream. The lexer is expected to be initialized with the input + string already. + """ + + def __init__(self, lexer: CLexer) -> None: + self._lexer = lexer + self._buffer: List[Optional[_Token]] = [] + self._index = 0 + + def peek(self, k: int = 1) -> Optional[_Token]: + """Peek at the k-th next token in the stream, without consuming it. + + Examples: + k=1 returns the immediate next token. + k=2 returns the token after that. + """ + if k <= 0: + return None + self._fill(k) + return self._buffer[self._index + k - 1] + + def next(self) -> Optional[_Token]: + """Consume a single token and return it.""" + self._fill(1) + tok = self._buffer[self._index] + self._index += 1 + return tok + + # The 'mark' and 'reset' methods are useful for speculative parsing with + # backtracking; when the parser needs to examine a sequence of tokens + # and potentially decide to try a different path on the same sequence, it + # can call 'mark' to obtain the current token position, and if the first + # path fails restore the position with `reset(pos)`. + def mark(self) -> int: + return self._index + + def reset(self, mark: int) -> None: + self._index = mark + + def _fill(self, n: int) -> None: + while len(self._buffer) < self._index + n: + tok = self._lexer.token() + self._buffer.append(tok) + if tok is None: + break + + +# Declaration specifiers are represented by a dictionary with entries: +# - qual: a list of type qualifiers +# - storage: a list of storage class specifiers +# - type: a list of type specifiers +# - function: a list of function specifiers +# - alignment: a list of alignment specifiers +class _DeclSpec(TypedDict): + qual: List[Any] + storage: List[Any] + type: List[Any] + function: List[Any] + alignment: List[Any] + + +_DeclSpecKind = Literal["qual", "storage", "type", "function", "alignment"] + + +class _DeclInfo(TypedDict): + # Declarator payloads used by declaration/initializer parsing: + # - decl: the declarator node (may be None for abstract/implicit cases) + # - init: optional initializer expression + # - bitsize: optional bit-field width expression (for struct declarators) + decl: Optional[c_ast.Node] + init: Optional[c_ast.Node] + bitsize: Optional[c_ast.Node] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pydantic_core-2.46.4.dist-info/INSTALLER b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pydantic_core-2.46.4.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pydantic_core-2.46.4.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pydantic_core-2.46.4.dist-info/METADATA b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pydantic_core-2.46.4.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..29068a781ba9da41573d1d09224c4016e21d4b93 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pydantic_core-2.46.4.dist-info/METADATA @@ -0,0 +1,173 @@ +Metadata-Version: 2.4 +Name: pydantic_core +Version: 2.46.4 +Classifier: Development Status :: 3 - Alpha +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +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.14 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Programming Language :: Python :: Implementation :: GraalPy +Classifier: Programming Language :: Rust +Classifier: Framework :: Pydantic +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Information Technology +Classifier: Operating System :: POSIX :: Linux +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: MacOS +Classifier: Typing :: Typed +Requires-Dist: typing-extensions>=4.14.1 +License-File: LICENSE +Summary: Core functionality for Pydantic validation and serialization +Home-Page: https://github.com/pydantic/pydantic +Author-email: Samuel Colvin , Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com>, David Montague , David Hewitt , Sydney Runkle , Victorien Plot +License-Expression: MIT +Requires-Python: >=3.9 +Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM +Project-URL: Funding, https://github.com/sponsors/samuelcolvin +Project-URL: Homepage, https://github.com/pydantic +Project-URL: Source, https://github.com/pydantic/pydantic/tree/main/pydantic-core + +# pydantic-core + +[![CI](https://github.com/pydantic/pydantic-core/workflows/ci/badge.svg?event=push)](https://github.com/pydantic/pydantic-core/actions?query=event%3Apush+branch%3Amain+workflow%3Aci) +[![Coverage](https://codecov.io/gh/pydantic/pydantic-core/branch/main/graph/badge.svg)](https://codecov.io/gh/pydantic/pydantic-core) +[![pypi](https://img.shields.io/pypi/v/pydantic-core.svg)](https://pypi.python.org/pypi/pydantic-core) +[![versions](https://img.shields.io/pypi/pyversions/pydantic-core.svg)](https://github.com/pydantic/pydantic-core) +[![license](https://img.shields.io/github/license/pydantic/pydantic-core.svg)](https://github.com/pydantic/pydantic-core/blob/main/LICENSE) + +This package provides the core functionality for [pydantic](https://docs.pydantic.dev) validation and serialization. + +Pydantic-core is currently around 17x faster than pydantic V1. +See [`tests/benchmarks/`](./tests/benchmarks/) for details. + +## Example of direct usage + +*NOTE: You should not need to use pydantic-core directly; instead, use pydantic, which in turn uses pydantic-core.* + +```py +from pydantic_core import SchemaValidator, ValidationError + + +v = SchemaValidator( + { + 'type': 'typed-dict', + 'fields': { + 'name': { + 'type': 'typed-dict-field', + 'schema': { + 'type': 'str', + }, + }, + 'age': { + 'type': 'typed-dict-field', + 'schema': { + 'type': 'int', + 'ge': 18, + }, + }, + 'is_developer': { + 'type': 'typed-dict-field', + 'schema': { + 'type': 'default', + 'schema': {'type': 'bool'}, + 'default': True, + }, + }, + }, + } +) + +r1 = v.validate_python({'name': 'Samuel', 'age': 35}) +assert r1 == {'name': 'Samuel', 'age': 35, 'is_developer': True} + +# pydantic-core can also validate JSON directly +r2 = v.validate_json('{"name": "Samuel", "age": 35}') +assert r1 == r2 + +try: + v.validate_python({'name': 'Samuel', 'age': 11}) +except ValidationError as e: + print(e) + """ + 1 validation error for model + age + Input should be greater than or equal to 18 + [type=greater_than_equal, context={ge: 18}, input_value=11, input_type=int] + """ +``` + +## Getting Started + +### Prerequisites + +You'll need: + +1. **[Rust](https://rustup.rs/)** - Rust stable (or nightly for coverage) +2. **[uv](https://docs.astral.sh/uv/getting-started/installation/)** - Fast Python package manager (will install Python 3.9+ automatically) +3. **[git](https://git-scm.com/)** - For version control +4. **[make](https://www.gnu.org/software/make/)** - For running development commands (or use `nmake` on Windows) + +### Quick Start + +```bash +# Clone the repository (or from your fork) +git clone git@github.com:pydantic/pydantic-core.git +cd pydantic-core + +# Install all dependencies using uv, setup pre-commit hooks, and build the development version +make install +``` + +Verify your installation by running: + +```bash +make +``` + +This runs a full development cycle: formatting, building, linting, and testing + +### Development Commands + +Run `make help` to see all available commands, or use these common ones: + +```bash +make build-dev # to build the package during development +make build-prod # to perform an optimised build for benchmarking +make test # to run the tests +make testcov # to run the tests and generate a coverage report +make lint # to run the linter +make format # to format python and rust code +make all # to run to run build-dev + format + lint + test +``` + +### Useful Resources + +* [`python/pydantic_core/_pydantic_core.pyi`](./python/pydantic_core/_pydantic_core.pyi) - Python API types +* [`python/pydantic_core/core_schema.py`](./python/pydantic_core/core_schema.py) - Core schema definitions +* [`tests/`](./tests) - Comprehensive usage examples + +## Profiling + +It's possible to profile the code using the [`flamegraph` utility from `flamegraph-rs`](https://github.com/flamegraph-rs/flamegraph). (Tested on Linux.) You can install this with `cargo install flamegraph`. + +Run `make build-profiling` to install a release build with debugging symbols included (needed for profiling). + +Once that is built, you can profile pytest benchmarks with (e.g.): + +```bash +flamegraph -- pytest tests/benchmarks/test_micro_benchmarks.py -k test_list_of_ints_core_py --benchmark-enable +``` + +The `flamegraph` command will produce an interactive SVG at `flamegraph.svg`. + +## Releasing + +TBC (needs to be integrated into `pydantic` repository release process). + diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pydantic_core-2.46.4.dist-info/RECORD b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pydantic_core-2.46.4.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..c3251d7f404414f33292e172ff70b786bbb734e9 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pydantic_core-2.46.4.dist-info/RECORD @@ -0,0 +1,13 @@ +pydantic_core-2.46.4.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +pydantic_core-2.46.4.dist-info/METADATA,sha256=E1-osviUc-kZHHB4whZOPsbIknphwjecL93MB_EfO64,6573 +pydantic_core-2.46.4.dist-info/RECORD,, +pydantic_core-2.46.4.dist-info/WHEEL,sha256=jsL9AqN9wHrgjdRkhDDyROu74_A4owfvDSioN563i9w,147 +pydantic_core-2.46.4.dist-info/licenses/LICENSE,sha256=Kv3TDVS01itvSIprzBVG6E7FBh8T9CCcA9ASNIeDeVo,1080 +pydantic_core-2.46.4.dist-info/sboms/pydantic-core.cyclonedx.json,sha256=zE9egKnIOkWwkp20k-A5gIOUDtVzbtwwJY6zMag6Woo,125376 +pydantic_core/__init__.py,sha256=nK1ikrdSVK9gapcKrpv_blrp8LCAic1jrK-jkbYHlNI,5115 +pydantic_core/__pycache__/__init__.cpython-310.pyc,, +pydantic_core/__pycache__/core_schema.cpython-310.pyc,, +pydantic_core/_pydantic_core.cpython-310-x86_64-linux-gnu.so,sha256=VdLL9qOiCSnk2bpaGYP84ONo-gBVlAr9WUAVg4GoW5I,4729280 +pydantic_core/_pydantic_core.pyi,sha256=H_lG8iKiv3Bpfd3rixY7xzs67gE-s0eiAqJaSbnF8Ss,45932 +pydantic_core/core_schema.py,sha256=1PM31yf_kGpm_H7GLnNFRkIPAQGPL9zh6rf2SxohVxg,155574 +pydantic_core/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pydantic_core-2.46.4.dist-info/WHEEL b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pydantic_core-2.46.4.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..89485cdbb8fc9bb4cc58c2844fefca934048a747 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pydantic_core-2.46.4.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: maturin (1.13.1) +Root-Is-Purelib: false +Tag: cp310-cp310-manylinux_2_17_x86_64 +Tag: cp310-cp310-manylinux2014_x86_64 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pymysql-1.1.3.dist-info/INSTALLER b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pymysql-1.1.3.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pymysql-1.1.3.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pymysql-1.1.3.dist-info/METADATA b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pymysql-1.1.3.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..eed9a107c89b6b9010412df7f728d9ceca90215f --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pymysql-1.1.3.dist-info/METADATA @@ -0,0 +1,131 @@ +Metadata-Version: 2.4 +Name: PyMySQL +Version: 1.1.3 +Summary: Pure Python MySQL Driver +Author-email: Inada Naoki , Yutaka Matsubara +License-Expression: MIT +Project-URL: Project, https://github.com/PyMySQL/PyMySQL +Project-URL: Documentation, https://pymysql.readthedocs.io/ +Project-URL: Changelog, https://github.com/PyMySQL/PyMySQL/blob/main/CHANGELOG.md +Keywords: MySQL +Classifier: Development Status :: 5 - Production/Stable +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Intended Audience :: Developers +Classifier: Topic :: Database +Requires-Python: >=3.9 +Description-Content-Type: text/markdown +License-File: LICENSE +Provides-Extra: rsa +Requires-Dist: cryptography>=46.0.7; extra == "rsa" +Provides-Extra: ed25519 +Requires-Dist: PyNaCl>=1.6.2; extra == "ed25519" +Dynamic: license-file + +[![Documentation Status](https://readthedocs.org/projects/pymysql/badge/?version=latest)](https://pymysql.readthedocs.io/) +[![codecov](https://codecov.io/gh/PyMySQL/PyMySQL/branch/main/graph/badge.svg?token=ppEuaNXBW4)](https://codecov.io/gh/PyMySQL/PyMySQL) +[![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/PyMySQL/PyMySQL) + +# PyMySQL + +This package contains a pure-Python MySQL and MariaDB client library, based on +[PEP 249](https://www.python.org/dev/peps/pep-0249/). + +## Requirements + +- Python -- one of the following: + - [CPython](https://www.python.org/) : 3.9 and newer + - [PyPy](https://pypy.org/) : Latest 3.x version +- MySQL Server -- one of the following: + - [MySQL](https://www.mysql.com/) LTS versions + - [MariaDB](https://mariadb.org/) LTS versions + +## Installation + +Package is uploaded on [PyPI](https://pypi.org/project/PyMySQL). + +You can install it with pip: + + $ python3 -m pip install PyMySQL + +To use "sha256_password" or "caching_sha2_password" for authenticate, +you need to install additional dependency: + + $ python3 -m pip install PyMySQL[rsa] + +To use MariaDB's "ed25519" authentication method, you need to install +additional dependency: + + $ python3 -m pip install PyMySQL[ed25519] + +## Documentation + +Documentation is available online: + +For support, please refer to the +[StackOverflow](https://stackoverflow.com/questions/tagged/pymysql). + +## Example + +The following examples make use of a simple table + +``` sql +CREATE TABLE `users` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `email` varchar(255) COLLATE utf8_bin NOT NULL, + `password` varchar(255) COLLATE utf8_bin NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin +AUTO_INCREMENT=1 ; +``` + +``` python +import pymysql.cursors + +# Connect to the database +connection = pymysql.connect(host='localhost', + user='user', + password='passwd', + database='db', + cursorclass=pymysql.cursors.DictCursor) + +with connection: + with connection.cursor() as cursor: + # Create a new record + sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)" + cursor.execute(sql, ('webmaster@python.org', 'very-secret')) + + # connection is not autocommit by default. So you must commit to save + # your changes. + connection.commit() + + with connection.cursor() as cursor: + # Read a single record + sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s" + cursor.execute(sql, ('webmaster@python.org',)) + result = cursor.fetchone() + print(result) +``` + +This example will print: + +``` python +{'password': 'very-secret', 'id': 1} +``` + +## Resources + +- DB-API 2.0: +- MySQL Reference Manuals: +- Getting Help With MariaDB +- MySQL client/server protocol: + +- "Connector" channel in MySQL Community Slack: + +- PyMySQL mailing list: + + +## License + +PyMySQL is released under the MIT License. See LICENSE for more +information. diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pymysql-1.1.3.dist-info/RECORD b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pymysql-1.1.3.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..5e6d1393923f999566dae64bea9766fd64bbf383 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pymysql-1.1.3.dist-info/RECORD @@ -0,0 +1,42 @@ +pymysql-1.1.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +pymysql-1.1.3.dist-info/METADATA,sha256=C_15Ebam9hWv-kZShIIpV49ZZVrQGUXD1REilhzEkTg,4306 +pymysql-1.1.3.dist-info/RECORD,, +pymysql-1.1.3.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91 +pymysql-1.1.3.dist-info/licenses/LICENSE,sha256=MUEg3GXwgA9ziksxQAx27hTezR--d86cNUCkIbhup7Y,1070 +pymysql-1.1.3.dist-info/top_level.txt,sha256=IKlV-f4o90sOdnMd6HBvo0l2nqfJOGUzkwZeaEEGuRg,8 +pymysql/__init__.py,sha256=oNtOny5WdCyu7oHNvn3Azx9410-jIiwSYq6eFBMCdag,4262 +pymysql/__pycache__/__init__.cpython-310.pyc,, +pymysql/__pycache__/_auth.cpython-310.pyc,, +pymysql/__pycache__/charset.cpython-310.pyc,, +pymysql/__pycache__/connections.cpython-310.pyc,, +pymysql/__pycache__/converters.cpython-310.pyc,, +pymysql/__pycache__/cursors.cpython-310.pyc,, +pymysql/__pycache__/err.cpython-310.pyc,, +pymysql/__pycache__/optionfile.cpython-310.pyc,, +pymysql/__pycache__/protocol.cpython-310.pyc,, +pymysql/__pycache__/times.cpython-310.pyc,, +pymysql/_auth.py,sha256=7bIFnJ7lJrFEhKLEnHGo1-h7E5cnZB2211KE1vatBAQ,7638 +pymysql/charset.py,sha256=Y4GgMDxn0Yz-99NwstfCLeCfoRFdwywWoHrn5Gnvghk,10258 +pymysql/connections.py,sha256=Bs8PG2UacyQF4hrJ7N68mdpifm7t5At0vTHvZFHZG8k,53908 +pymysql/constants/CLIENT.py,sha256=SSvMFPZCTVMU1UWa4zOrfhYMDdR2wG2mS0E5GzJhDsg,878 +pymysql/constants/COMMAND.py,sha256=TGITAUcNWlq2Gwg2wv5UK2ykdTd4LYTk_EcJJOCpGIc,679 +pymysql/constants/CR.py,sha256=Qk35FWRMxRHd6Sa9CCIATMh7jegR3xnLdrdaBCT0dTQ,2320 +pymysql/constants/ER.py,sha256=nwqX_r0o4mmN4Cxm7NVRyJOTVov_5Gbl5peGe6oz5fk,12357 +pymysql/constants/FIELD_TYPE.py,sha256=ytFzgAnGmb9hvdsBlnK68qdZv_a6jYFIXT6VSAb60z8,370 +pymysql/constants/FLAG.py,sha256=Fy-PrCLnUI7fx_o5WypYnUAzWAM0E9d5yL8fFRVKffY,214 +pymysql/constants/SERVER_STATUS.py,sha256=m28Iq5JGCFCWLhafE73-iOvw_9gDGqnytW3NkHpbugA,333 +pymysql/constants/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pymysql/constants/__pycache__/CLIENT.cpython-310.pyc,, +pymysql/constants/__pycache__/COMMAND.cpython-310.pyc,, +pymysql/constants/__pycache__/CR.cpython-310.pyc,, +pymysql/constants/__pycache__/ER.cpython-310.pyc,, +pymysql/constants/__pycache__/FIELD_TYPE.cpython-310.pyc,, +pymysql/constants/__pycache__/FLAG.cpython-310.pyc,, +pymysql/constants/__pycache__/SERVER_STATUS.cpython-310.pyc,, +pymysql/constants/__pycache__/__init__.cpython-310.pyc,, +pymysql/converters.py,sha256=8Jl-1K1Nt-ZKAiahBJV4MoSvO1O-PZtu8CfQG9EDftk,9523 +pymysql/cursors.py,sha256=O4duzCMsJycpUHJEt5Er3lrfrqe8J8Z47JqG6-DPz2w,16675 +pymysql/err.py,sha256=wLe0af6AmK6z7fq_MnYfgYsc6LnUuMj7EliHPZKquBA,4178 +pymysql/optionfile.py,sha256=eQoz6c43yvmHtp5MI9TB2GPRdoggOLemcUWABksfutk,651 +pymysql/protocol.py,sha256=aD-PGPRYcwkSI6ZJoJWZVRKn9H_A0f70KfPDu65tq0o,11812 +pymysql/times.py,sha256=_qXgDaYwsHntvpIKSKXp1rrYIgtq6Z9pLyLnO2XNoL0,360 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pymysql-1.1.3.dist-info/WHEEL b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pymysql-1.1.3.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..14a883f292bc96b20c2b76a3081991f2676523a9 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pymysql-1.1.3.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (82.0.1) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pymysql-1.1.3.dist-info/top_level.txt b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pymysql-1.1.3.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..d4a7eda50c15f0aee13204710d37dad082cf95ef --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pymysql-1.1.3.dist-info/top_level.txt @@ -0,0 +1 @@ +pymysql diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pytablewriter/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pytablewriter/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..609501c8c5930a400204046b9dfa63a8132e9086 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pytablewriter/__init__.py @@ -0,0 +1,133 @@ +""" +.. codeauthor:: Tsuyoshi Hombashi +""" + +from dataproperty import LineBreakHandling + +from .__version__ import __author__, __copyright__, __email__, __license__, __version__ +from ._factory import TableWriterFactory +from ._function import dumps_tabledata +from ._logger import set_logger +from ._table_format import FormatAttr, TableFormat +from .error import ( + EmptyTableDataError, + EmptyTableNameError, + EmptyValueError, + NotSupportedError, + WriterNotFoundError, +) +from .style import Align, Format +from .typehint import ( + Bool, + DateTime, + Dictionary, + Infinity, + Integer, + IpAddress, + List, + Nan, + NoneType, + NullString, + RealNumber, + String, +) +from .writer import ( + AbstractTableWriter, + AsciiDocTableWriter, + BoldUnicodeTableWriter, + BorderlessTableWriter, + CssTableWriter, + CsvTableWriter, + ElasticsearchWriter, + ExcelXlsTableWriter, + ExcelXlsxTableWriter, + HtmlTableWriter, + JavaScriptTableWriter, + JsonLinesTableWriter, + JsonTableWriter, + LatexMatrixWriter, + LatexTableWriter, + LtsvTableWriter, + MarkdownTableWriter, + MediaWikiTableWriter, + NullTableWriter, + NumpyTableWriter, + PandasDataFramePickleWriter, + PandasDataFrameWriter, + PythonCodeTableWriter, + RstCsvTableWriter, + RstGridTableWriter, + RstSimpleTableWriter, + SpaceAlignedTableWriter, + SqliteTableWriter, + TomlTableWriter, + TsvTableWriter, + UnicodeTableWriter, + YamlTableWriter, +) + + +__all__ = ( + "__author__", + "__copyright__", + "__email__", + "__license__", + "__version__", + "LineBreakHandling", + "TableWriterFactory", + "dumps_tabledata", + "set_logger", + "FormatAttr", + "TableFormat", + "Align", + "Format", + "Bool", + "DateTime", + "Dictionary", + "Infinity", + "Integer", + "IpAddress", + "List", + "Nan", + "NoneType", + "NullString", + "RealNumber", + "String", + "EmptyTableDataError", + "EmptyTableNameError", + "EmptyValueError", + "NotSupportedError", + "WriterNotFoundError", + "AbstractTableWriter", + "AsciiDocTableWriter", + "BoldUnicodeTableWriter", + "BorderlessTableWriter", + "CssTableWriter", + "CsvTableWriter", + "ElasticsearchWriter", + "ExcelXlsTableWriter", + "ExcelXlsxTableWriter", + "HtmlTableWriter", + "JavaScriptTableWriter", + "JsonLinesTableWriter", + "JsonTableWriter", + "LatexMatrixWriter", + "LatexTableWriter", + "LtsvTableWriter", + "MarkdownTableWriter", + "MediaWikiTableWriter", + "NullTableWriter", + "NumpyTableWriter", + "PandasDataFramePickleWriter", + "PandasDataFrameWriter", + "PythonCodeTableWriter", + "RstCsvTableWriter", + "RstGridTableWriter", + "RstSimpleTableWriter", + "SpaceAlignedTableWriter", + "SqliteTableWriter", + "TomlTableWriter", + "TsvTableWriter", + "UnicodeTableWriter", + "YamlTableWriter", +) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pytablewriter/__version__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pytablewriter/__version__.py new file mode 100644 index 0000000000000000000000000000000000000000..3742416fce9d48332e755b67aefb6b1ff6699db1 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pytablewriter/__version__.py @@ -0,0 +1,9 @@ +from typing import Final + + +__author__: Final = "Tsuyoshi Hombashi" +__copyright__: Final = f"Copyright 2016-2025, {__author__}" +__license__: Final = "MIT License" +__version__ = "1.2.1" +__maintainer__: Final = __author__ +__email__: Final = "tsuyoshi.hombashi@gmail.com" diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pytablewriter/_converter.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pytablewriter/_converter.py new file mode 100644 index 0000000000000000000000000000000000000000..2a8d70441a2dd20e4184eda5ab80bc4a5d116960 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pytablewriter/_converter.py @@ -0,0 +1,11 @@ +""" +.. codeauthor:: Tsuyoshi Hombashi +""" + +import re + + +def strip_quote(text: str, value: str) -> str: + re_replace = re.compile(f"[\"']{value:s}[\"']", re.MULTILINE) + + return re_replace.sub(value, text) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pytablewriter/_factory.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pytablewriter/_factory.py new file mode 100644 index 0000000000000000000000000000000000000000..0244a1cc7e8912800038b7ac6dc64513227029d0 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pytablewriter/_factory.py @@ -0,0 +1,274 @@ +""" +.. codeauthor:: Tsuyoshi Hombashi +""" + +import os +from itertools import chain +from typing import Any, Final + +import typepy + +from ._logger import logger +from ._table_format import FormatAttr, TableFormat +from .error import WriterNotFoundError +from .writer import AbstractTableWriter + + +class TableWriterFactory: + """ + A factory class of table writer classes. + """ + + @classmethod + def create_from_file_extension(cls, file_extension: str, **kwargs: Any) -> AbstractTableWriter: + """ + Create a table writer class instance from a file extension. + Supported file extensions are as follows: + + ================== =================================== + Extension Writer Class + ================== =================================== + ``".adoc"`` :py:class:`~.AsciiDocTableWriter` + ``".asciidoc"`` :py:class:`~.AsciiDocTableWriter` + ``".asc"`` :py:class:`~.AsciiDocTableWriter` + ``".css"`` :py:class:`~.CssTableWriter` + ``".csv"`` :py:class:`~.CsvTableWriter` + ``".htm"`` :py:class:`~.HtmlTableWriter` + ``".html"`` :py:class:`~.HtmlTableWriter` + ``".js"`` :py:class:`~.JavaScriptTableWriter` + ``".json"`` :py:class:`~.JsonTableWriter` + ``".jsonl"`` :py:class:`~.JsonLinesTableWriter` + ``".ltsv"`` :py:class:`~.LtsvTableWriter` + ``".ldjson"`` :py:class:`~.JsonLinesTableWriter` + ``".md"`` :py:class:`~.MarkdownTableWriter` + ``".ndjson"`` :py:class:`~.JsonLinesTableWriter` + ``".py"`` :py:class:`~.PythonCodeTableWriter` + ``".rst"`` :py:class:`~.RstGridTableWriter` + ``".tsv"`` :py:class:`~.TsvTableWriter` + ``".xls"`` :py:class:`~.ExcelXlsTableWriter` + ``".xlsx"`` :py:class:`~.ExcelXlsxTableWriter` + ``".sqlite"`` :py:class:`~.SqliteTableWriter` + ``".sqlite3"`` :py:class:`~.SqliteTableWriter` + ``".tsv"`` :py:class:`~.TsvTableWriter` + ``".toml"`` :py:class:`~.TomlTableWriter` + ``".yml"`` :py:class:`~.YamlTableWriter` + ================== =================================== + + :param str file_extension: + File extension string (case insensitive). + :param kwargs: + Keyword arguments that pass to a writer class constructor. + :return: + Writer instance that coincides with the ``file_extension``. + :rtype: + :py:class:`~pytablewriter.writer._table_writer.TableWriterInterface` + :raises pytablewriter.WriterNotFoundError: + |WriterNotFoundError_desc| the file extension. + """ + + ext: Final = os.path.splitext(file_extension)[1] + if typepy.is_null_string(ext): + file_extension = file_extension + else: + file_extension = ext + + file_extension = file_extension.lstrip(".").lower() + + for table_format in TableFormat: + if file_extension not in table_format.file_extensions: + continue + + if table_format.format_attribute & FormatAttr.SECONDARY_EXT: + continue + + logger.debug(f"create a {table_format.writer_class} instance") + + return table_format.writer_class(**kwargs) # type: ignore + + raise WriterNotFoundError( + "\n".join( + [ + f"{file_extension:s} (unknown file extension).", + "", + "acceptable file extensions are: {}.".format(", ".join(cls.get_extensions())), + ] + ) + ) + + @classmethod + def create_from_format_name(cls, format_name: str, **kwargs: Any) -> AbstractTableWriter: + """ + Create a table writer class instance from a format name. + Supported file format names are as follows: + + ============================================= =================================== + Format name Writer Class + ============================================= =================================== + ``"adoc"`` :py:class:`~.AsciiDocTableWriter` + ``"asciidoc"`` :py:class:`~.AsciiDocTableWriter` + ``"css"`` :py:class:`~.CssTableWriter` + ``"csv"`` :py:class:`~.CsvTableWriter` + ``"elasticsearch"`` :py:class:`~.ElasticsearchWriter` + ``"excel"`` :py:class:`~.ExcelXlsxTableWriter` + ``"html"``/``"htm"`` :py:class:`~.HtmlTableWriter` + ``"javascript"``/``"js"`` :py:class:`~.JavaScriptTableWriter` + ``"json"`` :py:class:`~.JsonTableWriter` + ``"json_lines"`` :py:class:`~.JsonLinesTableWriter` + ``"latex_matrix"`` :py:class:`~.LatexMatrixWriter` + ``"latex_table"`` :py:class:`~.LatexTableWriter` + ``"ldjson"`` :py:class:`~.JsonLinesTableWriter` + ``"ltsv"`` :py:class:`~.LtsvTableWriter` + ``"markdown"``/``"md"`` :py:class:`~.MarkdownTableWriter` + ``"mediawiki"`` :py:class:`~.MediaWikiTableWriter` + ``"null"`` :py:class:`~.NullTableWriter` + ``"pandas"`` :py:class:`~.PandasDataFrameWriter` + ``"py"``/``"python"`` :py:class:`~.PythonCodeTableWriter` + ``"rst"``/``"rst_grid"``/``"rst_grid_table"`` :py:class:`~.RstGridTableWriter` + ``"rst_simple"``/``"rst_simple_table"`` :py:class:`~.RstSimpleTableWriter` + ``"rst_csv"``/``"rst_csv_table"`` :py:class:`~.RstCsvTableWriter` + ``"sqlite"`` :py:class:`~.SqliteTableWriter` + ``"ssv"`` :py:class:`~.SpaceAlignedTableWriter` + ``"tsv"`` :py:class:`~.TsvTableWriter` + ``"toml"`` :py:class:`~.TomlTableWriter` + ``"unicode"`` :py:class:`~.UnicodeTableWriter` + ``"yaml"`` :py:class:`~.YamlTableWriter` + ============================================= =================================== + + :param str format_name: + Format name string (case insensitive). + :param kwargs: + Keyword arguments that pass to a writer class constructor. + :return: + Writer instance that coincides with the ``format_name``: + :rtype: + :py:class:`~pytablewriter.writer._table_writer.TableWriterInterface` + :raises pytablewriter.WriterNotFoundError: + |WriterNotFoundError_desc| for the format. + """ + + format_name = format_name.casefold() + + for table_format in TableFormat: + if format_name in table_format.names and not ( + table_format.format_attribute & FormatAttr.SECONDARY_NAME + ): + writer = table_format.writer_class(**kwargs) # type: ignore + logger.debug(f"create a {writer.FORMAT_NAME} instance") + + return writer + + raise WriterNotFoundError( + "\n".join( + [ + f"{format_name} (unknown format name).", + "acceptable format names are: {}.".format(", ".join(cls.get_format_names())), + ] + ) + ) + + @classmethod + def get_format_names(cls) -> list[str]: + """ + :return: Available format names. + :rtype: list + + :Example: + .. code:: python + + >>> import pytablewriter as ptw + >>> for name in ptw.TableWriterFactory.get_format_names(): + ... print(name) + ... + adoc + asciidoc + bold_unicode + borderless + css + csv + elasticsearch + excel + htm + html + javascript + js + json + json_lines + jsonl + latex_matrix + latex_table + ldjson + ltsv + markdown + md + mediawiki + ndjson + null + numpy + pandas + pandas_pickle + py + python + rst + rst_csv + rst_csv_table + rst_grid + rst_grid_table + rst_simple + rst_simple_table + space_aligned + sqlite + ssv + toml + tsv + unicode + yaml + + """ + + return sorted(list(set(chain(*(table_format.names for table_format in TableFormat))))) + + @classmethod + def get_extensions(cls) -> list[str]: + """ + :return: Available file extensions. + :rtype: list + + :Example: + .. code:: python + + >>> import pytablewriter as ptw + >>> for name in ptw.TableWriterFactory.get_extensions(): + ... print(name) + ... + adoc + asc + asciidoc + css + csv + htm + html + js + json + jsonl + ldjson + ltsv + md + ndjson + py + rst + sqlite + sqlite3 + tex + toml + tsv + xls + xlsx + yml + """ + + file_extension_set = set() + for table_format in TableFormat: + for file_extension in table_format.file_extensions: + file_extension_set.add(file_extension) + + return sorted(list(file_extension_set)) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pytablewriter/_function.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pytablewriter/_function.py new file mode 100644 index 0000000000000000000000000000000000000000..0e116a1ae13fda44995680c1400ac3b794da2047 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pytablewriter/_function.py @@ -0,0 +1,84 @@ +""" +.. codeauthor:: Tsuyoshi Hombashi +""" + +from datetime import datetime +from enum import Enum +from typing import Any, Optional + +import dataproperty +from pathvalidate import replace_symbol +from tabledata._core import TableData + + +def quote_datetime_formatter(value: datetime) -> str: + return f'"{value.strftime(dataproperty.DefaultValue.DATETIME_FORMAT):s}"' + + +def dateutil_datetime_formatter(value: datetime) -> str: + return 'dateutil.parser.parse("{:s}")'.format( + value.strftime(dataproperty.DefaultValue.DATETIME_FORMAT) + ) + + +def dumps_tabledata(value: TableData, format_name: str = "rst_grid_table", **kwargs: Any) -> str: + """ + :param tabledata.TableData value: Tabular data to dump. + :param str format_name: + Dumped format name of tabular data. + Available formats are described in + :py:meth:`~pytablewriter.TableWriterFactory.create_from_format_name` + + :Example: + .. code:: python + + >>> dumps_tabledata(value) + .. table:: sample_data + + ====== ====== ====== + attr_a attr_b attr_c + ====== ====== ====== + 1 4.0 a + 2 2.1 bb + 3 120.9 ccc + ====== ====== ====== + """ + + from ._factory import TableWriterFactory + + if not value: + raise TypeError("value must be a tabledata.TableData instance") + + writer = TableWriterFactory.create_from_format_name(format_name) + + for attr_name, attr_value in kwargs.items(): + setattr(writer, attr_name, attr_value) + + writer.from_tabledata(value) + + return writer.dumps() + + +def normalize_enum( + value: Any, enum_class: type[Enum], validate: bool = True, default: Optional[Enum] = None +) -> Any: + if value is None: + return default + + if isinstance(value, enum_class): + return value + + try: + return enum_class[replace_symbol(value.strip(), "_").upper()] + except AttributeError: + if validate: + raise TypeError(f"value must be a {enum_class} or a str: actual={type(value)}") + except KeyError: + if validate: + raise ValueError( + "invalid valid found: expected={}, actual={}".format( + "/".join(item.name for item in enum_class), value + ) + ) + + return value diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pytablewriter/_table_format.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pytablewriter/_table_format.py new file mode 100644 index 0000000000000000000000000000000000000000..fccd04756d2060e608ef83c63038065a9d44bba7 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pytablewriter/_table_format.py @@ -0,0 +1,354 @@ +""" +.. codeauthor:: Tsuyoshi Hombashi +""" + +import enum +from collections.abc import Sequence +from typing import Optional + +from .writer import ( + AbstractTableWriter, + AsciiDocTableWriter, + BoldUnicodeTableWriter, + BorderlessTableWriter, + CssTableWriter, + CsvTableWriter, + ElasticsearchWriter, + ExcelXlsTableWriter, + ExcelXlsxTableWriter, + HtmlTableWriter, + JavaScriptTableWriter, + JsonLinesTableWriter, + JsonTableWriter, + LatexMatrixWriter, + LatexTableWriter, + LtsvTableWriter, + MarkdownTableWriter, + MediaWikiTableWriter, + NullTableWriter, + NumpyTableWriter, + PandasDataFramePickleWriter, + PandasDataFrameWriter, + PythonCodeTableWriter, + RstCsvTableWriter, + RstGridTableWriter, + RstSimpleTableWriter, + SpaceAlignedTableWriter, + SqliteTableWriter, + TomlTableWriter, + TsvTableWriter, + UnicodeTableWriter, + YamlTableWriter, +) + + +class FormatAttr: + """ + Bitmaps to represent table attributes. + """ + + NONE = 1 << 1 + + #: Can create a file with the format. + FILE = 1 << 2 + + #: Table format that can represent as a text. + TEXT = 1 << 3 + + #: Table format that can represent as a binary file. + BIN = 1 << 4 + + #: Can create a source code (variables definition) + #: one of the programming language. + SOURCECODE = 1 << 5 + + #: Can call API for external service. + API = 1 << 6 + + SECONDARY_EXT = 1 << 10 + SECONDARY_NAME = 1 << 11 + + +@enum.unique +class TableFormat(enum.Enum): + """ + Enum to represent table format attributes. + """ + + ASCIIDOC = ( + [AsciiDocTableWriter.FORMAT_NAME, "adoc"], + AsciiDocTableWriter, + FormatAttr.FILE | FormatAttr.TEXT, + ["adoc", "asciidoc", "asc"], + ) + CSV = ([CsvTableWriter.FORMAT_NAME], CsvTableWriter, FormatAttr.FILE | FormatAttr.TEXT, ["csv"]) + CSS = ( + [CssTableWriter.FORMAT_NAME], + CssTableWriter, + FormatAttr.FILE | FormatAttr.TEXT, + ["css"], + ) + ELASTICSEARCH = ( + [ElasticsearchWriter.FORMAT_NAME], # type: ignore + ElasticsearchWriter, + FormatAttr.API, + [], + ) + EXCEL_XLSX = ( + [ExcelXlsxTableWriter.FORMAT_NAME], + ExcelXlsxTableWriter, + FormatAttr.FILE | FormatAttr.BIN, + ["xlsx"], + ) + EXCEL_XLS = ( + [ExcelXlsTableWriter.FORMAT_NAME], + ExcelXlsTableWriter, + FormatAttr.FILE | FormatAttr.BIN | FormatAttr.SECONDARY_NAME, + ["xls"], + ) + HTML = ( + [HtmlTableWriter.FORMAT_NAME, "htm"], + HtmlTableWriter, + FormatAttr.FILE | FormatAttr.TEXT, + ["html", "htm"], + ) + JAVASCRIPT = ( + [JavaScriptTableWriter.FORMAT_NAME, "js"], + JavaScriptTableWriter, + FormatAttr.FILE | FormatAttr.TEXT | FormatAttr.SOURCECODE, + ["js"], + ) + JSON = ( + [JsonTableWriter.FORMAT_NAME], + JsonTableWriter, + FormatAttr.FILE | FormatAttr.TEXT, + ["json"], + ) + JSON_LINES = ( + [JsonLinesTableWriter.FORMAT_NAME, "jsonl", "ldjson", "ndjson"], + JsonLinesTableWriter, + FormatAttr.FILE | FormatAttr.TEXT, + ["jsonl", "ldjson", "ndjson"], + ) + LATEX_MATRIX = ( + [LatexMatrixWriter.FORMAT_NAME], + LatexMatrixWriter, + FormatAttr.FILE | FormatAttr.TEXT, + ["tex"], + ) + LATEX_TABLE = ( + [LatexTableWriter.FORMAT_NAME], + LatexTableWriter, + FormatAttr.FILE | FormatAttr.TEXT | FormatAttr.SECONDARY_EXT, + ["tex"], + ) + LTSV = ( + [LtsvTableWriter.FORMAT_NAME], + LtsvTableWriter, + FormatAttr.FILE | FormatAttr.TEXT, + ["ltsv"], + ) + MARKDOWN = ( + [MarkdownTableWriter.FORMAT_NAME, "md"], + MarkdownTableWriter, + FormatAttr.FILE | FormatAttr.TEXT, + ["md"], + ) + MEDIAWIKI = ( + [MediaWikiTableWriter.FORMAT_NAME], # type: ignore + MediaWikiTableWriter, + FormatAttr.FILE | FormatAttr.TEXT, + [], + ) + NULL = ( + [NullTableWriter.FORMAT_NAME], # type: ignore + NullTableWriter, + FormatAttr.NONE, + [], + ) + NUMPY = ( + [NumpyTableWriter.FORMAT_NAME], + NumpyTableWriter, + FormatAttr.FILE | FormatAttr.TEXT | FormatAttr.SOURCECODE | FormatAttr.SECONDARY_EXT, + ["py"], + ) + PANDAS = ( + [PandasDataFrameWriter.FORMAT_NAME], + PandasDataFrameWriter, + FormatAttr.FILE | FormatAttr.TEXT | FormatAttr.SOURCECODE | FormatAttr.SECONDARY_EXT, + ["py"], + ) + PANDAS_PICKLE = ( + [PandasDataFramePickleWriter.FORMAT_NAME], # type: ignore + PandasDataFramePickleWriter, + FormatAttr.FILE | FormatAttr.BIN, + [], + ) + PYTHON = ( + [PythonCodeTableWriter.FORMAT_NAME, "py"], + PythonCodeTableWriter, + FormatAttr.FILE | FormatAttr.TEXT | FormatAttr.SOURCECODE, + ["py"], + ) + RST_CSV_TABLE = ( + [RstCsvTableWriter.FORMAT_NAME, "rst_csv"], + RstCsvTableWriter, + FormatAttr.FILE | FormatAttr.TEXT | FormatAttr.SECONDARY_EXT, + ["rst"], + ) + RST_GRID_TABLE = ( + [RstGridTableWriter.FORMAT_NAME, "rst_grid", "rst"], + RstGridTableWriter, + FormatAttr.FILE | FormatAttr.TEXT, + ["rst"], + ) + RST_SIMPLE_TABLE = ( + [RstSimpleTableWriter.FORMAT_NAME, "rst_simple"], + RstSimpleTableWriter, + FormatAttr.FILE | FormatAttr.TEXT | FormatAttr.SECONDARY_EXT, + ["rst"], + ) + SPACE_ALIGNED = ( + [SpaceAlignedTableWriter.FORMAT_NAME, "ssv"], # type: ignore + SpaceAlignedTableWriter, + FormatAttr.FILE | FormatAttr.TEXT, + [], + ) + SQLITE = ( + [SqliteTableWriter.FORMAT_NAME], + SqliteTableWriter, + FormatAttr.FILE | FormatAttr.BIN, + ["sqlite", "sqlite3"], + ) + TOML = ( + [TomlTableWriter.FORMAT_NAME], + TomlTableWriter, + FormatAttr.FILE | FormatAttr.TEXT, + ["toml"], + ) + TSV = ([TsvTableWriter.FORMAT_NAME], TsvTableWriter, FormatAttr.FILE | FormatAttr.TEXT, ["tsv"]) + UNICODE = ( + [UnicodeTableWriter.FORMAT_NAME], # type: ignore + UnicodeTableWriter, + FormatAttr.TEXT, + [], + ) + YAML = ( + [YamlTableWriter.FORMAT_NAME], + YamlTableWriter, + FormatAttr.FILE | FormatAttr.TEXT, + ["yml"], + ) + BOLD_UNICODE = ( + [BoldUnicodeTableWriter.FORMAT_NAME], # type: ignore + BoldUnicodeTableWriter, + FormatAttr.TEXT, + [], + ) + BORDERLESS = ( + [BorderlessTableWriter.FORMAT_NAME], # type: ignore + BorderlessTableWriter, + FormatAttr.TEXT, + [], + ) + + @property + def names(self) -> list[str]: + """ + List[str]: Names associated with the table format. + """ + + return self.__names + + @property + def writer_class(self) -> type[AbstractTableWriter]: + """ + Type[AbstractTableWriter]: Table writer class object associated with the table format. + """ + + return self.__writer_class + + @property + def format_attribute(self) -> int: + """ + FormatAttr: Table attributes bitmap. + """ + + return self.__format_attribute + + @property + def file_extensions(self) -> list[str]: + """ + List[str]: File extensions associated with the table format. + """ + + return self.__file_extensions + + def __init__( + self, + names: Sequence[str], + writer_class: type[AbstractTableWriter], + format_attribute: int, + file_extensions: Sequence[str], + ) -> None: + self.__names = list(names) + self.__writer_class = writer_class + self.__format_attribute = format_attribute + self.__file_extensions = list(file_extensions) + + @classmethod + def find_all_attr(cls, format_attribute: int) -> list["TableFormat"]: + """Searching table formats that have specific attributes. + + Args: + format_attribute (FormatAttr): + Table format attributes to look for. + + Returns: + List[TableFormat]: Table formats that matched the attribute. + """ + + return [ + table_format + for table_format in TableFormat + if table_format.format_attribute & format_attribute + ] + + @classmethod + def from_name(cls, format_name: str) -> Optional["TableFormat"]: + """Get a table format from a format name. + + Args: + format_name (str): Table format specifier. + + Returns: + Optional[TableFormat]: A table format enum value corresponding to the ``format_name``. + """ + + format_name = format_name.casefold().strip() + + for table_format in TableFormat: + if format_name in table_format.names: + return table_format + + return None + + @classmethod + def from_file_extension(cls, file_extension: str) -> Optional["TableFormat"]: + """Get a table format from a file extension. + + Args: + file_extension (str): File extension. + + Returns: + Optional[TableFormat]: + A table format enum value corresponding to the ``file_extension``. + """ + + ext = file_extension.lower().strip().lstrip(".") + + for table_format in TableFormat: + if ext in table_format.file_extensions: + return table_format + + return None diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pytablewriter/error.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pytablewriter/error.py new file mode 100644 index 0000000000000000000000000000000000000000..325be5c2e4395d0898fc7d9b3b43acf011ec48b7 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pytablewriter/error.py @@ -0,0 +1,34 @@ +""" +.. codeauthor:: Tsuyoshi Hombashi +""" + + +class NotSupportedError(Exception): + pass + + +class EmptyTableNameError(Exception): + """ + Exception raised when a table writer class of the |table_name| attribute + is null and the class is not accepted null |table_name|. + """ + + +class EmptyValueError(Exception): + """ + Exception raised when a table writer class of the |value_matrix| attribute + is null, and the class is not accepted null |value_matrix|. + """ + + +class EmptyTableDataError(Exception): + """ + Exception raised when a table writer class of the |headers| and + |value_matrix| attributes are null. + """ + + +class WriterNotFoundError(Exception): + """ + Exception raised when appropriate loader writer found. + """ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pytablewriter/py.typed b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pytablewriter/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/requests_oauthlib/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/requests_oauthlib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..865d72fb768b4cac4912efd3afc62af2c774dbab --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/requests_oauthlib/__init__.py @@ -0,0 +1,20 @@ +# ruff: noqa: F401 +import logging + +from .oauth1_auth import OAuth1 +from .oauth1_session import OAuth1Session +from .oauth2_auth import OAuth2 +from .oauth2_session import OAuth2Session, TokenUpdated + +__version__ = "2.0.0" + +import requests + +if requests.__version__ < "2.0.0": + msg = ( + "You are using requests version %s, which is older than " + "requests-oauthlib expects, please upgrade to 2.0.0 or later." + ) + raise Warning(msg % requests.__version__) + +logging.getLogger("requests_oauthlib").addHandler(logging.NullHandler()) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/requests_oauthlib/oauth1_auth.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/requests_oauthlib/oauth1_auth.py new file mode 100644 index 0000000000000000000000000000000000000000..f8c0bd6e74e7caffb99874b62d363df92cd8f1a5 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/requests_oauthlib/oauth1_auth.py @@ -0,0 +1,112 @@ +# -*- coding: utf-8 -*- +import logging + +from oauthlib.common import extract_params +from oauthlib.oauth1 import Client, SIGNATURE_HMAC, SIGNATURE_TYPE_AUTH_HEADER +from oauthlib.oauth1 import SIGNATURE_TYPE_BODY +from requests.utils import to_native_string +from requests.auth import AuthBase + +CONTENT_TYPE_FORM_URLENCODED = "application/x-www-form-urlencoded" +CONTENT_TYPE_MULTI_PART = "multipart/form-data" + + +log = logging.getLogger(__name__) + +# OBS!: Correct signing of requests are conditional on invoking OAuth1 +# as the last step of preparing a request, or at least having the +# content-type set properly. +class OAuth1(AuthBase): + """Signs the request using OAuth 1 (RFC5849)""" + + client_class = Client + + def __init__( + self, + client_key, + client_secret=None, + resource_owner_key=None, + resource_owner_secret=None, + callback_uri=None, + signature_method=SIGNATURE_HMAC, + signature_type=SIGNATURE_TYPE_AUTH_HEADER, + rsa_key=None, + verifier=None, + decoding="utf-8", + client_class=None, + force_include_body=False, + **kwargs + ): + + try: + signature_type = signature_type.upper() + except AttributeError: + pass + + client_class = client_class or self.client_class + + self.force_include_body = force_include_body + + self.client = client_class( + client_key, + client_secret, + resource_owner_key, + resource_owner_secret, + callback_uri, + signature_method, + signature_type, + rsa_key, + verifier, + decoding=decoding, + **kwargs + ) + + def __call__(self, r): + """Add OAuth parameters to the request. + + Parameters may be included from the body if the content-type is + urlencoded, if no content type is set a guess is made. + """ + # Overwriting url is safe here as request will not modify it past + # this point. + log.debug("Signing request %s using client %s", r, self.client) + + content_type = r.headers.get("Content-Type", "") + if ( + not content_type + and extract_params(r.body) + or self.client.signature_type == SIGNATURE_TYPE_BODY + ): + content_type = CONTENT_TYPE_FORM_URLENCODED + if not isinstance(content_type, str): + content_type = content_type.decode("utf-8") + + is_form_encoded = CONTENT_TYPE_FORM_URLENCODED in content_type + + log.debug( + "Including body in call to sign: %s", + is_form_encoded or self.force_include_body, + ) + + if is_form_encoded: + r.headers["Content-Type"] = CONTENT_TYPE_FORM_URLENCODED + r.url, headers, r.body = self.client.sign( + str(r.url), str(r.method), r.body or "", r.headers + ) + elif self.force_include_body: + # To allow custom clients to work on non form encoded bodies. + r.url, headers, r.body = self.client.sign( + str(r.url), str(r.method), r.body or "", r.headers + ) + else: + # Omit body data in the signing of non form-encoded requests + r.url, headers, _ = self.client.sign( + str(r.url), str(r.method), None, r.headers + ) + + r.prepare_headers(headers) + r.url = to_native_string(r.url) + log.debug("Updated url: %s", r.url) + log.debug("Updated headers: %s", headers) + log.debug("Updated body: %r", r.body) + return r diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/requests_oauthlib/oauth1_session.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/requests_oauthlib/oauth1_session.py new file mode 100644 index 0000000000000000000000000000000000000000..7625c8084eecd402705e4bb76ea0604dcaa20560 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/requests_oauthlib/oauth1_session.py @@ -0,0 +1,395 @@ +from urllib.parse import urlparse + +import logging + +from oauthlib.common import add_params_to_uri +from oauthlib.common import urldecode as _urldecode +from oauthlib.oauth1 import SIGNATURE_HMAC, SIGNATURE_RSA, SIGNATURE_TYPE_AUTH_HEADER +import requests + +from . import OAuth1 + + +log = logging.getLogger(__name__) + + +def urldecode(body): + """Parse query or json to python dictionary""" + try: + return _urldecode(body) + except Exception: + import json + + return json.loads(body) + + +class TokenRequestDenied(ValueError): + def __init__(self, message, response): + super(TokenRequestDenied, self).__init__(message) + self.response = response + + @property + def status_code(self): + """For backwards-compatibility purposes""" + return self.response.status_code + + +class TokenMissing(ValueError): + def __init__(self, message, response): + super(TokenMissing, self).__init__(message) + self.response = response + + +class VerifierMissing(ValueError): + pass + + +class OAuth1Session(requests.Session): + """Request signing and convenience methods for the oauth dance. + + What is the difference between OAuth1Session and OAuth1? + + OAuth1Session actually uses OAuth1 internally and its purpose is to assist + in the OAuth workflow through convenience methods to prepare authorization + URLs and parse the various token and redirection responses. It also provide + rudimentary validation of responses. + + An example of the OAuth workflow using a basic CLI app and Twitter. + + >>> # Credentials obtained during the registration. + >>> client_key = 'client key' + >>> client_secret = 'secret' + >>> callback_uri = 'https://127.0.0.1/callback' + >>> + >>> # Endpoints found in the OAuth provider API documentation + >>> request_token_url = 'https://api.twitter.com/oauth/request_token' + >>> authorization_url = 'https://api.twitter.com/oauth/authorize' + >>> access_token_url = 'https://api.twitter.com/oauth/access_token' + >>> + >>> oauth_session = OAuth1Session(client_key,client_secret=client_secret, callback_uri=callback_uri) + >>> + >>> # First step, fetch the request token. + >>> oauth_session.fetch_request_token(request_token_url) + { + 'oauth_token': 'kjerht2309u', + 'oauth_token_secret': 'lsdajfh923874', + } + >>> + >>> # Second step. Follow this link and authorize + >>> oauth_session.authorization_url(authorization_url) + 'https://api.twitter.com/oauth/authorize?oauth_token=sdf0o9823sjdfsdf&oauth_callback=https%3A%2F%2F127.0.0.1%2Fcallback' + >>> + >>> # Third step. Fetch the access token + >>> redirect_response = input('Paste the full redirect URL here.') + >>> oauth_session.parse_authorization_response(redirect_response) + { + 'oauth_token: 'kjerht2309u', + 'oauth_token_secret: 'lsdajfh923874', + 'oauth_verifier: 'w34o8967345', + } + >>> oauth_session.fetch_access_token(access_token_url) + { + 'oauth_token': 'sdf0o9823sjdfsdf', + 'oauth_token_secret': '2kjshdfp92i34asdasd', + } + >>> # Done. You can now make OAuth requests. + >>> status_url = 'http://api.twitter.com/1/statuses/update.json' + >>> new_status = {'status': 'hello world!'} + >>> oauth_session.post(status_url, data=new_status) + + """ + + def __init__( + self, + client_key, + client_secret=None, + resource_owner_key=None, + resource_owner_secret=None, + callback_uri=None, + signature_method=SIGNATURE_HMAC, + signature_type=SIGNATURE_TYPE_AUTH_HEADER, + rsa_key=None, + verifier=None, + client_class=None, + force_include_body=False, + **kwargs + ): + """Construct the OAuth 1 session. + + :param client_key: A client specific identifier. + :param client_secret: A client specific secret used to create HMAC and + plaintext signatures. + :param resource_owner_key: A resource owner key, also referred to as + request token or access token depending on + when in the workflow it is used. + :param resource_owner_secret: A resource owner secret obtained with + either a request or access token. Often + referred to as token secret. + :param callback_uri: The URL the user is redirect back to after + authorization. + :param signature_method: Signature methods determine how the OAuth + signature is created. The three options are + oauthlib.oauth1.SIGNATURE_HMAC (default), + oauthlib.oauth1.SIGNATURE_RSA and + oauthlib.oauth1.SIGNATURE_PLAIN. + :param signature_type: Signature type decides where the OAuth + parameters are added. Either in the + Authorization header (default) or to the URL + query parameters or the request body. Defined as + oauthlib.oauth1.SIGNATURE_TYPE_AUTH_HEADER, + oauthlib.oauth1.SIGNATURE_TYPE_QUERY and + oauthlib.oauth1.SIGNATURE_TYPE_BODY + respectively. + :param rsa_key: The private RSA key as a string. Can only be used with + signature_method=oauthlib.oauth1.SIGNATURE_RSA. + :param verifier: A verifier string to prove authorization was granted. + :param client_class: A subclass of `oauthlib.oauth1.Client` to use with + `requests_oauthlib.OAuth1` instead of the default + :param force_include_body: Always include the request body in the + signature creation. + :param **kwargs: Additional keyword arguments passed to `OAuth1` + """ + super(OAuth1Session, self).__init__() + self._client = OAuth1( + client_key, + client_secret=client_secret, + resource_owner_key=resource_owner_key, + resource_owner_secret=resource_owner_secret, + callback_uri=callback_uri, + signature_method=signature_method, + signature_type=signature_type, + rsa_key=rsa_key, + verifier=verifier, + client_class=client_class, + force_include_body=force_include_body, + **kwargs + ) + self.auth = self._client + + @property + def token(self): + oauth_token = self._client.client.resource_owner_key + oauth_token_secret = self._client.client.resource_owner_secret + oauth_verifier = self._client.client.verifier + + token_dict = {} + if oauth_token: + token_dict["oauth_token"] = oauth_token + if oauth_token_secret: + token_dict["oauth_token_secret"] = oauth_token_secret + if oauth_verifier: + token_dict["oauth_verifier"] = oauth_verifier + + return token_dict + + @token.setter + def token(self, value): + self._populate_attributes(value) + + @property + def authorized(self): + """Boolean that indicates whether this session has an OAuth token + or not. If `self.authorized` is True, you can reasonably expect + OAuth-protected requests to the resource to succeed. If + `self.authorized` is False, you need the user to go through the OAuth + authentication dance before OAuth-protected requests to the resource + will succeed. + """ + if self._client.client.signature_method == SIGNATURE_RSA: + # RSA only uses resource_owner_key + return bool(self._client.client.resource_owner_key) + else: + # other methods of authentication use all three pieces + return ( + bool(self._client.client.client_secret) + and bool(self._client.client.resource_owner_key) + and bool(self._client.client.resource_owner_secret) + ) + + def authorization_url(self, url, request_token=None, **kwargs): + """Create an authorization URL by appending request_token and optional + kwargs to url. + + This is the second step in the OAuth 1 workflow. The user should be + redirected to this authorization URL, grant access to you, and then + be redirected back to you. The redirection back can either be specified + during client registration or by supplying a callback URI per request. + + :param url: The authorization endpoint URL. + :param request_token: The previously obtained request token. + :param kwargs: Optional parameters to append to the URL. + :returns: The authorization URL with new parameters embedded. + + An example using a registered default callback URI. + + >>> request_token_url = 'https://api.twitter.com/oauth/request_token' + >>> authorization_url = 'https://api.twitter.com/oauth/authorize' + >>> oauth_session = OAuth1Session('client-key', client_secret='secret') + >>> oauth_session.fetch_request_token(request_token_url) + { + 'oauth_token': 'sdf0o9823sjdfsdf', + 'oauth_token_secret': '2kjshdfp92i34asdasd', + } + >>> oauth_session.authorization_url(authorization_url) + 'https://api.twitter.com/oauth/authorize?oauth_token=sdf0o9823sjdfsdf' + >>> oauth_session.authorization_url(authorization_url, foo='bar') + 'https://api.twitter.com/oauth/authorize?oauth_token=sdf0o9823sjdfsdf&foo=bar' + + An example using an explicit callback URI. + + >>> request_token_url = 'https://api.twitter.com/oauth/request_token' + >>> authorization_url = 'https://api.twitter.com/oauth/authorize' + >>> oauth_session = OAuth1Session('client-key', client_secret='secret', callback_uri='https://127.0.0.1/callback') + >>> oauth_session.fetch_request_token(request_token_url) + { + 'oauth_token': 'sdf0o9823sjdfsdf', + 'oauth_token_secret': '2kjshdfp92i34asdasd', + } + >>> oauth_session.authorization_url(authorization_url) + 'https://api.twitter.com/oauth/authorize?oauth_token=sdf0o9823sjdfsdf&oauth_callback=https%3A%2F%2F127.0.0.1%2Fcallback' + """ + kwargs["oauth_token"] = request_token or self._client.client.resource_owner_key + log.debug("Adding parameters %s to url %s", kwargs, url) + return add_params_to_uri(url, kwargs.items()) + + def fetch_request_token(self, url, realm=None, **request_kwargs): + """Fetch a request token. + + This is the first step in the OAuth 1 workflow. A request token is + obtained by making a signed post request to url. The token is then + parsed from the application/x-www-form-urlencoded response and ready + to be used to construct an authorization url. + + :param url: The request token endpoint URL. + :param realm: A list of realms to request access to. + :param request_kwargs: Optional arguments passed to ''post'' + function in ''requests.Session'' + :returns: The response in dict format. + + Note that a previously set callback_uri will be reset for your + convenience, or else signature creation will be incorrect on + consecutive requests. + + >>> request_token_url = 'https://api.twitter.com/oauth/request_token' + >>> oauth_session = OAuth1Session('client-key', client_secret='secret') + >>> oauth_session.fetch_request_token(request_token_url) + { + 'oauth_token': 'sdf0o9823sjdfsdf', + 'oauth_token_secret': '2kjshdfp92i34asdasd', + } + """ + self._client.client.realm = " ".join(realm) if realm else None + token = self._fetch_token(url, **request_kwargs) + log.debug("Resetting callback_uri and realm (not needed in next phase).") + self._client.client.callback_uri = None + self._client.client.realm = None + return token + + def fetch_access_token(self, url, verifier=None, **request_kwargs): + """Fetch an access token. + + This is the final step in the OAuth 1 workflow. An access token is + obtained using all previously obtained credentials, including the + verifier from the authorization step. + + Note that a previously set verifier will be reset for your + convenience, or else signature creation will be incorrect on + consecutive requests. + + >>> access_token_url = 'https://api.twitter.com/oauth/access_token' + >>> redirect_response = 'https://127.0.0.1/callback?oauth_token=kjerht2309uf&oauth_token_secret=lsdajfh923874&oauth_verifier=w34o8967345' + >>> oauth_session = OAuth1Session('client-key', client_secret='secret') + >>> oauth_session.parse_authorization_response(redirect_response) + { + 'oauth_token: 'kjerht2309u', + 'oauth_token_secret: 'lsdajfh923874', + 'oauth_verifier: 'w34o8967345', + } + >>> oauth_session.fetch_access_token(access_token_url) + { + 'oauth_token': 'sdf0o9823sjdfsdf', + 'oauth_token_secret': '2kjshdfp92i34asdasd', + } + """ + if verifier: + self._client.client.verifier = verifier + if not getattr(self._client.client, "verifier", None): + raise VerifierMissing("No client verifier has been set.") + token = self._fetch_token(url, **request_kwargs) + log.debug("Resetting verifier attribute, should not be used anymore.") + self._client.client.verifier = None + return token + + def parse_authorization_response(self, url): + """Extract parameters from the post authorization redirect response URL. + + :param url: The full URL that resulted from the user being redirected + back from the OAuth provider to you, the client. + :returns: A dict of parameters extracted from the URL. + + >>> redirect_response = 'https://127.0.0.1/callback?oauth_token=kjerht2309uf&oauth_token_secret=lsdajfh923874&oauth_verifier=w34o8967345' + >>> oauth_session = OAuth1Session('client-key', client_secret='secret') + >>> oauth_session.parse_authorization_response(redirect_response) + { + 'oauth_token: 'kjerht2309u', + 'oauth_token_secret: 'lsdajfh923874', + 'oauth_verifier: 'w34o8967345', + } + """ + log.debug("Parsing token from query part of url %s", url) + token = dict(urldecode(urlparse(url).query)) + log.debug("Updating internal client token attribute.") + self._populate_attributes(token) + self.token = token + return token + + def _populate_attributes(self, token): + if "oauth_token" in token: + self._client.client.resource_owner_key = token["oauth_token"] + else: + raise TokenMissing( + "Response does not contain a token: {resp}".format(resp=token), token + ) + if "oauth_token_secret" in token: + self._client.client.resource_owner_secret = token["oauth_token_secret"] + if "oauth_verifier" in token: + self._client.client.verifier = token["oauth_verifier"] + + def _fetch_token(self, url, **request_kwargs): + log.debug("Fetching token from %s using client %s", url, self._client.client) + r = self.post(url, **request_kwargs) + + if r.status_code >= 400: + error = "Token request failed with code %s, response was '%s'." + raise TokenRequestDenied(error % (r.status_code, r.text), r) + + log.debug('Decoding token from response "%s"', r.text) + try: + token = dict(urldecode(r.text.strip())) + except ValueError as e: + error = ( + "Unable to decode token from token response. " + "This is commonly caused by an unsuccessful request where" + " a non urlencoded error message is returned. " + "The decoding error was %s" + "" % e + ) + raise ValueError(error) + + log.debug("Obtained token %s", token) + log.debug("Updating internal client attributes from token data.") + self._populate_attributes(token) + self.token = token + return token + + def rebuild_auth(self, prepared_request, response): + """ + When being redirected we should always strip Authorization + header, since nonce may not be reused as per OAuth spec. + """ + if "Authorization" in prepared_request.headers: + # If we get redirected to a new host, we should strip out + # any authentication headers. + prepared_request.headers.pop("Authorization", True) + prepared_request.prepare_auth(self.auth) + return diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/requests_oauthlib/oauth2_auth.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/requests_oauthlib/oauth2_auth.py new file mode 100644 index 0000000000000000000000000000000000000000..f19f52ac900cd33c38500f184076c8422bcba81e --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/requests_oauthlib/oauth2_auth.py @@ -0,0 +1,36 @@ +from oauthlib.oauth2 import WebApplicationClient, InsecureTransportError +from oauthlib.oauth2 import is_secure_transport +from requests.auth import AuthBase + + +class OAuth2(AuthBase): + """Adds proof of authorization (OAuth2 token) to the request.""" + + def __init__(self, client_id=None, client=None, token=None): + """Construct a new OAuth 2 authorization object. + + :param client_id: Client id obtained during registration + :param client: :class:`oauthlib.oauth2.Client` to be used. Default is + WebApplicationClient which is useful for any + hosted application but not mobile or desktop. + :param token: Token dictionary, must include access_token + and token_type. + """ + self._client = client or WebApplicationClient(client_id, token=token) + if token: + for k, v in token.items(): + setattr(self._client, k, v) + + def __call__(self, r): + """Append an OAuth 2 token to the request. + + Note that currently HTTPS is required for all requests. There may be + a token type that allows for plain HTTP in the future and then this + should be updated to allow plain HTTP on a white list basis. + """ + if not is_secure_transport(r.url): + raise InsecureTransportError() + r.url, r.headers, r.body = self._client.add_token( + r.url, http_method=r.method, body=r.body, headers=r.headers + ) + return r diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/requests_oauthlib/oauth2_session.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/requests_oauthlib/oauth2_session.py new file mode 100644 index 0000000000000000000000000000000000000000..93cc4d7bbd2af7e74e1c8d79a805d3d5540b1a5d --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/requests_oauthlib/oauth2_session.py @@ -0,0 +1,587 @@ +import logging + +from oauthlib.common import generate_token, urldecode +from oauthlib.oauth2 import WebApplicationClient, InsecureTransportError +from oauthlib.oauth2 import LegacyApplicationClient +from oauthlib.oauth2 import TokenExpiredError, is_secure_transport +import requests + +log = logging.getLogger(__name__) + + +class TokenUpdated(Warning): + def __init__(self, token): + super(TokenUpdated, self).__init__() + self.token = token + + +class OAuth2Session(requests.Session): + """Versatile OAuth 2 extension to :class:`requests.Session`. + + Supports any grant type adhering to :class:`oauthlib.oauth2.Client` spec + including the four core OAuth 2 grants. + + Can be used to create authorization urls, fetch tokens and access protected + resources using the :class:`requests.Session` interface you are used to. + + - :class:`oauthlib.oauth2.WebApplicationClient` (default): Authorization Code Grant + - :class:`oauthlib.oauth2.MobileApplicationClient`: Implicit Grant + - :class:`oauthlib.oauth2.LegacyApplicationClient`: Password Credentials Grant + - :class:`oauthlib.oauth2.BackendApplicationClient`: Client Credentials Grant + + Note that the only time you will be using Implicit Grant from python is if + you are driving a user agent able to obtain URL fragments. + """ + + def __init__( + self, + client_id=None, + client=None, + auto_refresh_url=None, + auto_refresh_kwargs=None, + scope=None, + redirect_uri=None, + token=None, + state=None, + token_updater=None, + pkce=None, + **kwargs + ): + """Construct a new OAuth 2 client session. + + :param client_id: Client id obtained during registration + :param client: :class:`oauthlib.oauth2.Client` to be used. Default is + WebApplicationClient which is useful for any + hosted application but not mobile or desktop. + :param scope: List of scopes you wish to request access to + :param redirect_uri: Redirect URI you registered as callback + :param token: Token dictionary, must include access_token + and token_type. + :param state: State string used to prevent CSRF. This will be given + when creating the authorization url and must be supplied + when parsing the authorization response. + Can be either a string or a no argument callable. + :auto_refresh_url: Refresh token endpoint URL, must be HTTPS. Supply + this if you wish the client to automatically refresh + your access tokens. + :auto_refresh_kwargs: Extra arguments to pass to the refresh token + endpoint. + :token_updater: Method with one argument, token, to be used to update + your token database on automatic token refresh. If not + set a TokenUpdated warning will be raised when a token + has been refreshed. This warning will carry the token + in its token argument. + :param pkce: Set "S256" or "plain" to enable PKCE. Default is disabled. + :param kwargs: Arguments to pass to the Session constructor. + """ + super(OAuth2Session, self).__init__(**kwargs) + self._client = client or WebApplicationClient(client_id, token=token) + self.token = token or {} + self._scope = scope + self.redirect_uri = redirect_uri + self.state = state or generate_token + self._state = state + self.auto_refresh_url = auto_refresh_url + self.auto_refresh_kwargs = auto_refresh_kwargs or {} + self.token_updater = token_updater + self._pkce = pkce + + if self._pkce not in ["S256", "plain", None]: + raise AttributeError("Wrong value for {}(.., pkce={})".format(self.__class__, self._pkce)) + + # Ensure that requests doesn't do any automatic auth. See #278. + # The default behavior can be re-enabled by setting auth to None. + self.auth = lambda r: r + + # Allow customizations for non compliant providers through various + # hooks to adjust requests and responses. + self.compliance_hook = { + "access_token_response": set(), + "refresh_token_response": set(), + "protected_request": set(), + "refresh_token_request": set(), + "access_token_request": set(), + } + + @property + def scope(self): + """By default the scope from the client is used, except if overridden""" + if self._scope is not None: + return self._scope + elif self._client is not None: + return self._client.scope + else: + return None + + @scope.setter + def scope(self, scope): + self._scope = scope + + def new_state(self): + """Generates a state string to be used in authorizations.""" + try: + self._state = self.state() + log.debug("Generated new state %s.", self._state) + except TypeError: + self._state = self.state + log.debug("Re-using previously supplied state %s.", self._state) + return self._state + + @property + def client_id(self): + return getattr(self._client, "client_id", None) + + @client_id.setter + def client_id(self, value): + self._client.client_id = value + + @client_id.deleter + def client_id(self): + del self._client.client_id + + @property + def token(self): + return getattr(self._client, "token", None) + + @token.setter + def token(self, value): + self._client.token = value + self._client.populate_token_attributes(value) + + @property + def access_token(self): + return getattr(self._client, "access_token", None) + + @access_token.setter + def access_token(self, value): + self._client.access_token = value + + @access_token.deleter + def access_token(self): + del self._client.access_token + + @property + def authorized(self): + """Boolean that indicates whether this session has an OAuth token + or not. If `self.authorized` is True, you can reasonably expect + OAuth-protected requests to the resource to succeed. If + `self.authorized` is False, you need the user to go through the OAuth + authentication dance before OAuth-protected requests to the resource + will succeed. + """ + return bool(self.access_token) + + def authorization_url(self, url, state=None, **kwargs): + """Form an authorization URL. + + :param url: Authorization endpoint url, must be HTTPS. + :param state: An optional state string for CSRF protection. If not + given it will be generated for you. + :param kwargs: Extra parameters to include. + :return: authorization_url, state + """ + state = state or self.new_state() + if self._pkce: + self._code_verifier = self._client.create_code_verifier(43) + kwargs["code_challenge_method"] = self._pkce + kwargs["code_challenge"] = self._client.create_code_challenge( + code_verifier=self._code_verifier, + code_challenge_method=self._pkce + ) + return ( + self._client.prepare_request_uri( + url, + redirect_uri=self.redirect_uri, + scope=self.scope, + state=state, + **kwargs + ), + state, + ) + + def fetch_token( + self, + token_url, + code=None, + authorization_response=None, + body="", + auth=None, + username=None, + password=None, + method="POST", + force_querystring=False, + timeout=None, + headers=None, + verify=None, + proxies=None, + include_client_id=None, + client_secret=None, + cert=None, + **kwargs + ): + """Generic method for fetching an access token from the token endpoint. + + If you are using the MobileApplicationClient you will want to use + `token_from_fragment` instead of `fetch_token`. + + The current implementation enforces the RFC guidelines. + + :param token_url: Token endpoint URL, must use HTTPS. + :param code: Authorization code (used by WebApplicationClients). + :param authorization_response: Authorization response URL, the callback + URL of the request back to you. Used by + WebApplicationClients instead of code. + :param body: Optional application/x-www-form-urlencoded body to add the + include in the token request. Prefer kwargs over body. + :param auth: An auth tuple or method as accepted by `requests`. + :param username: Username required by LegacyApplicationClients to appear + in the request body. + :param password: Password required by LegacyApplicationClients to appear + in the request body. + :param method: The HTTP method used to make the request. Defaults + to POST, but may also be GET. Other methods should + be added as needed. + :param force_querystring: If True, force the request body to be sent + in the querystring instead. + :param timeout: Timeout of the request in seconds. + :param headers: Dict to default request headers with. + :param verify: Verify SSL certificate. + :param proxies: The `proxies` argument is passed onto `requests`. + :param include_client_id: Should the request body include the + `client_id` parameter. Default is `None`, + which will attempt to autodetect. This can be + forced to always include (True) or never + include (False). + :param client_secret: The `client_secret` paired to the `client_id`. + This is generally required unless provided in the + `auth` tuple. If the value is `None`, it will be + omitted from the request, however if the value is + an empty string, an empty string will be sent. + :param cert: Client certificate to send for OAuth 2.0 Mutual-TLS Client + Authentication (draft-ietf-oauth-mtls). Can either be the + path of a file containing the private key and certificate or + a tuple of two filenames for certificate and key. + :param kwargs: Extra parameters to include in the token request. + :return: A token dict + """ + if not is_secure_transport(token_url): + raise InsecureTransportError() + + if not code and authorization_response: + self._client.parse_request_uri_response( + authorization_response, state=self._state + ) + code = self._client.code + elif not code and isinstance(self._client, WebApplicationClient): + code = self._client.code + if not code: + raise ValueError( + "Please supply either code or " "authorization_response parameters." + ) + + if self._pkce: + if self._code_verifier is None: + raise ValueError( + "Code verifier is not found, authorization URL must be generated before" + ) + kwargs["code_verifier"] = self._code_verifier + + # Earlier versions of this library build an HTTPBasicAuth header out of + # `username` and `password`. The RFC states, however these attributes + # must be in the request body and not the header. + # If an upstream server is not spec compliant and requires them to + # appear as an Authorization header, supply an explicit `auth` header + # to this function. + # This check will allow for empty strings, but not `None`. + # + # References + # 4.3.2 - Resource Owner Password Credentials Grant + # https://tools.ietf.org/html/rfc6749#section-4.3.2 + + if isinstance(self._client, LegacyApplicationClient): + if username is None: + raise ValueError( + "`LegacyApplicationClient` requires both the " + "`username` and `password` parameters." + ) + if password is None: + raise ValueError( + "The required parameter `username` was supplied, " + "but `password` was not." + ) + + # merge username and password into kwargs for `prepare_request_body` + if username is not None: + kwargs["username"] = username + if password is not None: + kwargs["password"] = password + + # is an auth explicitly supplied? + if auth is not None: + # if we're dealing with the default of `include_client_id` (None): + # we will assume the `auth` argument is for an RFC compliant server + # and we should not send the `client_id` in the body. + # This approach allows us to still force the client_id by submitting + # `include_client_id=True` along with an `auth` object. + if include_client_id is None: + include_client_id = False + + # otherwise we may need to create an auth header + else: + # since we don't have an auth header, we MAY need to create one + # it is possible that we want to send the `client_id` in the body + # if so, `include_client_id` should be set to True + # otherwise, we will generate an auth header + if include_client_id is not True: + client_id = self.client_id + if client_id: + log.debug( + 'Encoding `client_id` "%s" with `client_secret` ' + "as Basic auth credentials.", + client_id, + ) + client_secret = client_secret if client_secret is not None else "" + auth = requests.auth.HTTPBasicAuth(client_id, client_secret) + + if include_client_id: + # this was pulled out of the params + # it needs to be passed into prepare_request_body + if client_secret is not None: + kwargs["client_secret"] = client_secret + + body = self._client.prepare_request_body( + code=code, + body=body, + redirect_uri=self.redirect_uri, + include_client_id=include_client_id, + **kwargs + ) + + headers = headers or { + "Accept": "application/json", + "Content-Type": "application/x-www-form-urlencoded", + } + self.token = {} + request_kwargs = {} + if method.upper() == "POST": + request_kwargs["params" if force_querystring else "data"] = dict( + urldecode(body) + ) + elif method.upper() == "GET": + request_kwargs["params"] = dict(urldecode(body)) + else: + raise ValueError("The method kwarg must be POST or GET.") + + for hook in self.compliance_hook["access_token_request"]: + log.debug("Invoking access_token_request hook %s.", hook) + token_url, headers, request_kwargs = hook( + token_url, headers, request_kwargs + ) + + r = self.request( + method=method, + url=token_url, + timeout=timeout, + headers=headers, + auth=auth, + verify=verify, + proxies=proxies, + cert=cert, + **request_kwargs + ) + + log.debug("Request to fetch token completed with status %s.", r.status_code) + log.debug("Request url was %s", r.request.url) + log.debug("Request headers were %s", r.request.headers) + log.debug("Request body was %s", r.request.body) + log.debug("Response headers were %s and content %s.", r.headers, r.text) + log.debug( + "Invoking %d token response hooks.", + len(self.compliance_hook["access_token_response"]), + ) + for hook in self.compliance_hook["access_token_response"]: + log.debug("Invoking hook %s.", hook) + r = hook(r) + + self._client.parse_request_body_response(r.text, scope=self.scope) + self.token = self._client.token + log.debug("Obtained token %s.", self.token) + return self.token + + def token_from_fragment(self, authorization_response): + """Parse token from the URI fragment, used by MobileApplicationClients. + + :param authorization_response: The full URL of the redirect back to you + :return: A token dict + """ + self._client.parse_request_uri_response( + authorization_response, state=self._state + ) + self.token = self._client.token + return self.token + + def refresh_token( + self, + token_url, + refresh_token=None, + body="", + auth=None, + timeout=None, + headers=None, + verify=None, + proxies=None, + **kwargs + ): + """Fetch a new access token using a refresh token. + + :param token_url: The token endpoint, must be HTTPS. + :param refresh_token: The refresh_token to use. + :param body: Optional application/x-www-form-urlencoded body to add the + include in the token request. Prefer kwargs over body. + :param auth: An auth tuple or method as accepted by `requests`. + :param timeout: Timeout of the request in seconds. + :param headers: A dict of headers to be used by `requests`. + :param verify: Verify SSL certificate. + :param proxies: The `proxies` argument will be passed to `requests`. + :param kwargs: Extra parameters to include in the token request. + :return: A token dict + """ + if not token_url: + raise ValueError("No token endpoint set for auto_refresh.") + + if not is_secure_transport(token_url): + raise InsecureTransportError() + + refresh_token = refresh_token or self.token.get("refresh_token") + + log.debug( + "Adding auto refresh key word arguments %s.", self.auto_refresh_kwargs + ) + kwargs.update(self.auto_refresh_kwargs) + body = self._client.prepare_refresh_body( + body=body, refresh_token=refresh_token, scope=self.scope, **kwargs + ) + log.debug("Prepared refresh token request body %s", body) + + if headers is None: + headers = { + "Accept": "application/json", + "Content-Type": ("application/x-www-form-urlencoded"), + } + + for hook in self.compliance_hook["refresh_token_request"]: + log.debug("Invoking refresh_token_request hook %s.", hook) + token_url, headers, body = hook(token_url, headers, body) + + r = self.post( + token_url, + data=dict(urldecode(body)), + auth=auth, + timeout=timeout, + headers=headers, + verify=verify, + withhold_token=True, + proxies=proxies, + ) + log.debug("Request to refresh token completed with status %s.", r.status_code) + log.debug("Response headers were %s and content %s.", r.headers, r.text) + log.debug( + "Invoking %d token response hooks.", + len(self.compliance_hook["refresh_token_response"]), + ) + for hook in self.compliance_hook["refresh_token_response"]: + log.debug("Invoking hook %s.", hook) + r = hook(r) + + self.token = self._client.parse_request_body_response(r.text, scope=self.scope) + if "refresh_token" not in self.token: + log.debug("No new refresh token given. Re-using old.") + self.token["refresh_token"] = refresh_token + return self.token + + def request( + self, + method, + url, + data=None, + headers=None, + withhold_token=False, + client_id=None, + client_secret=None, + files=None, + **kwargs + ): + """Intercept all requests and add the OAuth 2 token if present.""" + if not is_secure_transport(url): + raise InsecureTransportError() + if self.token and not withhold_token: + log.debug( + "Invoking %d protected resource request hooks.", + len(self.compliance_hook["protected_request"]), + ) + for hook in self.compliance_hook["protected_request"]: + log.debug("Invoking hook %s.", hook) + url, headers, data = hook(url, headers, data) + + log.debug("Adding token %s to request.", self.token) + try: + url, headers, data = self._client.add_token( + url, http_method=method, body=data, headers=headers + ) + # Attempt to retrieve and save new access token if expired + except TokenExpiredError: + if self.auto_refresh_url: + log.debug( + "Auto refresh is set, attempting to refresh at %s.", + self.auto_refresh_url, + ) + + # We mustn't pass auth twice. + auth = kwargs.pop("auth", None) + if client_id and client_secret and (auth is None): + log.debug( + 'Encoding client_id "%s" with client_secret as Basic auth credentials.', + client_id, + ) + auth = requests.auth.HTTPBasicAuth(client_id, client_secret) + token = self.refresh_token( + self.auto_refresh_url, auth=auth, **kwargs + ) + if self.token_updater: + log.debug( + "Updating token to %s using %s.", token, self.token_updater + ) + self.token_updater(token) + url, headers, data = self._client.add_token( + url, http_method=method, body=data, headers=headers + ) + else: + raise TokenUpdated(token) + else: + raise + + log.debug("Requesting url %s using method %s.", url, method) + log.debug("Supplying headers %s and data %s", headers, data) + log.debug("Passing through key word arguments %s.", kwargs) + return super(OAuth2Session, self).request( + method, url, headers=headers, data=data, files=files, **kwargs + ) + + def register_compliance_hook(self, hook_type, hook): + """Register a hook for request/response tweaking. + + Available hooks are: + access_token_response invoked before token parsing. + refresh_token_response invoked before refresh token parsing. + protected_request invoked before making a request. + access_token_request invoked before making a token fetch request. + refresh_token_request invoked before making a refresh request. + + If you find a new hook is needed please send a GitHub PR request + or open an issue. + """ + if hook_type not in self.compliance_hook: + raise ValueError( + "Hook type %s is not in %s.", hook_type, self.compliance_hook + ) + self.compliance_hook[hook_type].add(hook) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sacrebleu-2.6.0.dist-info/INSTALLER b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sacrebleu-2.6.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sacrebleu-2.6.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sacrebleu-2.6.0.dist-info/METADATA b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sacrebleu-2.6.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..5d4185bc907017e7231d55c634292138a6519c27 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sacrebleu-2.6.0.dist-info/METADATA @@ -0,0 +1,707 @@ +Metadata-Version: 2.4 +Name: sacrebleu +Version: 2.6.0 +Summary: Hassle-free computation of shareable, comparable, and reproducible BLEU, chrF, and TER scores +Author-email: Matt Post +Maintainer-email: Matt Post +License-Expression: Apache-2.0 +Project-URL: Repository, https://github.com/mjpost/sacrebleu +Keywords: machine translation,evaluation,NLP,natural language processing,computational linguistics +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Science/Research +Classifier: Topic :: Scientific/Engineering +Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence +Classifier: Topic :: Text Processing +Classifier: Operating System :: POSIX +Classifier: Operating System :: MacOS :: MacOS X +Classifier: Operating System :: Microsoft :: Windows +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Typing :: Typed +Requires-Python: >=3.9 +Description-Content-Type: text/markdown +License-File: LICENSE.txt +Requires-Dist: portalocker +Requires-Dist: regex +Requires-Dist: tabulate>=0.8.9 +Requires-Dist: numpy>=1.17 +Requires-Dist: colorama +Requires-Dist: lxml +Provides-Extra: dev +Requires-Dist: wheel; extra == "dev" +Requires-Dist: pytest; extra == "dev" +Requires-Dist: mypy; extra == "dev" +Requires-Dist: types-tabulate; extra == "dev" +Requires-Dist: lxml-stubs; extra == "dev" +Requires-Dist: setuptools; extra == "dev" +Provides-Extra: ja +Requires-Dist: mecab-python3<2.0.0,>=1.0.9; extra == "ja" +Requires-Dist: ipadic<2.0,>=1.0; extra == "ja" +Provides-Extra: ko +Requires-Dist: mecab-ko<2.0.0,>=1.0.2; extra == "ko" +Requires-Dist: mecab-ko-dic<2.0,>=1.0; extra == "ko" +Dynamic: license-file + +# sacreBLEU + +[![PyPI version](https://img.shields.io/pypi/v/sacrebleu)](https://img.shields.io/pypi/v/sacrebleu) +[![Python version](https://img.shields.io/pypi/pyversions/sacrebleu)](https://img.shields.io/pypi/pyversions/sacrebleu) +[![GitHub issues](https://img.shields.io/github/issues/mjpost/sacreBLEU.svg)](https://github.com/mjpost/sacrebleu/issues) + +SacreBLEU ([Post, 2018](http://aclweb.org/anthology/W18-6319)) provides hassle-free computation of shareable, comparable, and reproducible **BLEU** scores. +Inspired by Rico Sennrich's `multi-bleu-detok.perl`, it produces the official WMT scores but works with plain text. +It also knows all the standard test sets and handles downloading, processing, and tokenization for you. + +The official version is hosted at . + +# Motivation + +Comparing BLEU scores is harder than it should be. Every decoder has its own implementation, often borrowed from Moses, but maybe with subtle changes. +Moses itself has a number of implementations as standalone scripts, with little indication of how they differ (note: they mostly don't, but `multi-bleu.pl` expects tokenized input). Different flags passed to each of these scripts can produce wide swings in the final score. All of these may handle tokenization in different ways. On top of this, downloading and managing test sets is a moderate annoyance. + +Sacre bleu! What a mess. + +**SacreBLEU** aims to solve these problems by wrapping the original reference implementation ([Papineni et al., 2002](https://www.aclweb.org/anthology/P02-1040.pdf)) together with other useful features. +The defaults are set the way that BLEU should be computed, and furthermore, the script outputs a short version string that allows others to know exactly what you did. +As an added bonus, it automatically downloads and manages test sets for you, so that you can simply tell it to score against `wmt14`, without having to hunt down a path on your local file system. +It is all designed to take BLEU a little more seriously. +After all, even with all its problems, BLEU is the default and---admit it---well-loved metric of our entire research community. +Sacre BLEU. + +# Features + +- It automatically downloads common WMT test sets and processes them to plain text +- It produces a short version string that facilitates cross-paper comparisons +- It properly computes scores on detokenized outputs, using WMT ([Conference on Machine Translation](http://statmt.org/wmt17)) standard tokenization +- It produces the same values as the official script (`mteval-v13a.pl`) used by WMT +- It outputs the BLEU score without the comma, so you don't have to remove it with `sed` (Looking at you, `multi-bleu.perl`) +- It supports different tokenizers for BLEU including support for Japanese and Chinese +- It supports **chrF, chrF++** and **Translation error rate (TER)** metrics +- It performs paired bootstrap resampling and paired approximate randomization tests for statistical significance reporting + +# Breaking Changes + +## v2.0.0 + +As of v2.0.0, the default output format is changed to `json` for less painful parsing experience. This means that software that parse the output of sacreBLEU should be modified to either (i) parse the JSON using for example the `jq` utility or (ii) pass `-f text` to sacreBLEU to preserve the old textual output. The latter change can also be made **persistently** by exporting `SACREBLEU_FORMAT=text` in relevant shell configuration files. + +Here's an example of parsing the `score` key of the JSON output using `jq`: + +``` +$ sacrebleu -i output.detok.txt -t wmt17 -l en-de | jq -r .score +20.8 +``` + +# Installation + +Install the official Python module from PyPI (**Python>=3.9 only**): + + pip install sacrebleu + +In order to install Japanese tokenizer support through `mecab-python3`, you need to run the +following command instead, to perform a full installation with dependencies: + + pip install "sacrebleu[ja]" + +In order to install Korean tokenizer support through `pymecab-ko`, you need to run the +following command instead, to perform a full installation with dependencies: + + pip install "sacrebleu[ko]" + +# Command-line Usage + +You can get a list of available test sets with `sacrebleu --list`. Please see [DATASETS.md](DATASETS.md) +for an up-to-date list of supported datasets. You can also list available test sets for a given language pair +with `sacrebleu --list -l en-fr`. + +## Basics + +### Downloading test sets + +Downloading is triggered when you request a test set. If the dataset is not available, it is downloaded +and unpacked. + +E.g., you can use the following commands to download the source, pass it through your translation system +in `translate.sh`, and then score it: + +``` +$ sacrebleu -t wmt17 -l en-de --echo src > wmt17.en-de.en +$ cat wmt17.en-de.en | translate.sh | sacrebleu -t wmt17 -l en-de +``` + +Some test sets also have the outputs of systems that were submitted to the task. +For example, the `wmt/systems` test set. + +```bash +$ sacrebleu -t wmt21/systems -l zh-en --echo NiuTrans +``` + +This provides a convenient way to score: + +```bash +$ sacrebleu -t wmt21/system -l zh-en --echo NiuTrans | sacrebleu -t wmt21/systems -l zh-en +``` + +You can see a list of the available outputs by passing an invalid value to `--echo`. + +### JSON output + +As of version `>=2.0.0`, sacreBLEU prints the computed scores in JSON format to make parsing less painful: + +``` +$ sacrebleu -i output.detok.txt -t wmt17 -l en-de +``` + +```json +{ + "name": "BLEU", + "score": 20.8, + "signature": "nrefs:1|case:mixed|eff:no|tok:13a|smooth:exp|version:2.0.0", + "verbose_score": "54.4/26.6/14.9/8.7 (BP = 1.000 ratio = 1.026 hyp_len = 62880 ref_len = 61287)", + "nrefs": "1", + "case": "mixed", + "eff": "no", + "tok": "13a", + "smooth": "exp", + "version": "2.0.0" +} +``` + +If you want to keep the old behavior, you can pass `-f text` or export `SACREBLEU_FORMAT=text`: + +``` +$ sacrebleu -i output.detok.txt -t wmt17 -l en-de -f text +BLEU|nrefs:1|case:mixed|eff:no|tok:13a|smooth:exp|version:2.0.0 = 20.8 54.4/26.6/14.9/8.7 (BP = 1.000 ratio = 1.026 hyp_len = 62880 ref_len = 61287) +``` + +### Scoring + +(All examples below assume old-style text output for a compact representation that save space) + +Let's say that you just translated the `en-de` test set of WMT17 with your fancy MT system and the **detokenized** translations are in a file called `output.detok.txt`: + +``` +# Option 1: Redirect system output to STDIN +$ cat output.detok.txt | sacrebleu -t wmt17 -l en-de +BLEU|nrefs:1|case:mixed|eff:no|tok:13a|smooth:exp|version:2.0.0 = 20.8 54.4/26.6/14.9/8.7 (BP = 1.000 ratio = 1.026 hyp_len = 62880 ref_len = 61287) + +# Option 2: Use the --input/-i argument +$ sacrebleu -t wmt17 -l en-de -i output.detok.txt +BLEU|nrefs:1|case:mixed|eff:no|tok:13a|smooth:exp|version:2.0.0 = 20.8 54.4/26.6/14.9/8.7 (BP = 1.000 ratio = 1.026 hyp_len = 62880 ref_len = 61287) +``` + +You can obtain a short version of the signature with `--short/-sh`: + +``` +$ sacrebleu -t wmt17 -l en-de -i output.detok.txt -sh +BLEU|#:1|c:mixed|e:no|tok:13a|s:exp|v:2.0.0 = 20.8 54.4/26.6/14.9/8.7 (BP = 1.000 ratio = 1.026 hyp_len = 62880 ref_len = 61287) +``` + +If you only want the score to be printed, you can use the `--score-only/-b` flag: + +``` +$ sacrebleu -t wmt17 -l en-de -i output.detok.txt -b +20.8 +``` + +The precision of the scores can be configured via the `--width/-w` flag: + +``` +$ sacrebleu -t wmt17 -l en-de -i output.detok.txt -b -w 4 +20.7965 +``` + +### Using your own reference file + +SacreBLEU knows about common test sets (as detailed in the `--list` example above), but you can also use it to score system outputs with arbitrary references. In this case, do not forget to provide **detokenized** reference and hypotheses files: + +``` +# Let's save the reference to a text file +$ sacrebleu -t wmt17 -l en-de --echo ref > ref.detok.txt + +# Option 1: Pass the reference file as a positional argument to sacreBLEU +$ sacrebleu ref.detok.txt -i output.detok.txt -m bleu -b -w 4 +20.7965 + +# Option 2: Redirect the system into STDIN (Compatible with multi-bleu.perl way of doing things) +$ cat output.detok.txt | sacrebleu ref.detok.txt -m bleu -b -w 4 +20.7965 +``` + +### Using multiple metrics + +Let's first compute BLEU, chrF and TER with the default settings: + +``` +$ sacrebleu -t wmt17 -l en-de -i output.detok.txt -m bleu chrf ter + BLEU|nrefs:1|case:mixed|eff:no|tok:13a|smooth:exp|version:2.0.0 = 20.8 + chrF2|nrefs:1|case:mixed|eff:yes|nc:6|nw:0|space:no|version:2.0.0 = 52.0 +TER|nrefs:1|case:lc|tok:tercom|norm:no|punct:yes|asian:no|version:2.0.0 = 69.0 +``` + +Let's now enable `chrF++` which is a revised version of chrF that takes into account word n-grams. +Observe how the `nw:0` gets changed into `nw:2` in the signature: + +``` +$ sacrebleu -t wmt17 -l en-de -i output.detok.txt -m bleu chrf ter --chrf-word-order 2 + BLEU|nrefs:1|case:mixed|eff:no|tok:13a|smooth:exp|version:2.0.0 = 20.8 + chrF2++|nrefs:1|case:mixed|eff:yes|nc:6|nw:2|space:no|version:2.0.0 = 49.0 +TER|nrefs:1|case:lc|tok:tercom|norm:no|punct:yes|asian:no|version:2.0.0 = 69.0 +``` + +Metric-specific arguments are detailed in the output of `--help`: + +``` +BLEU related arguments: + --smooth-method {none,floor,add-k,exp}, -s {none,floor,add-k,exp} + Smoothing method: exponential decay, floor (increment zero counts), add-k (increment num/denom by k for n>1), or none. (Default: exp) + --smooth-value BLEU_SMOOTH_VALUE, -sv BLEU_SMOOTH_VALUE + The smoothing value. Only valid for floor and add-k. (Defaults: floor: 0.1, add-k: 1) + --tokenize {none,zh,13a,char,intl,ja-mecab,ko-mecab}, -tok {none,zh,13a,char,intl,ja-mecab,ko-mecab} + Tokenization method to use for BLEU. If not provided, defaults to `zh` for Chinese, `ja-mecab` for Japanese, `ko-mecab` for Korean and `13a` (mteval) otherwise. + --lowercase, -lc If True, enables case-insensitivity. (Default: False) + --force Insist that your tokenized input is actually detokenized. + +chrF related arguments: + --chrf-char-order CHRF_CHAR_ORDER, -cc CHRF_CHAR_ORDER + Character n-gram order. (Default: 6) + --chrf-word-order CHRF_WORD_ORDER, -cw CHRF_WORD_ORDER + Word n-gram order (Default: 0). If equals to 2, the metric is referred to as chrF++. + --chrf-beta CHRF_BETA + Determine the importance of recall w.r.t precision. (Default: 2) + --chrf-whitespace Include whitespaces when extracting character n-grams. (Default: False) + --chrf-lowercase Enable case-insensitivity. (Default: False) + --chrf-eps-smoothing Enables epsilon smoothing similar to chrF++.py, NLTK and Moses; instead of effective order smoothing. (Default: False) + +TER related arguments (The defaults replicate TERCOM's behavior): + --ter-case-sensitive Enables case sensitivity (Default: False) + --ter-asian-support Enables special treatment of Asian characters (Default: False) + --ter-no-punct Removes punctuation. (Default: False) + --ter-normalized Applies basic normalization and tokenization. (Default: False) +``` + +### Version Signatures +As you may have noticed, sacreBLEU generates version strings such as `BLEU|nrefs:1|case:mixed|eff:no|tok:13a|smooth:exp|version:2.0.0` for reproducibility reasons. It's strongly recommended to share these signatures in your papers! + +### Outputting other metadata + +Sacrebleu knows about metadata for some test sets, and you can output it like this: + +``` +$ sacrebleu -t wmt21 -l en-de --echo src docid ref | head 2 +Couple MACED at California dog park for not wearing face masks while having lunch (VIDEO) - RT USA News rt.com.131279 Paar in Hundepark in Kalifornien mit Pfefferspray besprüht, weil es beim Mittagessen keine Masken trug (VIDEO) - RT USA News +There's mask-shaming and then there's full on assault. rt.com.131279 Masken-Shaming ist eine Sache, Körperverletzung eine andere. +``` + +If multiple fields are requested, they are output as tab-separated columns (a TSV). + +To see the available fields, add `--echo asdf` (or some other garbage data): + +``` +$ sacrebleu -t wmt21 -l en-de --echo asdf +sacreBLEU: No such field asdf in test set wmt21 for language pair en-de. +sacreBLEU: available fields for wmt21/en-de: src, ref:A, ref, docid, origlang +``` + +## Translationese Support + +If you are interested in the translationese effect, you can evaluate BLEU on a subset of sentences +with a given original language (identified based on the `origlang` tag in the raw SGM files). +E.g., to evaluate only against originally German sentences translated to English use: + + $ sacrebleu -t wmt13 -l de-en --origlang=de -i my-wmt13-output.txt + +and to evaluate against the complement (in this case `origlang` en, fr, cs, ru, de) use: + + $ sacrebleu -t wmt13 -l de-en --origlang=non-de -i my-wmt13-output.txt + +**Please note** that the evaluator will return a BLEU score only on the requested subset, +but it expects that you pass through the entire translated test set. + +## Languages & Preprocessing + +### BLEU + +- You can compute case-insensitive BLEU by passing `--lowercase` to sacreBLEU +- The default tokenizer for BLEU is `13a` which mimics the `mteval-v13a` script from Moses. +- Other tokenizers are: + - `none` which will not apply any kind of tokenization at all + - `char` for language-agnostic character-level tokenization + - `intl` applies international tokenization and mimics the `mteval-v14` script from Moses + - `zh` separates out **Chinese** characters and tokenizes the non-Chinese parts using `13a` tokenizer + - `ja-mecab` tokenizes **Japanese** inputs using the [MeCab](https://pypi.org/project/mecab-python3) morphological analyzer + - `ko-mecab` tokenizes **Korean** inputs using the [MeCab-ko](https://pypi.org/project/mecab-ko) morphological analyzer + - `flores101` and `flores200` uses the SentencePiece model built from the Flores-101 and [Flores-200](https://github.com/facebookresearch/flores/blob/main/flores200/README.md#languages-in-flores-200) dataset, respectively. Note: the canonical .spm file will be automatically fetched if not found locally. + - 🔥🆕 `spBLEU-1K` is a newly introduced **multilingual** SentencePiece tokenizer, trained on **over 1,000** data sources, as proposed in the [Toucan](https://aclanthology.org/2024.findings-acl.781/) paper (ACL 2024). For more details, see spBLEU's [GitHub repository](https://github.com/UBC-NLP/Toucan/tree/main/spBLEU-1K). + + +- You can switch tokenizers using the `--tokenize` flag of sacreBLEU. Alternatively, if you provide language-pair strings + using `--language-pair/-l`, `zh`, `ja-mecab` and `ko-mecab` tokenizers will be used if the target language is `zh` or `ja` or `ko`, respectively. +- **Note that** there's no automatic language detection from the hypotheses so you need to make sure that you are correctly + selecting the tokenizer for **Japanese**, **Korean** and **Chinese**. + + +Default 13a tokenizer will produce poor results for Japanese: + +``` +$ sacrebleu kyoto-test.ref.ja -i kyoto-test.hyp.ja -b +2.1 +``` + +Let's use the `ja-mecab` tokenizer: +``` +$ sacrebleu kyoto-test.ref.ja -i kyoto-test.hyp.ja --tokenize ja-mecab -b +14.5 +``` + +If you provide the language-pair, sacreBLEU will use ja-mecab automatically: + +``` +$ sacrebleu kyoto-test.ref.ja -i kyoto-test.hyp.ja -l en-ja -b +14.5 +``` + +### chrF / chrF++ + +chrF applies minimum to none pre-processing as it deals with character n-grams: + +- If you pass `--chrf-whitespace`, whitespace characters will be preserved when computing character n-grams. +- If you pass `--chrf-lowercase`, sacreBLEU will compute case-insensitive chrF. +- If you enable non-zero `--chrf-word-order` (pass `2` for `chrF++`), a very simple punctuation tokenization will be internally applied. + + +### TER + +Translation Error Rate (TER) has its own special tokenizer that you can configure through the command line. +The defaults provided are **compatible with the upstream TER implementation (TERCOM)** but you can nevertheless modify the +behavior through the command-line: + +- TER is by default case-insensitive. Pass `--ter-case-sensitive` to enable case-sensitivity. +- Pass `--ter-normalize` to apply a general Western tokenization +- Pass `--ter-asian-support` to enable the tokenization of Asian characters. If provided with `--ter-normalize`, + both will be applied. +- Pass `--ter-no-punct` to strip punctuation. + +## Multi-reference Evaluation + +All three metrics support the use of multiple references during evaluation. Let's first pass all references as positional arguments: + +``` +$ sacrebleu ref1 ref2 -i system -m bleu chrf ter + BLEU|nrefs:2|case:mixed|eff:no|tok:13a|smooth:exp|version:2.0.0 = 61.8 + chrF2|nrefs:2|case:mixed|eff:yes|nc:6|nw:0|space:no|version:2.0.0 = 75.0 +TER|nrefs:2|case:lc|tok:tercom|norm:no|punct:yes|asian:no|version:2.0.0 = 31.2 +``` + +Alternatively (less recommended), we can concatenate references using tabs as delimiters as well. Don't forget to pass `--num-refs/-nr` in this case! + +``` +$ paste ref1 ref2 > refs.tsv + +$ sacrebleu refs.tsv --num-refs 2 -i system -m bleu +BLEU|nrefs:2|case:mixed|eff:no|tok:13a|smooth:exp|version:2.0.0 = 61.8 +``` + +## Multi-system Evaluation +As of version `>=2.0.0`, SacreBLEU supports evaluation of an arbitrary number of systems for a particular +test set and language-pair. This has the advantage of seeing all results in a +nicely formatted table. + +Let's pass all system output files that match the shell glob `newstest2017.online-*` to sacreBLEU for evaluation: + +``` +$ sacrebleu -t wmt17 -l en-de -i newstest2017.online-* -m bleu chrf +╒═══════════════════════════════╤════════╤═════════╕ +│ System │ BLEU │ chrF2 │ +╞═══════════════════════════════╪════════╪═════════╡ +│ newstest2017.online-A.0.en-de │ 20.8 │ 52.0 │ +├───────────────────────────────┼────────┼─────────┤ +│ newstest2017.online-B.0.en-de │ 26.7 │ 56.3 │ +├───────────────────────────────┼────────┼─────────┤ +│ newstest2017.online-F.0.en-de │ 15.5 │ 49.3 │ +├───────────────────────────────┼────────┼─────────┤ +│ newstest2017.online-G.0.en-de │ 18.2 │ 51.6 │ +╘═══════════════════════════════╧════════╧═════════╛ + +----------------- +Metric signatures +----------------- + - BLEU nrefs:1|case:mixed|eff:no|tok:13a|smooth:exp|version:2.0.0 + - chrF2 nrefs:1|case:mixed|eff:yes|nc:6|nw:0|space:no|version:2.0.0 +``` + +You can also change the output format to `latex`: + +``` +$ sacrebleu -t wmt17 -l en-de -i newstest2017.online-* -m bleu chrf -f latex +\begin{tabular}{rcc} +\toprule + System & BLEU & chrF2 \\ +\midrule + newstest2017.online-A.0.en-de & 20.8 & 52.0 \\ + newstest2017.online-B.0.en-de & 26.7 & 56.3 \\ + newstest2017.online-F.0.en-de & 15.5 & 49.3 \\ + newstest2017.online-G.0.en-de & 18.2 & 51.6 \\ +\bottomrule +\end{tabular} + +... +``` + +## Confidence Intervals for Single System Evaluation + +When enabled with the `--confidence` flag, SacreBLEU will print +(1) the actual system score, (2) the true mean estimated from bootstrap resampling and (3), +the 95% [confidence interval](https://en.wikipedia.org/wiki/Confidence_interval) around the mean. +By default, the number of bootstrap resamples is 1000 (`bs:1000` in the signature) +and can be changed with `--confidence-n`: + +``` +$ sacrebleu -t wmt17 -l en-de -i output.detok.txt -m bleu chrf --confidence -f text --short + BLEU|#:1|bs:1000|rs:12345|c:mixed|e:no|tok:13a|s:exp|v:2.0.0 = 22.675 (μ = 22.669 ± 0.598) ... +chrF2|#:1|bs:1000|rs:12345|c:mixed|e:yes|nc:6|nw:0|s:no|v:2.0.0 = 51.953 (μ = 51.953 ± 0.462) +``` + +**NOTE:** Although provided as a functionality, having access to confidence intervals for just one system +may not reveal much information about the underlying model. It often makes more sense to perform +**paired statistical tests** across multiple systems. + +**NOTE:** When resampling, the seed of the `numpy`'s random number generator (RNG) +is fixed to `12345`. If you want to relax this and set your own seed, you can +export the environment variable `SACREBLEU_SEED` to an integer. Alternatively, you can export +`SACREBLEU_SEED=None` to skip initializing the RNG's seed and allow for non-deterministic +behavior. + +## Paired Significance Tests for Multi System Evaluation +Ideally, one would have access to many systems in cases such as (1) investigating +whether a newly added feature yields significantly different scores than the baseline or +(2) evaluating submissions for a particular shared task. SacreBLEU offers two different paired significance tests that are widely used in MT research. + +### Paired bootstrap resampling (--paired-bs) + +This is an efficient implementation of the paper [Statistical Significance Tests for Machine Translation Evaluation](https://www.aclweb.org/anthology/W04-3250.pdf) and is result-compliant with the [reference Moses implementation](https://github.com/moses-smt/mosesdecoder/blob/master/scripts/analysis/bootstrap-hypothesis-difference-significance.pl). The number of bootstrap resamples can be changed with the `--paired-bs-n` flag and its default is 1000. + +When launched, paired bootstrap resampling will perform: + - Bootstrap resampling to estimate 95% CI for all systems and the baseline + - A significance test between the **baseline** and each **system** to compute a [p-value](https://en.wikipedia.org/wiki/P-value). + +### Paired approximate randomization (--paired-ar) + +Paired approximate randomization (AR) is another type of paired significance test that is claimed to be more accurate than paired bootstrap resampling when it comes to Type-I errors ([Riezler and Maxwell III, 2005](https://www.aclweb.org/anthology/W05-0908.pdf)). Type-I errors indicate failures to reject the null hypothesis when it is true. In other words, AR should in theory be more robust to subtle changes across systems. + +Our implementation is verified to be result-compliant with the [Multeval toolkit](https://github.com/jhclark/multeval) that also uses paired AR test for pairwise comparison. The number of approximate randomization trials is set to 10,000 by default. This can be changed with the `--paired-ar-n` flag. + +### Running the tests + +- The **first system** provided to `--input/-i` will be automatically taken as the **baseline system** against which you want to compare **other systems.** +- When `--input/-i` is used, the system output files will be automatically named according to the file paths. For the sake of simplicity, SacreBLEU will automatically discard the **baseline system** if it also appears amongst **other systems**. This is useful if you would like to run the tool by passing `-i systems/baseline.txt systems/*.txt`. Here, the `baseline.txt` file will not be also considered as a candidate system. +- Alternatively, you can also use a tab-separated input file redirected to SacreBLEU. In this case, the first column hypotheses will be taken as the **baseline system**. However, this method is **not recommended** as it won't allow naming your systems in a human-readable way. It will instead enumerate the systems from 1 to N following the column order in the tab-separated input. +- On Linux and Mac OS X, you can launch the tests on multiple CPU's by passing the flag `--paired-jobs N`. If `N == 0`, SacreBLEU will launch one worker for each pairwise comparison. If `N > 0`, `N` worker processes will be spawned. This feature will substantially speed up the runtime especially if you want the **TER** metric to be computed. + +#### Example: Paired bootstrap resampling +In the example below, we select `newstest2017.LIUM-NMT.4900.en-de` as the baseline and compare it to 4 other WMT17 submissions using paired bootstrap resampling. According to the results, the null hypothesis (i.e. the two systems being essentially the same) could not be rejected (at the significance level of 0.05) for the following comparisons: + +- 0.1 BLEU difference between the baseline and the online-B system (p = 0.3077) + +``` +$ sacrebleu -t wmt17 -l en-de -i newstest2017.LIUM-NMT.4900.en-de newstest2017.online-* -m bleu chrf --paired-bs +╒════════════════════════════════════════════╤═════════════════════╤══════════════════════╕ +│ System │ BLEU (μ ± 95% CI) │ chrF2 (μ ± 95% CI) │ +╞════════════════════════════════════════════╪═════════════════════╪══════════════════════╡ +│ Baseline: newstest2017.LIUM-NMT.4900.en-de │ 26.6 (26.6 ± 0.6) │ 55.9 (55.9 ± 0.5) │ +├────────────────────────────────────────────┼─────────────────────┼──────────────────────┤ +│ newstest2017.online-A.0.en-de │ 20.8 (20.8 ± 0.6) │ 52.0 (52.0 ± 0.4) │ +│ │ (p = 0.0010)* │ (p = 0.0010)* │ +├────────────────────────────────────────────┼─────────────────────┼──────────────────────┤ +│ newstest2017.online-B.0.en-de │ 26.7 (26.6 ± 0.7) │ 56.3 (56.3 ± 0.5) │ +│ │ (p = 0.3077) │ (p = 0.0240)* │ +├────────────────────────────────────────────┼─────────────────────┼──────────────────────┤ +│ newstest2017.online-F.0.en-de │ 15.5 (15.4 ± 0.5) │ 49.3 (49.3 ± 0.4) │ +│ │ (p = 0.0010)* │ (p = 0.0010)* │ +├────────────────────────────────────────────┼─────────────────────┼──────────────────────┤ +│ newstest2017.online-G.0.en-de │ 18.2 (18.2 ± 0.5) │ 51.6 (51.6 ± 0.4) │ +│ │ (p = 0.0010)* │ (p = 0.0010)* │ +╘════════════════════════════════════════════╧═════════════════════╧══════════════════════╛ + +------------------------------------------------------------ +Paired bootstrap resampling test with 1000 resampling trials +------------------------------------------------------------ + - Each system is pairwise compared to Baseline: newstest2017.LIUM-NMT.4900.en-de. + Actual system score / bootstrap estimated true mean / 95% CI are provided for each metric. + + - Null hypothesis: the system and the baseline translations are essentially + generated by the same underlying process. For a given system and the baseline, + the p-value is roughly the probability of the absolute score difference (delta) + or higher occurring due to chance, under the assumption that the null hypothesis is correct. + + - Assuming a significance threshold of 0.05, the null hypothesis can be rejected + for p-values < 0.05 (marked with "*"). This means that the delta is unlikely to be attributed + to chance, hence the system is significantly "different" than the baseline. + Otherwise, the p-values are highlighted in red. + + - NOTE: Significance does not tell whether a system is "better" than the baseline but rather + emphasizes the "difference" of the systems in terms of the replicability of the delta. + +----------------- +Metric signatures +----------------- + - BLEU nrefs:1|bs:1000|seed:12345|case:mixed|eff:no|tok:13a|smooth:exp|version:2.0.0 + - chrF2 nrefs:1|bs:1000|seed:12345|case:mixed|eff:yes|nc:6|nw:0|space:no|version:2.0.0 +``` + +#### Example: Paired approximate randomization + +Let's now run the paired approximate randomization test for the same comparison. According to the results, the findings are compatible with the paired bootstrap resampling test. However, the p-value for the `baseline vs. online-B` comparison is much higher (`0.8066`) than the paired bootstrap resampling test. + +(**Note that** the AR test does not provide confidence intervals around the true mean as it does not perform bootstrap resampling.) + +``` +$ sacrebleu -t wmt17 -l en-de -i newstest2017.LIUM-NMT.4900.en-de newstest2017.online-* -m bleu chrf --paired-ar +╒════════════════════════════════════════════╤═══════════════╤═══════════════╕ +│ System │ BLEU │ chrF2 │ +╞════════════════════════════════════════════╪═══════════════╪═══════════════╡ +│ Baseline: newstest2017.LIUM-NMT.4900.en-de │ 26.6 │ 55.9 │ +├────────────────────────────────────────────┼───────────────┼───────────────┤ +│ newstest2017.online-A.0.en-de │ 20.8 │ 52.0 │ +│ │ (p = 0.0001)* │ (p = 0.0001)* │ +├────────────────────────────────────────────┼───────────────┼───────────────┤ +│ newstest2017.online-B.0.en-de │ 26.7 │ 56.3 │ +│ │ (p = 0.8066) │ (p = 0.0385)* │ +├────────────────────────────────────────────┼───────────────┼───────────────┤ +│ newstest2017.online-F.0.en-de │ 15.5 │ 49.3 │ +│ │ (p = 0.0001)* │ (p = 0.0001)* │ +├────────────────────────────────────────────┼───────────────┼───────────────┤ +│ newstest2017.online-G.0.en-de │ 18.2 │ 51.6 │ +│ │ (p = 0.0001)* │ (p = 0.0001)* │ +╘════════════════════════════════════════════╧═══════════════╧═══════════════╛ + +------------------------------------------------------- +Paired approximate randomization test with 10000 trials +------------------------------------------------------- + - Each system is pairwise compared to Baseline: newstest2017.LIUM-NMT.4900.en-de. + Actual system score is provided for each metric. + + - Null hypothesis: the system and the baseline translations are essentially + generated by the same underlying process. For a given system and the baseline, + the p-value is roughly the probability of the absolute score difference (delta) + or higher occurring due to chance, under the assumption that the null hypothesis is correct. + + - Assuming a significance threshold of 0.05, the null hypothesis can be rejected + for p-values < 0.05 (marked with "*"). This means that the delta is unlikely to be attributed + to chance, hence the system is significantly "different" than the baseline. + Otherwise, the p-values are highlighted in red. + + - NOTE: Significance does not tell whether a system is "better" than the baseline but rather + emphasizes the "difference" of the systems in terms of the replicability of the delta. + +----------------- +Metric signatures +----------------- + - BLEU nrefs:1|ar:10000|seed:12345|case:mixed|eff:no|tok:13a|smooth:exp|version:2.0.0 + - chrF2 nrefs:1|ar:10000|seed:12345|case:mixed|eff:yes|nc:6|nw:0|space:no|version:2.0.0 +``` + +# Using SacreBLEU from Python + +For evaluation, it may be useful to compute BLEU, chrF or TER from a Python script. The recommended +way of doing this is to use the object-oriented API, by creating an instance of the `metrics.BLEU` class +for example: + +```python +In [1]: from sacrebleu.metrics import BLEU, CHRF, TER + ...: + ...: refs = [ # First set of references + ...: ['The dog bit the man.', 'It was not unexpected.', 'The man bit him first.'], + ...: # Second set of references + ...: ['The dog had bit the man.', 'No one was surprised.', 'The man had bitten the dog.'], + ...: ] + ...: sys = ['The dog bit the man.', "It wasn't surprising.", 'The man had just bitten him.'] + +In [2]: bleu = BLEU() + +In [3]: bleu.corpus_score(sys, refs) +Out[3]: BLEU = 48.53 82.4/50.0/45.5/37.5 (BP = 0.943 ratio = 0.944 hyp_len = 17 ref_len = 18) + +In [4]: bleu.get_signature() +Out[4]: nrefs:2|case:mixed|eff:no|tok:13a|smooth:exp|version:2.0.0 + +In [5]: chrf = CHRF() + +In [6]: chrf.corpus_score(sys, refs) +Out[6]: chrF2 = 59.73 +``` + +### Variable Number of References + +Let's now remove the first reference sentence for the first system sentence `The dog bit the man.` by replacing it with either `None` or the empty string `''`. +This allows using a variable number of reference segments per hypothesis. Observe how the signature changes from `nrefs:2` to `nrefs:var`: + +```python +In [1]: from sacrebleu.metrics import BLEU, CHRF, TER + ...: + ...: refs = [ # First set of references + # 1st sentence does not have a ref here + ...: ['', 'It was not unexpected.', 'The man bit him first.'], + ...: # Second set of references + ...: ['The dog had bit the man.', 'No one was surprised.', 'The man had bitten the dog.'], + ...: ] + ...: sys = ['The dog bit the man.', "It wasn't surprising.", 'The man had just bitten him.'] + +In [2]: bleu = BLEU() + +In [3]: bleu.corpus_score(sys, refs) +Out[3]: BLEU = 29.44 82.4/42.9/27.3/12.5 (BP = 0.889 ratio = 0.895 hyp_len = 17 ref_len = 19) + +In [4]: bleu.get_signature() +Out[4]: nrefs:var|case:mixed|eff:no|tok:13a|smooth:exp|version:2.0.0 +``` + +## Compatibility API + +You can also use the compatibility API that provides wrapper functions around the object-oriented API to +compute sentence-level and corpus-level BLEU, chrF and TER: (It should be noted that this API can be +removed in future releases) + +```python +In [1]: import sacrebleu + ...: + ...: refs = [ # First set of references + ...: ['The dog bit the man.', 'It was not unexpected.', 'The man bit him first.'], + ...: # Second set of references + ...: ['The dog had bit the man.', 'No one was surprised.', 'The man had bitten the dog.'], + ...: ] + ...: sys = ['The dog bit the man.', "It wasn't surprising.", 'The man had just bitten him.'] + +In [2]: sacrebleu.corpus_bleu(sys, refs) +Out[2]: BLEU = 48.53 82.4/50.0/45.5/37.5 (BP = 0.943 ratio = 0.944 hyp_len = 17 ref_len = 18) +``` + +# License + +SacreBLEU is licensed under the [Apache 2.0 License](LICENSE.txt). + +# Credits + +This was all [Rico Sennrich's idea](https://twitter.com/RicoSennrich/status/883246242763026433) +Originally written by Matt Post. +New features and ongoing support provided by Martin Popel (@martinpopel) and Ozan Caglayan (@ozancaglayan). + +If you use SacreBLEU, please cite the following: + +``` +@inproceedings{post-2018-call, + title = "A Call for Clarity in Reporting {BLEU} Scores", + author = "Post, Matt", + booktitle = "Proceedings of the Third Conference on Machine Translation: Research Papers", + month = oct, + year = "2018", + address = "Belgium, Brussels", + publisher = "Association for Computational Linguistics", + url = "https://www.aclweb.org/anthology/W18-6319", + pages = "186--191", +} +``` + +# Release Notes + +Please see [CHANGELOG.md](CHANGELOG.md) for release notes. diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sacrebleu-2.6.0.dist-info/RECORD b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sacrebleu-2.6.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..cebb8a9fb11db108472dce0ae5838aede656881a --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sacrebleu-2.6.0.dist-info/RECORD @@ -0,0 +1,77 @@ +../../../bin/sacrebleu,sha256=vajcXO7VtovP6vhWRoTm1BWBJVDSVtOEMT6CUjSDXLw,252 +sacrebleu-2.6.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +sacrebleu-2.6.0.dist-info/METADATA,sha256=0WmePGUUkncvx5mOm6ebh6gCv7PhYseM2nbYFeGYXGE,39183 +sacrebleu-2.6.0.dist-info/RECORD,, +sacrebleu-2.6.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91 +sacrebleu-2.6.0.dist-info/entry_points.txt,sha256=oacOmm24wUB3Xd7hB1dBABMzlZh9ReRJRNhaKu1fDlw,55 +sacrebleu-2.6.0.dist-info/licenses/LICENSE.txt,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357 +sacrebleu-2.6.0.dist-info/top_level.txt,sha256=H3cpHXPQtQtVbKIwDN8Au2t8nwrTQlA9omGuoF7tJOA,10 +sacrebleu/__init__.py,sha256=iQwhJhBOCWnzqzmctILrRPMWMFidtZSVgbwLKj6sCnY,1772 +sacrebleu/__main__.py,sha256=Eim2Tft9Xcoh5PJ4n23mVnpP36UmecOtCAH1Upl5kao,1062 +sacrebleu/__pycache__/__init__.cpython-310.pyc,, +sacrebleu/__pycache__/__main__.cpython-310.pyc,, +sacrebleu/__pycache__/compat.cpython-310.pyc,, +sacrebleu/__pycache__/sacrebleu.cpython-310.pyc,, +sacrebleu/__pycache__/significance.cpython-310.pyc,, +sacrebleu/__pycache__/utils.cpython-310.pyc,, +sacrebleu/__pycache__/version.cpython-310.pyc,, +sacrebleu/compat.py,sha256=rq8s6SgH9xgBc2uK6JXoH0HWZ6CbcpP_4_X66nQhyCs,9100 +sacrebleu/dataset/__init__.py,sha256=H1tYij9C71Snjm4JgM9x0gA2AZSSeguGQbsnUsKbL0w,107104 +sacrebleu/dataset/__main__.py,sha256=4zJ7F7mtk2LKCGorTJe0YCtZ0al5lvrJNMrfrxl3_OQ,1250 +sacrebleu/dataset/__pycache__/__init__.cpython-310.pyc,, +sacrebleu/dataset/__pycache__/__main__.cpython-310.pyc,, +sacrebleu/dataset/__pycache__/base.cpython-310.pyc,, +sacrebleu/dataset/__pycache__/fake_sgml.cpython-310.pyc,, +sacrebleu/dataset/__pycache__/iwslt_xml.cpython-310.pyc,, +sacrebleu/dataset/__pycache__/plain_text.cpython-310.pyc,, +sacrebleu/dataset/__pycache__/tsv.cpython-310.pyc,, +sacrebleu/dataset/__pycache__/wmt_xml.cpython-310.pyc,, +sacrebleu/dataset/base.py,sha256=TZGsir4PvdcO8YF_MWevd3Qb95ycQB2rvtAOkYIR0XM,6724 +sacrebleu/dataset/fake_sgml.py,sha256=SW00xrlhdc9Sr9Z8Q7RF8mXVuLo3s1aNLC-zu3Crevo,4098 +sacrebleu/dataset/iwslt_xml.py,sha256=nAwIXBfbcQLbbI3Eoe2DqdjGfD1V-429_qrwuZZqmj0,210 +sacrebleu/dataset/plain_text.py,sha256=AKYCHFRtVLCoFod5pKBrqvKRxYmkqoPwUpcPup1Jg_8,1237 +sacrebleu/dataset/tsv.py,sha256=m__O5lc8GmPvKl_901bndLAOuh9a1fK1koHOKWX6h90,2179 +sacrebleu/dataset/wmt_xml.py,sha256=DHoE6Qqajgemst-nForyCNzQ-vkvSUxsTutrBbJcIYY,7914 +sacrebleu/metrics/__init__.py,sha256=MzC5hSbprlwwvbeu6_6_FOz3L7c1KvtBkmkgOaGVTDk,260 +sacrebleu/metrics/__pycache__/__init__.cpython-310.pyc,, +sacrebleu/metrics/__pycache__/base.cpython-310.pyc,, +sacrebleu/metrics/__pycache__/bleu.cpython-310.pyc,, +sacrebleu/metrics/__pycache__/chrf.cpython-310.pyc,, +sacrebleu/metrics/__pycache__/helpers.cpython-310.pyc,, +sacrebleu/metrics/__pycache__/lib_ter.cpython-310.pyc,, +sacrebleu/metrics/__pycache__/ter.cpython-310.pyc,, +sacrebleu/metrics/base.py,sha256=7Q4yjpocwhU2WLGOKfna_V2wgImjN74HcRwx4ikKvxY,16646 +sacrebleu/metrics/bleu.py,sha256=jSJ7pEcNzxOC6YP8YV4bukHj0_Ghfn2MPQ0woMI_RgY,17577 +sacrebleu/metrics/chrf.py,sha256=lhkOB3nwuSOvsub17Mct9gQ0oR038gEj5vj-1IFQhXU,10674 +sacrebleu/metrics/helpers.py,sha256=VWngO3F_9gUa4uQFH1WJm4xZqpq3CLYeAWEOeMuECx4,2339 +sacrebleu/metrics/lib_ter.py,sha256=OBJjJHmDBzq_supZW68Vma-tkSVy1tibSLw_R093ncE,16477 +sacrebleu/metrics/ter.py,sha256=TuS52VLjayllPf-EB6-8Sf7EdkIGdJ0L1QfXzCSOcBo,7769 +sacrebleu/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sacrebleu/sacrebleu.py,sha256=NWidL0mxu3yA899edlFJPmSUmf243zEhiApXM4164d8,28462 +sacrebleu/significance.py,sha256=PDO7mCu5zL-7XNc9tA7QKs0C3TkcfrJgbKqYXwnXTp4,18329 +sacrebleu/tokenizers/__init__.py,sha256=V1unPdEJPrfDKNDYR1VSLu1bXCX0Fr8Uu8y9pNcZXGA,89 +sacrebleu/tokenizers/__pycache__/__init__.cpython-310.pyc,, +sacrebleu/tokenizers/__pycache__/tokenizer_13a.cpython-310.pyc,, +sacrebleu/tokenizers/__pycache__/tokenizer_base.cpython-310.pyc,, +sacrebleu/tokenizers/__pycache__/tokenizer_char.cpython-310.pyc,, +sacrebleu/tokenizers/__pycache__/tokenizer_intl.cpython-310.pyc,, +sacrebleu/tokenizers/__pycache__/tokenizer_ja_mecab.cpython-310.pyc,, +sacrebleu/tokenizers/__pycache__/tokenizer_ko_mecab.cpython-310.pyc,, +sacrebleu/tokenizers/__pycache__/tokenizer_none.cpython-310.pyc,, +sacrebleu/tokenizers/__pycache__/tokenizer_re.cpython-310.pyc,, +sacrebleu/tokenizers/__pycache__/tokenizer_spm.cpython-310.pyc,, +sacrebleu/tokenizers/__pycache__/tokenizer_ter.cpython-310.pyc,, +sacrebleu/tokenizers/__pycache__/tokenizer_zh.cpython-310.pyc,, +sacrebleu/tokenizers/tokenizer_13a.py,sha256=_1ClpQPIGqRj6uaklsFegAvSZUtlbE-yztmr51dLirU,985 +sacrebleu/tokenizers/tokenizer_base.py,sha256=YNvqL3oW3rsCtUbMNat6RhlYSn2VlZuPHgYHBj6jfJg,461 +sacrebleu/tokenizers/tokenizer_char.py,sha256=ubPsBjzNXqFPJ7WEpHQ2XD2ZWWqPgeOli9ErHOxmjTw,458 +sacrebleu/tokenizers/tokenizer_intl.py,sha256=EGayKRqqcY6oV-Zstah4mrYw979W5jK0AWK8Uo3C55Q,1869 +sacrebleu/tokenizers/tokenizer_ja_mecab.py,sha256=WYHc7xtAruICGfe-D6RYmnyrXxrlHlyNXVqQVs-6l1o,1420 +sacrebleu/tokenizers/tokenizer_ko_mecab.py,sha256=BWTEkHp8d2dJOAmlqdBtLt2MHJtpOdM78CWztQ-qS00,1455 +sacrebleu/tokenizers/tokenizer_none.py,sha256=0VX-qoUM3HzuLpF59L-gHjNgmoXXXpco23zYJtwmEmw,236 +sacrebleu/tokenizers/tokenizer_re.py,sha256=OGck3pPhwibf48Dssy-6cZObsHNetwb3IIJnUYGRiAg,1271 +sacrebleu/tokenizers/tokenizer_spm.py,sha256=LK7D0OjpysaCnTHIJBPgjetf-E_epNpTXG-eNsuSs78,2456 +sacrebleu/tokenizers/tokenizer_ter.py,sha256=37KPsx0jwsSZsqZ7UJKWAYyttvqS11SxzkHZIjrZBdA,6219 +sacrebleu/tokenizers/tokenizer_zh.py,sha256=GmBe3E29uECf61dFsR_qAHNzATEkgwwp0XAqb8de9wU,4724 +sacrebleu/utils.py,sha256=k9sfKYP2wuVluw7Re02JNtbCCIjaSxriRHttTwnLyMY,24646 +sacrebleu/version.py,sha256=2GXF52IIutfiInnoWGItHWB6xM45HGVQYJ3J77-iUV0,704 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sacrebleu-2.6.0.dist-info/WHEEL b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sacrebleu-2.6.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..e7fa31b6f3f78deb1022c1f7927f07d4d16da822 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sacrebleu-2.6.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sacrebleu-2.6.0.dist-info/entry_points.txt b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sacrebleu-2.6.0.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..07aad66d59eabe4a30481d4fe36ace4e1c17e234 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sacrebleu-2.6.0.dist-info/entry_points.txt @@ -0,0 +1,2 @@ +[console_scripts] +sacrebleu = sacrebleu.sacrebleu:main diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sacrebleu-2.6.0.dist-info/top_level.txt b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sacrebleu-2.6.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..454a21c03558b3210da0efe42581688e9cfc4b1d --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sacrebleu-2.6.0.dist-info/top_level.txt @@ -0,0 +1 @@ +sacrebleu diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools-79.0.1.dist-info/INSTALLER b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools-79.0.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools-79.0.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools-79.0.1.dist-info/METADATA b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools-79.0.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..8d42d121a54e13da648db704b2ba36b2d7d54108 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools-79.0.1.dist-info/METADATA @@ -0,0 +1,140 @@ +Metadata-Version: 2.4 +Name: setuptools +Version: 79.0.1 +Summary: Easily download, build, install, upgrade, and uninstall Python packages +Author-email: Python Packaging Authority +Project-URL: Source, https://github.com/pypa/setuptools +Project-URL: Documentation, https://setuptools.pypa.io/ +Project-URL: Changelog, https://setuptools.pypa.io/en/stable/history.html +Keywords: CPAN PyPI distutils eggs package management +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Topic :: System :: Archiving :: Packaging +Classifier: Topic :: System :: Systems Administration +Classifier: Topic :: Utilities +Requires-Python: >=3.9 +Description-Content-Type: text/x-rst +License-File: LICENSE +Provides-Extra: test +Requires-Dist: pytest!=8.1.*,>=6; extra == "test" +Requires-Dist: virtualenv>=13.0.0; extra == "test" +Requires-Dist: wheel>=0.44.0; extra == "test" +Requires-Dist: pip>=19.1; extra == "test" +Requires-Dist: packaging>=24.2; extra == "test" +Requires-Dist: jaraco.envs>=2.2; extra == "test" +Requires-Dist: pytest-xdist>=3; extra == "test" +Requires-Dist: jaraco.path>=3.7.2; extra == "test" +Requires-Dist: build[virtualenv]>=1.0.3; extra == "test" +Requires-Dist: filelock>=3.4.0; extra == "test" +Requires-Dist: ini2toml[lite]>=0.14; extra == "test" +Requires-Dist: tomli-w>=1.0.0; extra == "test" +Requires-Dist: pytest-timeout; extra == "test" +Requires-Dist: pytest-perf; sys_platform != "cygwin" and extra == "test" +Requires-Dist: jaraco.develop>=7.21; (python_version >= "3.9" and sys_platform != "cygwin") and extra == "test" +Requires-Dist: pytest-home>=0.5; extra == "test" +Requires-Dist: pytest-subprocess; extra == "test" +Requires-Dist: pyproject-hooks!=1.1; extra == "test" +Requires-Dist: jaraco.test>=5.5; extra == "test" +Provides-Extra: doc +Requires-Dist: sphinx>=3.5; extra == "doc" +Requires-Dist: jaraco.packaging>=9.3; extra == "doc" +Requires-Dist: rst.linker>=1.9; extra == "doc" +Requires-Dist: furo; extra == "doc" +Requires-Dist: sphinx-lint; extra == "doc" +Requires-Dist: jaraco.tidelift>=1.4; extra == "doc" +Requires-Dist: pygments-github-lexers==0.0.5; extra == "doc" +Requires-Dist: sphinx-favicon; extra == "doc" +Requires-Dist: sphinx-inline-tabs; extra == "doc" +Requires-Dist: sphinx-reredirects; extra == "doc" +Requires-Dist: sphinxcontrib-towncrier; extra == "doc" +Requires-Dist: sphinx-notfound-page<2,>=1; extra == "doc" +Requires-Dist: pyproject-hooks!=1.1; extra == "doc" +Requires-Dist: towncrier<24.7; extra == "doc" +Provides-Extra: ssl +Provides-Extra: certs +Provides-Extra: core +Requires-Dist: packaging>=24.2; extra == "core" +Requires-Dist: more_itertools>=8.8; extra == "core" +Requires-Dist: jaraco.text>=3.7; extra == "core" +Requires-Dist: importlib_metadata>=6; python_version < "3.10" and extra == "core" +Requires-Dist: tomli>=2.0.1; python_version < "3.11" and extra == "core" +Requires-Dist: wheel>=0.43.0; extra == "core" +Requires-Dist: platformdirs>=4.2.2; extra == "core" +Requires-Dist: jaraco.functools>=4; extra == "core" +Requires-Dist: more_itertools; extra == "core" +Provides-Extra: check +Requires-Dist: pytest-checkdocs>=2.4; extra == "check" +Requires-Dist: pytest-ruff>=0.2.1; sys_platform != "cygwin" and extra == "check" +Requires-Dist: ruff>=0.8.0; sys_platform != "cygwin" and extra == "check" +Provides-Extra: cover +Requires-Dist: pytest-cov; extra == "cover" +Provides-Extra: enabler +Requires-Dist: pytest-enabler>=2.2; extra == "enabler" +Provides-Extra: type +Requires-Dist: pytest-mypy; extra == "type" +Requires-Dist: mypy==1.14.*; extra == "type" +Requires-Dist: importlib_metadata>=7.0.2; python_version < "3.10" and extra == "type" +Requires-Dist: jaraco.develop>=7.21; sys_platform != "cygwin" and extra == "type" +Dynamic: license-file + +.. |pypi-version| image:: https://img.shields.io/pypi/v/setuptools.svg + :target: https://pypi.org/project/setuptools + +.. |py-version| image:: https://img.shields.io/pypi/pyversions/setuptools.svg + +.. |test-badge| image:: https://github.com/pypa/setuptools/actions/workflows/main.yml/badge.svg + :target: https://github.com/pypa/setuptools/actions?query=workflow%3A%22tests%22 + :alt: tests + +.. |ruff-badge| image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v2.json + :target: https://github.com/astral-sh/ruff + :alt: Ruff + +.. |docs-badge| image:: https://img.shields.io/readthedocs/setuptools/latest.svg + :target: https://setuptools.pypa.io + +.. |skeleton-badge| image:: https://img.shields.io/badge/skeleton-2025-informational + :target: https://blog.jaraco.com/skeleton + +.. |codecov-badge| image:: https://img.shields.io/codecov/c/github/pypa/setuptools/master.svg?logo=codecov&logoColor=white + :target: https://codecov.io/gh/pypa/setuptools + +.. |tidelift-badge| image:: https://tidelift.com/badges/github/pypa/setuptools?style=flat + :target: https://tidelift.com/subscription/pkg/pypi-setuptools?utm_source=pypi-setuptools&utm_medium=readme + +.. |discord-badge| image:: https://img.shields.io/discord/803025117553754132 + :target: https://discord.com/channels/803025117553754132/815945031150993468 + :alt: Discord + +|pypi-version| |py-version| |test-badge| |ruff-badge| |docs-badge| |skeleton-badge| |codecov-badge| |discord-badge| + +See the `Quickstart `_ +and the `User's Guide `_ for +instructions on how to use Setuptools. + +Questions and comments should be directed to `GitHub Discussions +`_. +Bug reports and especially tested patches may be +submitted directly to the `bug tracker +`_. + + +Code of Conduct +=============== + +Everyone interacting in the setuptools project's codebases, issue trackers, +chat rooms, and fora is expected to follow the +`PSF Code of Conduct `_. + + +For Enterprise +============== + +Available as part of the Tidelift Subscription. + +Setuptools and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use. + +`Learn more `_. diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools-79.0.1.dist-info/RECORD b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools-79.0.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..9da9449c793481ea5f315bbc27c54510b88a1b4d --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools-79.0.1.dist-info/RECORD @@ -0,0 +1,873 @@ +_distutils_hack/__init__.py,sha256=34HmvLo07j45Uvd2VR-2aRQ7lJD91sTK6zJgn5fphbQ,6755 +_distutils_hack/__pycache__/__init__.cpython-310.pyc,, +_distutils_hack/__pycache__/override.cpython-310.pyc,, +_distutils_hack/override.py,sha256=Eu_s-NF6VIZ4Cqd0tbbA5wtWky2IZPNd8et6GLt1mzo,44 +distutils-precedence.pth,sha256=JjjOniUA5XKl4N5_rtZmHrVp0baW_LoHsN0iPaX10iQ,151 +pkg_resources/__init__.py,sha256=-rh7XOnTxdGuC-_9FAyu5D6s8BL1UsBehxUtj7a-IVo,126203 +pkg_resources/__pycache__/__init__.cpython-310.pyc,, +pkg_resources/api_tests.txt,sha256=XEdvy4igHHrq2qNHNMHnlfO6XSQKNqOyLHbl6QcpfAI,12595 +pkg_resources/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pkg_resources/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pkg_resources/tests/__pycache__/__init__.cpython-310.pyc,, +pkg_resources/tests/__pycache__/test_find_distributions.cpython-310.pyc,, +pkg_resources/tests/__pycache__/test_integration_zope_interface.cpython-310.pyc,, +pkg_resources/tests/__pycache__/test_markers.cpython-310.pyc,, +pkg_resources/tests/__pycache__/test_pkg_resources.cpython-310.pyc,, +pkg_resources/tests/__pycache__/test_resources.cpython-310.pyc,, +pkg_resources/tests/__pycache__/test_working_set.cpython-310.pyc,, +pkg_resources/tests/data/my-test-package-source/__pycache__/setup.cpython-310.pyc,, +pkg_resources/tests/data/my-test-package-source/setup.cfg,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pkg_resources/tests/data/my-test-package-source/setup.py,sha256=1VobhAZbMb7M9mfhb_NE8PwDsvukoWLs9aUAS0pYhe8,105 +pkg_resources/tests/data/my-test-package-zip/my-test-package.zip,sha256=AYRcQ39GVePPnMT8TknP1gdDHyJnXhthESmpAjnzSCI,1809 +pkg_resources/tests/data/my-test-package_unpacked-egg/my_test_package-1.0-py3.7.egg/EGG-INFO/PKG-INFO,sha256=JvWv9Io2PAuYwEEw2fBW4Qc5YvdbkscpKX1kmLzsoHk,187 +pkg_resources/tests/data/my-test-package_unpacked-egg/my_test_package-1.0-py3.7.egg/EGG-INFO/SOURCES.txt,sha256=4ClkH8eTovZrdVrJFsVuxdbMEF--lBVSuKonDAPE5Jc,208 +pkg_resources/tests/data/my-test-package_unpacked-egg/my_test_package-1.0-py3.7.egg/EGG-INFO/dependency_links.txt,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1 +pkg_resources/tests/data/my-test-package_unpacked-egg/my_test_package-1.0-py3.7.egg/EGG-INFO/top_level.txt,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1 +pkg_resources/tests/data/my-test-package_unpacked-egg/my_test_package-1.0-py3.7.egg/EGG-INFO/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1 +pkg_resources/tests/data/my-test-package_zipped-egg/my_test_package-1.0-py3.7.egg,sha256=ZTlMGxjRGiKDNkiA2c75jbQH2TWIteP00irF9gvczbo,843 +pkg_resources/tests/test_find_distributions.py,sha256=U91cov5L1COAIWLNq3Xy4plU7_MnOE1WtXMu6iV2waM,1972 +pkg_resources/tests/test_integration_zope_interface.py,sha256=nzVoK557KZQN0V3DIQ1sVeaCOgt4Kpl-CODAWsO7pmc,1652 +pkg_resources/tests/test_markers.py,sha256=0orKg7UMDf7fnuNQvRMOc-EF9EAP_JTQnk4mtGgbW50,241 +pkg_resources/tests/test_pkg_resources.py,sha256=5Mt4bJQhLCL8j8cC46Uv32Np2Xc1TTxLGawIfET55Fk,17111 +pkg_resources/tests/test_resources.py,sha256=K0LqMAUGpRQ9pUb9K0vyI7GesvtlQvTH074m-E2VQlo,31252 +pkg_resources/tests/test_working_set.py,sha256=lRtGJWIixSwSMSbjHgRxeJEQiLMRXcz3xzJL2qL7eXY,8602 +setuptools-79.0.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +setuptools-79.0.1.dist-info/METADATA,sha256=0xUsrrFIbRQ7MLHUH_-q3bfqlf3JVHrhE1zml7GkILU,6548 +setuptools-79.0.1.dist-info/RECORD,, +setuptools-79.0.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools-79.0.1.dist-info/WHEEL,sha256=SmOxYU7pzNKBqASvQJ7DjX3XGUF92lrGhMb3R6_iiqI,91 +setuptools-79.0.1.dist-info/entry_points.txt,sha256=zkgthpf_Fa9NVE9p6FKT3Xk9DR1faAcRU4coggsV7jA,2449 +setuptools-79.0.1.dist-info/licenses/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023 +setuptools-79.0.1.dist-info/top_level.txt,sha256=d9yL39v_W7qmKDDSH6sT4bE0j_Ls1M3P161OGgdsm4g,41 +setuptools/__init__.py,sha256=AQsMeRFWz9CQ9aBtcSkbB4Dn8t2w86-GPriklpoAjew,10406 +setuptools/__pycache__/__init__.cpython-310.pyc,, +setuptools/__pycache__/_core_metadata.cpython-310.pyc,, +setuptools/__pycache__/_entry_points.cpython-310.pyc,, +setuptools/__pycache__/_imp.cpython-310.pyc,, +setuptools/__pycache__/_importlib.cpython-310.pyc,, +setuptools/__pycache__/_itertools.cpython-310.pyc,, +setuptools/__pycache__/_normalization.cpython-310.pyc,, +setuptools/__pycache__/_path.cpython-310.pyc,, +setuptools/__pycache__/_reqs.cpython-310.pyc,, +setuptools/__pycache__/_shutil.cpython-310.pyc,, +setuptools/__pycache__/_static.cpython-310.pyc,, +setuptools/__pycache__/archive_util.cpython-310.pyc,, +setuptools/__pycache__/build_meta.cpython-310.pyc,, +setuptools/__pycache__/depends.cpython-310.pyc,, +setuptools/__pycache__/discovery.cpython-310.pyc,, +setuptools/__pycache__/dist.cpython-310.pyc,, +setuptools/__pycache__/errors.cpython-310.pyc,, +setuptools/__pycache__/extension.cpython-310.pyc,, +setuptools/__pycache__/glob.cpython-310.pyc,, +setuptools/__pycache__/installer.cpython-310.pyc,, +setuptools/__pycache__/launch.cpython-310.pyc,, +setuptools/__pycache__/logging.cpython-310.pyc,, +setuptools/__pycache__/modified.cpython-310.pyc,, +setuptools/__pycache__/monkey.cpython-310.pyc,, +setuptools/__pycache__/msvc.cpython-310.pyc,, +setuptools/__pycache__/namespaces.cpython-310.pyc,, +setuptools/__pycache__/package_index.cpython-310.pyc,, +setuptools/__pycache__/sandbox.cpython-310.pyc,, +setuptools/__pycache__/unicode_utils.cpython-310.pyc,, +setuptools/__pycache__/version.cpython-310.pyc,, +setuptools/__pycache__/warnings.cpython-310.pyc,, +setuptools/__pycache__/wheel.cpython-310.pyc,, +setuptools/__pycache__/windows_support.cpython-310.pyc,, +setuptools/_core_metadata.py,sha256=T7Tjp-WSoN881adev3R1wzXCPnkDHqbC2MgylN1yjS8,11978 +setuptools/_distutils/__init__.py,sha256=xGYuhWwLG07J0Q49BVnEjPy6wyDcd6veJMDJX7ljlyM,359 +setuptools/_distutils/__pycache__/__init__.cpython-310.pyc,, +setuptools/_distutils/__pycache__/_log.cpython-310.pyc,, +setuptools/_distutils/__pycache__/_macos_compat.cpython-310.pyc,, +setuptools/_distutils/__pycache__/_modified.cpython-310.pyc,, +setuptools/_distutils/__pycache__/_msvccompiler.cpython-310.pyc,, +setuptools/_distutils/__pycache__/archive_util.cpython-310.pyc,, +setuptools/_distutils/__pycache__/ccompiler.cpython-310.pyc,, +setuptools/_distutils/__pycache__/cmd.cpython-310.pyc,, +setuptools/_distutils/__pycache__/core.cpython-310.pyc,, +setuptools/_distutils/__pycache__/cygwinccompiler.cpython-310.pyc,, +setuptools/_distutils/__pycache__/debug.cpython-310.pyc,, +setuptools/_distutils/__pycache__/dep_util.cpython-310.pyc,, +setuptools/_distutils/__pycache__/dir_util.cpython-310.pyc,, +setuptools/_distutils/__pycache__/dist.cpython-310.pyc,, +setuptools/_distutils/__pycache__/errors.cpython-310.pyc,, +setuptools/_distutils/__pycache__/extension.cpython-310.pyc,, +setuptools/_distutils/__pycache__/fancy_getopt.cpython-310.pyc,, +setuptools/_distutils/__pycache__/file_util.cpython-310.pyc,, +setuptools/_distutils/__pycache__/filelist.cpython-310.pyc,, +setuptools/_distutils/__pycache__/log.cpython-310.pyc,, +setuptools/_distutils/__pycache__/spawn.cpython-310.pyc,, +setuptools/_distutils/__pycache__/sysconfig.cpython-310.pyc,, +setuptools/_distutils/__pycache__/text_file.cpython-310.pyc,, +setuptools/_distutils/__pycache__/unixccompiler.cpython-310.pyc,, +setuptools/_distutils/__pycache__/util.cpython-310.pyc,, +setuptools/_distutils/__pycache__/version.cpython-310.pyc,, +setuptools/_distutils/__pycache__/versionpredicate.cpython-310.pyc,, +setuptools/_distutils/__pycache__/zosccompiler.cpython-310.pyc,, +setuptools/_distutils/_log.py,sha256=i-lNTTcXS8TmWITJ6DODGvtW5z5tMattJQ76h8rZxQU,42 +setuptools/_distutils/_macos_compat.py,sha256=JzUGhF4E5yIITHbUaPobZEWjGHdrrcNV63z86S4RjBc,239 +setuptools/_distutils/_modified.py,sha256=RF1n1CexyDYV3lvGbeXS0s-XCJVboDOIUbA8wEQqYTY,3211 +setuptools/_distutils/_msvccompiler.py,sha256=9PSfSHxvJnHnQL6Sqz4Xcz7iaBIT62p6BheQzGsSlwo,335 +setuptools/_distutils/archive_util.py,sha256=Qw2z-Pt-NV8lNUQrzjs3XDGWCWHMPnqHLyt8TiD2XEA,8884 +setuptools/_distutils/ccompiler.py,sha256=FKVjqzGJ7c-FtouNjhLiaMPm5LKMZHHAruXf8LU216c,524 +setuptools/_distutils/cmd.py,sha256=hXtaRaH7QBnfNOIqEvCt47iwZzD9MVvBdhhdQctHsxM,22186 +setuptools/_distutils/command/__init__.py,sha256=GfFAzbBqk1qxSH4BdaKioKS4hRRnD44BAmwEN85C4u8,386 +setuptools/_distutils/command/__pycache__/__init__.cpython-310.pyc,, +setuptools/_distutils/command/__pycache__/_framework_compat.cpython-310.pyc,, +setuptools/_distutils/command/__pycache__/bdist.cpython-310.pyc,, +setuptools/_distutils/command/__pycache__/bdist_dumb.cpython-310.pyc,, +setuptools/_distutils/command/__pycache__/bdist_rpm.cpython-310.pyc,, +setuptools/_distutils/command/__pycache__/build.cpython-310.pyc,, +setuptools/_distutils/command/__pycache__/build_clib.cpython-310.pyc,, +setuptools/_distutils/command/__pycache__/build_ext.cpython-310.pyc,, +setuptools/_distutils/command/__pycache__/build_py.cpython-310.pyc,, +setuptools/_distutils/command/__pycache__/build_scripts.cpython-310.pyc,, +setuptools/_distutils/command/__pycache__/check.cpython-310.pyc,, +setuptools/_distutils/command/__pycache__/clean.cpython-310.pyc,, +setuptools/_distutils/command/__pycache__/config.cpython-310.pyc,, +setuptools/_distutils/command/__pycache__/install.cpython-310.pyc,, +setuptools/_distutils/command/__pycache__/install_data.cpython-310.pyc,, +setuptools/_distutils/command/__pycache__/install_egg_info.cpython-310.pyc,, +setuptools/_distutils/command/__pycache__/install_headers.cpython-310.pyc,, +setuptools/_distutils/command/__pycache__/install_lib.cpython-310.pyc,, +setuptools/_distutils/command/__pycache__/install_scripts.cpython-310.pyc,, +setuptools/_distutils/command/__pycache__/sdist.cpython-310.pyc,, +setuptools/_distutils/command/_framework_compat.py,sha256=0iZdSJYzGRWCCvzRDKE-R0-_yaAYvFMd1ylXb2eYXug,1609 +setuptools/_distutils/command/bdist.py,sha256=jWtk61R7fWNUUNxJV0thTZzU5n80L3Ay1waSiP9kiLA,5854 +setuptools/_distutils/command/bdist_dumb.py,sha256=Hx1jAqoZNxYIy4N5TLzUp6J5fi8Ls18py7UlLNFhO2E,4631 +setuptools/_distutils/command/bdist_rpm.py,sha256=nxcXXv5a7B-1ntWu4DbGmCtES4EBINrJaBQcRNAYCJI,21785 +setuptools/_distutils/command/build.py,sha256=SpHlagf0iNaKVyIhxDfhPFZ8X1-LAWOCQACy-yt2K0w,5923 +setuptools/_distutils/command/build_clib.py,sha256=aMqZcUfCbOAu_xr-A9iW-Q9YZHzpDGLRTezOgMQJmSQ,7777 +setuptools/_distutils/command/build_ext.py,sha256=zrrsu9HXnzV6bXYbJuZCK4SwVZMjKnl4pG1o3bNcxtc,32710 +setuptools/_distutils/command/build_py.py,sha256=Vfq-INemoMbg6f003BTy_Ufp8bjOZhmFIhpKMcfXLgs,16696 +setuptools/_distutils/command/build_scripts.py,sha256=tUpEzwTsnrP8qrNory3ldPB240QDCFkMp-pdYPs2wTk,5118 +setuptools/_distutils/command/check.py,sha256=yoNe2MPY4JcTM7rwoIQdfZ75q5Ri058I2coi-Gq9CjM,4946 +setuptools/_distutils/command/clean.py,sha256=dQAacOabwBXU9JoZ-1GFusq3eFltDaeXJFSYncqGbvE,2644 +setuptools/_distutils/command/config.py,sha256=qrrfz6NEQORmbqiY2XlvCDWYhsbLyxZXJsURKfYN_kw,12724 +setuptools/_distutils/command/install.py,sha256=-JenB-mua4hc2RI_-W8F9PnP_J-OaFO7E0PJGKxLo1o,30072 +setuptools/_distutils/command/install_data.py,sha256=GzBlUWWKubTYJlP-L0auUriq9cL-5RKOcoyHTttKj0Q,2875 +setuptools/_distutils/command/install_egg_info.py,sha256=ffiLoU1ivQJ8q2_WL7ZygZbUcOsgdFLKL7otEIJWWkI,2868 +setuptools/_distutils/command/install_headers.py,sha256=5ciKCj8c3XKsYNKdkdMvnypaUCKcoWCDeeZij3fD-Z4,1272 +setuptools/_distutils/command/install_lib.py,sha256=2s9-m5-b1qKm51F28lB5L39Z6vv_GHMlv9dNBSupok0,8588 +setuptools/_distutils/command/install_scripts.py,sha256=M0pPdiaqB7TGmqTMujpGGeiL0Iq_CTeGjMFtrmDmwzM,2002 +setuptools/_distutils/command/sdist.py,sha256=cRIF6Ht1hJ6ayOOFVycMFBUNxjo94e_rFYPx4Hi8Ahc,19151 +setuptools/_distutils/compat/__init__.py,sha256=J20aXGjJ86Rg41xFLIWlcWCgZ9edMdJ9vvdNEQ87vPQ,522 +setuptools/_distutils/compat/__pycache__/__init__.cpython-310.pyc,, +setuptools/_distutils/compat/__pycache__/numpy.cpython-310.pyc,, +setuptools/_distutils/compat/__pycache__/py39.cpython-310.pyc,, +setuptools/_distutils/compat/numpy.py,sha256=UFgneZw9w97g4c-yGoAIOyLxUOWQ-fPRIhhfMs7_Ouc,167 +setuptools/_distutils/compat/py39.py,sha256=hOsD6lwZLqZoMnacNJ3P6nUA-LJQhEpVtYTzVH0o96M,1964 +setuptools/_distutils/compilers/C/__pycache__/base.cpython-310.pyc,, +setuptools/_distutils/compilers/C/__pycache__/cygwin.cpython-310.pyc,, +setuptools/_distutils/compilers/C/__pycache__/errors.cpython-310.pyc,, +setuptools/_distutils/compilers/C/__pycache__/msvc.cpython-310.pyc,, +setuptools/_distutils/compilers/C/__pycache__/unix.cpython-310.pyc,, +setuptools/_distutils/compilers/C/__pycache__/zos.cpython-310.pyc,, +setuptools/_distutils/compilers/C/base.py,sha256=XR1rBCStCquqm7QOYXD41-LfvsFcPpGxrwxeXzJyn_w,54876 +setuptools/_distutils/compilers/C/cygwin.py,sha256=DUlwQSb55aj7OdcmcddrmCmVEjEaxIiJ5hHUO3GBPNs,11844 +setuptools/_distutils/compilers/C/errors.py,sha256=sKOVzJajMUmNdfywo9UM_QQGsKFcclDhtI5TlCiXMLc,573 +setuptools/_distutils/compilers/C/msvc.py,sha256=elzG8v9jN5QytLMwLCdUdSuZ3eZ3R98VUvnm9Y2PBCA,21404 +setuptools/_distutils/compilers/C/tests/__pycache__/test_base.cpython-310.pyc,, +setuptools/_distutils/compilers/C/tests/__pycache__/test_cygwin.cpython-310.pyc,, +setuptools/_distutils/compilers/C/tests/__pycache__/test_mingw.cpython-310.pyc,, +setuptools/_distutils/compilers/C/tests/__pycache__/test_msvc.cpython-310.pyc,, +setuptools/_distutils/compilers/C/tests/__pycache__/test_unix.cpython-310.pyc,, +setuptools/_distutils/compilers/C/tests/test_base.py,sha256=rdhHc56bhXtm5NnN9BSHwr6c69UqzMItZQzlw2AsdMc,2706 +setuptools/_distutils/compilers/C/tests/test_cygwin.py,sha256=UgV2VgUXj3VulcbDc0UBWfEyJDx42tgSwS4LzHix3mY,2701 +setuptools/_distutils/compilers/C/tests/test_mingw.py,sha256=hCmwyywISpRoyOySbFHBL4TprWRV0mUWDKmOLO8XBXE,1900 +setuptools/_distutils/compilers/C/tests/test_msvc.py,sha256=DlGjmZ1mBSMXIgmlu80BKc7V-EJOZuYucwJwFh5dn28,4151 +setuptools/_distutils/compilers/C/tests/test_unix.py,sha256=AyadWw1fR-UeDl2TvIbYBzOJVHkpE_oRRQ3JTJWqaEA,14642 +setuptools/_distutils/compilers/C/unix.py,sha256=YH-y9g_pjBFjaJyHJQkDEBQ7q4D20I2-cWJNdgw-Yho,16531 +setuptools/_distutils/compilers/C/zos.py,sha256=vnNeWLRZkdIkdZ-YyBnL8idTUfcCOn0tLMW5OBJ0ScU,6586 +setuptools/_distutils/core.py,sha256=GEHKaFC48T3o-_SmH4864GvKyx1IgbVC6ISIPVlx7a4,9364 +setuptools/_distutils/cygwinccompiler.py,sha256=mG_cU8SVZ4amD_VtF5vH6BXP0-kghGsDPbDSXrQ963c,594 +setuptools/_distutils/debug.py,sha256=N6MrTAqK6l9SVk6tWweR108PM8Ol7qNlfyV-nHcLhsY,139 +setuptools/_distutils/dep_util.py,sha256=xN75p6ZpHhMiHEc-rpL2XilJQynHnDNiafHteaZ4tjU,349 +setuptools/_distutils/dir_util.py,sha256=DXPUlfVVGsg9B-Jgg4At_j9T7vM60OgwNXkQHqTo7-I,7236 +setuptools/_distutils/dist.py,sha256=gW598UE0WMkzXQQ31Nr-8L7MPw0oIOz5OSSRzYZlwrM,55794 +setuptools/_distutils/errors.py,sha256=PPE2oDRh5y9Q1beKK9rhdvDaCzQhi4HCXs4KcqfqgZY,3092 +setuptools/_distutils/extension.py,sha256=Foyu4gULcPqm1_U9zrYYHxNk4NqglXv1rbsOk_QrSds,11155 +setuptools/_distutils/fancy_getopt.py,sha256=PjdO-bWCW0imV_UN-MGEw9R2GP2OiE8pHjITgmTAY3Q,17895 +setuptools/_distutils/file_util.py,sha256=YFQL_pD3hLuER9II_H6-hDC_YIGEookdd4wedLuiTW0,7978 +setuptools/_distutils/filelist.py,sha256=MBeSRJmPcKmDv8ooZgSU4BiQPZ0Khwv8l_jhD50XycI,15337 +setuptools/_distutils/log.py,sha256=VyBs5j7z4-K6XTEEBThUc9HyMpoPLGtQpERqbz5ylww,1200 +setuptools/_distutils/spawn.py,sha256=zseCh9sEifyp0I5Vg719JNIASlROJ2ehXqQnHlpt89Q,4086 +setuptools/_distutils/sysconfig.py,sha256=KeI8OHbMuEzHJ8Q0cBez9KZny8iRy6Z6Y0AkMz1jlsU,19728 +setuptools/_distutils/tests/__init__.py,sha256=j-IoPZEtQv3EOPuqNTwalr6GLyRjzCC-OOaNvZzmHsI,1485 +setuptools/_distutils/tests/__pycache__/__init__.cpython-310.pyc,, +setuptools/_distutils/tests/__pycache__/support.cpython-310.pyc,, +setuptools/_distutils/tests/__pycache__/test_archive_util.cpython-310.pyc,, +setuptools/_distutils/tests/__pycache__/test_bdist.cpython-310.pyc,, +setuptools/_distutils/tests/__pycache__/test_bdist_dumb.cpython-310.pyc,, +setuptools/_distutils/tests/__pycache__/test_bdist_rpm.cpython-310.pyc,, +setuptools/_distutils/tests/__pycache__/test_build.cpython-310.pyc,, +setuptools/_distutils/tests/__pycache__/test_build_clib.cpython-310.pyc,, +setuptools/_distutils/tests/__pycache__/test_build_ext.cpython-310.pyc,, +setuptools/_distutils/tests/__pycache__/test_build_py.cpython-310.pyc,, +setuptools/_distutils/tests/__pycache__/test_build_scripts.cpython-310.pyc,, +setuptools/_distutils/tests/__pycache__/test_check.cpython-310.pyc,, +setuptools/_distutils/tests/__pycache__/test_clean.cpython-310.pyc,, +setuptools/_distutils/tests/__pycache__/test_cmd.cpython-310.pyc,, +setuptools/_distutils/tests/__pycache__/test_config_cmd.cpython-310.pyc,, +setuptools/_distutils/tests/__pycache__/test_core.cpython-310.pyc,, +setuptools/_distutils/tests/__pycache__/test_dir_util.cpython-310.pyc,, +setuptools/_distutils/tests/__pycache__/test_dist.cpython-310.pyc,, +setuptools/_distutils/tests/__pycache__/test_extension.cpython-310.pyc,, +setuptools/_distutils/tests/__pycache__/test_file_util.cpython-310.pyc,, +setuptools/_distutils/tests/__pycache__/test_filelist.cpython-310.pyc,, +setuptools/_distutils/tests/__pycache__/test_install.cpython-310.pyc,, +setuptools/_distutils/tests/__pycache__/test_install_data.cpython-310.pyc,, +setuptools/_distutils/tests/__pycache__/test_install_headers.cpython-310.pyc,, +setuptools/_distutils/tests/__pycache__/test_install_lib.cpython-310.pyc,, +setuptools/_distutils/tests/__pycache__/test_install_scripts.cpython-310.pyc,, +setuptools/_distutils/tests/__pycache__/test_log.cpython-310.pyc,, +setuptools/_distutils/tests/__pycache__/test_modified.cpython-310.pyc,, +setuptools/_distutils/tests/__pycache__/test_sdist.cpython-310.pyc,, +setuptools/_distutils/tests/__pycache__/test_spawn.cpython-310.pyc,, +setuptools/_distutils/tests/__pycache__/test_sysconfig.cpython-310.pyc,, +setuptools/_distutils/tests/__pycache__/test_text_file.cpython-310.pyc,, +setuptools/_distutils/tests/__pycache__/test_util.cpython-310.pyc,, +setuptools/_distutils/tests/__pycache__/test_version.cpython-310.pyc,, +setuptools/_distutils/tests/__pycache__/test_versionpredicate.cpython-310.pyc,, +setuptools/_distutils/tests/__pycache__/unix_compat.cpython-310.pyc,, +setuptools/_distutils/tests/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_distutils/tests/compat/__pycache__/__init__.cpython-310.pyc,, +setuptools/_distutils/tests/compat/__pycache__/py39.cpython-310.pyc,, +setuptools/_distutils/tests/compat/py39.py,sha256=t0GBTM-30jX-9zCfkwlNBFtzzabemx6065mJ0d9_VRw,1026 +setuptools/_distutils/tests/support.py,sha256=tjsYsyxvpTK4NrkCseh2ujvDIGV0Mf_b5SI5fP2T0yM,4099 +setuptools/_distutils/tests/test_archive_util.py,sha256=jozimSwPBF-JoJfN_vDaiVGZp66BNcWZGh34FlW57DQ,11787 +setuptools/_distutils/tests/test_bdist.py,sha256=xNHxUsLlHsZQRwkzLb_iSD24s-9Mk-NX2ffBWwOyPyc,1396 +setuptools/_distutils/tests/test_bdist_dumb.py,sha256=QF05MHNhPOdZyh88Xpw8KsO64s7pRFkl8KL-RoV4XK0,2247 +setuptools/_distutils/tests/test_bdist_rpm.py,sha256=Hdm-pwWgyaoGdGbEcGZa8cRhGU45y8gHK8umOanTjik,3932 +setuptools/_distutils/tests/test_build.py,sha256=JJY5XpOZco25ZY0pstxl-iI8mHsWP0ujf5o8aOtuZYY,1742 +setuptools/_distutils/tests/test_build_clib.py,sha256=Mo1ZFb4C1VXBYOGvnallwN7YCnTtr24akLDO8Zi4CsY,4331 +setuptools/_distutils/tests/test_build_ext.py,sha256=QFO9qYVhWWdJu17HXc4x9RMnLZlhk0lAHi9HVppbuX4,22545 +setuptools/_distutils/tests/test_build_py.py,sha256=NsfmRrojOHBXNMqWR_mp5g4PLTgjhD7iZFUffGZFIdw,6882 +setuptools/_distutils/tests/test_build_scripts.py,sha256=cD-FRy-oX55sXRX5Ez5xQCaeHrWajyKc4Xuwv2fe48w,2880 +setuptools/_distutils/tests/test_check.py,sha256=hHSV07qf7YoSxGsTbbsUQ9tssZz5RRNdbrY1s2SwaFI,6226 +setuptools/_distutils/tests/test_clean.py,sha256=hPH6jfIpGFUrvWbF1txkiNVSNaAxt2wq5XjV499zO4E,1240 +setuptools/_distutils/tests/test_cmd.py,sha256=bgRB79mitoOKR1OiyZHnCogvGxt3pWkxeTqIC04lQWQ,3254 +setuptools/_distutils/tests/test_config_cmd.py,sha256=Zs6WX0IfxDvmuC19XzuVNnYCnTr9Y-hl73TAmDSBN4Y,2664 +setuptools/_distutils/tests/test_core.py,sha256=L7XKVAxa-MGoAZeANopnuK9fRKneYhkSQpgw8XQvcF8,3829 +setuptools/_distutils/tests/test_dir_util.py,sha256=E84lC-k4riVUwURyWaQ0Jqx2ui2-io-0RuJa3M7qkJs,4500 +setuptools/_distutils/tests/test_dist.py,sha256=a6wlc5fQJd5qQ6HOndzcupNhjTxvj6-_JLtpuYvaP1M,18793 +setuptools/_distutils/tests/test_extension.py,sha256=-YejLgZCuycFrOBd64pVH0JvwMc9NwhzHvQxvvjXHqk,3670 +setuptools/_distutils/tests/test_file_util.py,sha256=livjnl3FkilQlrB2rFdFQq9nvjEVZHynNya0bfzv_b4,3522 +setuptools/_distutils/tests/test_filelist.py,sha256=rJwkqCUfkGDgWlD22TozsT8ycbupMHB8DXqThzwT1T4,10766 +setuptools/_distutils/tests/test_install.py,sha256=TfCB0ykhIxydIC2Q4SuTAZzSHvteMHgrBL9whoSgK9Q,8618 +setuptools/_distutils/tests/test_install_data.py,sha256=vKq3K97k0hBAnOg38nmwEdf7cEDVr9rTVyCeJolgb4A,2464 +setuptools/_distutils/tests/test_install_headers.py,sha256=PVAYpo_tYl980Qf64DPOmmSvyefIHdU06f7VsJeZykE,936 +setuptools/_distutils/tests/test_install_lib.py,sha256=qri6Rl-maNTQrNDV8DbeXNl0hjsfRIKiI4rfZLrmWBI,3612 +setuptools/_distutils/tests/test_install_scripts.py,sha256=KE3v0cDkFW-90IOID-OmZZGM2mhy-ZkEuuW7UXS2SHw,1600 +setuptools/_distutils/tests/test_log.py,sha256=isFtOufloCyEdZaQOV7cVUr46GwtdVMj43mGBB5XH7k,323 +setuptools/_distutils/tests/test_modified.py,sha256=h1--bOWmtJo1bpVV6uRhdnS9br71CBiNDM1MDwSGpug,4221 +setuptools/_distutils/tests/test_sdist.py,sha256=cfzUhlCA418-1vH9ta3IBs26c_jUBbkJoFOK5GnAyNk,15062 +setuptools/_distutils/tests/test_spawn.py,sha256=eS8w9D7bTxyFLSyRahJWeuh8Kc1F8RWWiY_dSG5B5Bc,4803 +setuptools/_distutils/tests/test_sysconfig.py,sha256=lxM8LsUi1TomjDV4HoYK8u5nUoBkeNL60Uq8PY1DcwU,11986 +setuptools/_distutils/tests/test_text_file.py,sha256=WQWSB5AfdBDZaMA8BFgipJPnsJb_2SKMfL90fSkRVtw,3460 +setuptools/_distutils/tests/test_util.py,sha256=H9zlZ4z4Vh4TfjNYDBsxP7wguQLpxCfJYyOcm1yZU3c,7988 +setuptools/_distutils/tests/test_version.py,sha256=ahfg_mP8wRy1sgwY-_Px5hrjgf6_upTIpnCgpR4yWRk,2750 +setuptools/_distutils/tests/test_versionpredicate.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_distutils/tests/unix_compat.py,sha256=z-op6C2iVdX1aq5BIBR7cqOxijKE97alNwJqHNdLpoI,386 +setuptools/_distutils/text_file.py,sha256=z4dkOJBr9Bo2LG0TNqm8sD63LEEaKSSP0J0bWBrFG3c,12101 +setuptools/_distutils/unixccompiler.py,sha256=1bXJWH4fiu_A2WfriHzf88xjllQTXnnjUkZdRKs9cWU,212 +setuptools/_distutils/util.py,sha256=Njfnqk60zMdkiAjRnGcTWX3t49-obHapOlbNvyIl02I,18094 +setuptools/_distutils/version.py,sha256=vImT5-ECXkQ21oKL0XYFiTqK6NyM09cpzBNoA_34CQU,12619 +setuptools/_distutils/versionpredicate.py,sha256=qBWQ6wTj12ODytoTmIydefIY2jb4uY1sdbgbuLn-IJM,5205 +setuptools/_distutils/zosccompiler.py,sha256=svdiXZ2kdcwKrJKfhUhib03y8gz7aGZKukXH3I7YkBc,58 +setuptools/_entry_points.py,sha256=Y3QUE9JKFW_YyquDnpffNWSs6f3jKEt1e-dnx--9-Kw,2310 +setuptools/_imp.py,sha256=YY1EjZEN-0zYci1cxO10B_adAEOr7i8eK8JoCc9Ierc,2435 +setuptools/_importlib.py,sha256=aKIjcK0HKXNz2D-XTrxaixGn_juTkONwmu3dcheMOF0,223 +setuptools/_itertools.py,sha256=jWRfsIrpC7myooz3hDURj9GtvpswZeKXg2HakmEhNjo,657 +setuptools/_normalization.py,sha256=kAmGfrwjF5djydEfLLyKgjkXCbL_0_ZxUPO-DlLlmIY,5824 +setuptools/_path.py,sha256=cPv41v03HD7uEYqCIo-E_cGRfpPVr4lywBCiK-HSrCg,2685 +setuptools/_reqs.py,sha256=QI3C9uOBSNRccu208qPnixHx51nxCry7_nPTIJaSYxM,1438 +setuptools/_shutil.py,sha256=cAOllcoyMTXs5JLoybQi29yI5gABk82hepJyOBv2bMw,1496 +setuptools/_static.py,sha256=GTR79gESF1_JaK4trLkpDrEuCeEtPlwQW0MRv7VNQX4,4855 +setuptools/_vendor/__pycache__/typing_extensions.cpython-310.pyc,, +setuptools/_vendor/autocommand-2.2.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +setuptools/_vendor/autocommand-2.2.2.dist-info/LICENSE,sha256=reeNBJgtaZctREqOFKlPh6IzTdOFXMgDSOqOJAqg3y0,7634 +setuptools/_vendor/autocommand-2.2.2.dist-info/METADATA,sha256=OADZuR3O6iBlpu1ieTgzYul6w4uOVrk0P0BO5TGGAJk,15006 +setuptools/_vendor/autocommand-2.2.2.dist-info/RECORD,sha256=giu6ZrQVJvpUcYa4AiH4XaUNZSvuVJPb_l0UCFES8MM,1308 +setuptools/_vendor/autocommand-2.2.2.dist-info/WHEEL,sha256=2wepM1nk4DS4eFpYrW1TTqPcoGNfHhhO_i5m4cOimbo,92 +setuptools/_vendor/autocommand-2.2.2.dist-info/top_level.txt,sha256=AzfhgKKS8EdAwWUTSF8mgeVQbXOY9kokHB6kSqwwqu0,12 +setuptools/_vendor/autocommand/__init__.py,sha256=zko5Rnvolvb-UXjCx_2ArPTGBWwUK5QY4LIQIKYR7As,1037 +setuptools/_vendor/autocommand/__pycache__/__init__.cpython-310.pyc,, +setuptools/_vendor/autocommand/__pycache__/autoasync.cpython-310.pyc,, +setuptools/_vendor/autocommand/__pycache__/autocommand.cpython-310.pyc,, +setuptools/_vendor/autocommand/__pycache__/automain.cpython-310.pyc,, +setuptools/_vendor/autocommand/__pycache__/autoparse.cpython-310.pyc,, +setuptools/_vendor/autocommand/__pycache__/errors.cpython-310.pyc,, +setuptools/_vendor/autocommand/autoasync.py,sha256=AMdyrxNS4pqWJfP_xuoOcImOHWD-qT7x06wmKN1Vp-U,5680 +setuptools/_vendor/autocommand/autocommand.py,sha256=hmkEmQ72HtL55gnURVjDOnsfYlGd5lLXbvT4KG496Qw,2505 +setuptools/_vendor/autocommand/automain.py,sha256=A2b8i754Mxc_DjU9WFr6vqYDWlhz0cn8miu8d8EsxV8,2076 +setuptools/_vendor/autocommand/autoparse.py,sha256=WVWmZJPcbzUKXP40raQw_0HD8qPJ2V9VG1eFFmmnFxw,11642 +setuptools/_vendor/autocommand/errors.py,sha256=7aa3roh9Herd6nIKpQHNWEslWE8oq7GiHYVUuRqORnA,886 +setuptools/_vendor/backports.tarfile-1.2.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +setuptools/_vendor/backports.tarfile-1.2.0.dist-info/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023 +setuptools/_vendor/backports.tarfile-1.2.0.dist-info/METADATA,sha256=ghXFTq132dxaEIolxr3HK1mZqm9iyUmaRANZQSr6WlE,2020 +setuptools/_vendor/backports.tarfile-1.2.0.dist-info/RECORD,sha256=JYofHISeEXUGmlWl1s41ev3QTjTNXeJwk-Ss7HqdLOE,1360 +setuptools/_vendor/backports.tarfile-1.2.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/backports.tarfile-1.2.0.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92 +setuptools/_vendor/backports.tarfile-1.2.0.dist-info/top_level.txt,sha256=cGjaLMOoBR1FK0ApojtzWVmViTtJ7JGIK_HwXiEsvtU,10 +setuptools/_vendor/backports/__init__.py,sha256=iOEMwnlORWezdO8-2vxBIPSR37D7JGjluZ8f55vzxls,81 +setuptools/_vendor/backports/__pycache__/__init__.cpython-310.pyc,, +setuptools/_vendor/backports/tarfile/__init__.py,sha256=Pwf2qUIfB0SolJPCKcx3vz3UEu_aids4g4sAfxy94qg,108491 +setuptools/_vendor/backports/tarfile/__main__.py,sha256=Yw2oGT1afrz2eBskzdPYL8ReB_3liApmhFkN2EbDmc4,59 +setuptools/_vendor/backports/tarfile/__pycache__/__init__.cpython-310.pyc,, +setuptools/_vendor/backports/tarfile/__pycache__/__main__.cpython-310.pyc,, +setuptools/_vendor/backports/tarfile/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/backports/tarfile/compat/__pycache__/__init__.cpython-310.pyc,, +setuptools/_vendor/backports/tarfile/compat/__pycache__/py38.cpython-310.pyc,, +setuptools/_vendor/backports/tarfile/compat/py38.py,sha256=iYkyt_gvWjLzGUTJD9TuTfMMjOk-ersXZmRlvQYN2qE,568 +setuptools/_vendor/importlib_metadata-8.0.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +setuptools/_vendor/importlib_metadata-8.0.0.dist-info/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358 +setuptools/_vendor/importlib_metadata-8.0.0.dist-info/METADATA,sha256=anuQ7_7h4J1bSEzfcjIBakPi2cyVQ7y7jklLHsBeH1k,4648 +setuptools/_vendor/importlib_metadata-8.0.0.dist-info/RECORD,sha256=DY08buueu-hsrH1ghhVSQzwynanqUSSLYdAr4uXmQDA,2518 +setuptools/_vendor/importlib_metadata-8.0.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/importlib_metadata-8.0.0.dist-info/WHEEL,sha256=mguMlWGMX-VHnMpKOjjQidIo1ssRlCFu4a4mBpz1s2M,91 +setuptools/_vendor/importlib_metadata-8.0.0.dist-info/top_level.txt,sha256=CO3fD9yylANiXkrMo4qHLV_mqXL2sC5JFKgt1yWAT-A,19 +setuptools/_vendor/importlib_metadata/__init__.py,sha256=tZNB-23h8Bixi9uCrQqj9Yf0aeC--Josdy3IZRIQeB0,33798 +setuptools/_vendor/importlib_metadata/__pycache__/__init__.cpython-310.pyc,, +setuptools/_vendor/importlib_metadata/__pycache__/_adapters.cpython-310.pyc,, +setuptools/_vendor/importlib_metadata/__pycache__/_collections.cpython-310.pyc,, +setuptools/_vendor/importlib_metadata/__pycache__/_compat.cpython-310.pyc,, +setuptools/_vendor/importlib_metadata/__pycache__/_functools.cpython-310.pyc,, +setuptools/_vendor/importlib_metadata/__pycache__/_itertools.cpython-310.pyc,, +setuptools/_vendor/importlib_metadata/__pycache__/_meta.cpython-310.pyc,, +setuptools/_vendor/importlib_metadata/__pycache__/_text.cpython-310.pyc,, +setuptools/_vendor/importlib_metadata/__pycache__/diagnose.cpython-310.pyc,, +setuptools/_vendor/importlib_metadata/_adapters.py,sha256=rIhWTwBvYA1bV7i-5FfVX38qEXDTXFeS5cb5xJtP3ks,2317 +setuptools/_vendor/importlib_metadata/_collections.py,sha256=CJ0OTCHIjWA0ZIVS4voORAsn2R4R2cQBEtPsZEJpASY,743 +setuptools/_vendor/importlib_metadata/_compat.py,sha256=73QKrN9KNoaZzhbX5yPCCZa-FaALwXe8TPlDR72JgBU,1314 +setuptools/_vendor/importlib_metadata/_functools.py,sha256=PsY2-4rrKX4RVeRC1oGp1lB1pmC9eKN88_f-bD9uOoA,2895 +setuptools/_vendor/importlib_metadata/_itertools.py,sha256=cvr_2v8BRbxcIl5x5ldfqdHjhI8Yi8s8yk50G_nm6jQ,2068 +setuptools/_vendor/importlib_metadata/_meta.py,sha256=nxZ7C8GVlcBFAKWyVOn_dn7ot_twBcbm1NmvjIetBHI,1801 +setuptools/_vendor/importlib_metadata/_text.py,sha256=HCsFksZpJLeTP3NEk_ngrAeXVRRtTrtyh9eOABoRP4A,2166 +setuptools/_vendor/importlib_metadata/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/importlib_metadata/compat/__pycache__/__init__.cpython-310.pyc,, +setuptools/_vendor/importlib_metadata/compat/__pycache__/py311.cpython-310.pyc,, +setuptools/_vendor/importlib_metadata/compat/__pycache__/py39.cpython-310.pyc,, +setuptools/_vendor/importlib_metadata/compat/py311.py,sha256=uqm-K-uohyj1042TH4a9Er_I5o7667DvulcD-gC_fSA,608 +setuptools/_vendor/importlib_metadata/compat/py39.py,sha256=cPkMv6-0ilK-0Jw_Tkn0xYbOKJZc4WJKQHow0c2T44w,1102 +setuptools/_vendor/importlib_metadata/diagnose.py,sha256=nkSRMiowlmkhLYhKhvCg9glmt_11Cox-EmLzEbqYTa8,379 +setuptools/_vendor/importlib_metadata/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/inflect-7.3.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +setuptools/_vendor/inflect-7.3.1.dist-info/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023 +setuptools/_vendor/inflect-7.3.1.dist-info/METADATA,sha256=ZgMNY0WAZRs-U8wZiV2SMfjSKqBrMngXyDMs_CAwMwg,21079 +setuptools/_vendor/inflect-7.3.1.dist-info/RECORD,sha256=XXg0rBuiYSxoAQUP3lenuYsPNqz4jDwtTzdv2JEbMJE,943 +setuptools/_vendor/inflect-7.3.1.dist-info/WHEEL,sha256=y4mX-SOX4fYIkonsAGA5N0Oy-8_gI4FXw5HNI1xqvWg,91 +setuptools/_vendor/inflect-7.3.1.dist-info/top_level.txt,sha256=m52ujdp10CqT6jh1XQxZT6kEntcnv-7Tl7UiGNTzWZA,8 +setuptools/_vendor/inflect/__init__.py,sha256=Jxy1HJXZiZ85kHeLAhkmvz6EMTdFqBe-duvt34R6IOc,103796 +setuptools/_vendor/inflect/__pycache__/__init__.cpython-310.pyc,, +setuptools/_vendor/inflect/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/inflect/compat/__pycache__/__init__.cpython-310.pyc,, +setuptools/_vendor/inflect/compat/__pycache__/py38.cpython-310.pyc,, +setuptools/_vendor/inflect/compat/py38.py,sha256=oObVfVnWX9_OpnOuEJn1mFbJxVhwyR5epbiTNXDDaso,160 +setuptools/_vendor/inflect/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/jaraco.collections-5.1.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +setuptools/_vendor/jaraco.collections-5.1.0.dist-info/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023 +setuptools/_vendor/jaraco.collections-5.1.0.dist-info/METADATA,sha256=IMUaliNsA5X1Ox9MXUWOagch5R4Wwb_3M7erp29dBtg,3933 +setuptools/_vendor/jaraco.collections-5.1.0.dist-info/RECORD,sha256=HptivXDkpfom6VlMu4CGD_7KPev-6Hc9rvp3TNJZygY,873 +setuptools/_vendor/jaraco.collections-5.1.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/jaraco.collections-5.1.0.dist-info/WHEEL,sha256=Mdi9PDNwEZptOjTlUcAth7XJDFtKrHYaQMPulZeBCiQ,91 +setuptools/_vendor/jaraco.collections-5.1.0.dist-info/top_level.txt,sha256=0JnN3LfXH4LIRfXL-QFOGCJzQWZO3ELx4R1d_louoQM,7 +setuptools/_vendor/jaraco.context-5.3.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +setuptools/_vendor/jaraco.context-5.3.0.dist-info/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023 +setuptools/_vendor/jaraco.context-5.3.0.dist-info/METADATA,sha256=xDtguJej0tN9iEXCUvxEJh2a7xceIRVBEakBLSr__tY,4020 +setuptools/_vendor/jaraco.context-5.3.0.dist-info/RECORD,sha256=VRl7iKeEQyl7stgnp1uq50CzOJYlHYcoNdS0x17C9X4,641 +setuptools/_vendor/jaraco.context-5.3.0.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92 +setuptools/_vendor/jaraco.context-5.3.0.dist-info/top_level.txt,sha256=0JnN3LfXH4LIRfXL-QFOGCJzQWZO3ELx4R1d_louoQM,7 +setuptools/_vendor/jaraco.functools-4.0.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +setuptools/_vendor/jaraco.functools-4.0.1.dist-info/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023 +setuptools/_vendor/jaraco.functools-4.0.1.dist-info/METADATA,sha256=i4aUaQDX-jjdEQK5wevhegyx8JyLfin2HyvaSk3FHso,2891 +setuptools/_vendor/jaraco.functools-4.0.1.dist-info/RECORD,sha256=YyqnwE98S8wBwCevW5vHb-iVj0oYEDW5V6O9MBS6JIs,843 +setuptools/_vendor/jaraco.functools-4.0.1.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92 +setuptools/_vendor/jaraco.functools-4.0.1.dist-info/top_level.txt,sha256=0JnN3LfXH4LIRfXL-QFOGCJzQWZO3ELx4R1d_louoQM,7 +setuptools/_vendor/jaraco.text-3.12.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +setuptools/_vendor/jaraco.text-3.12.1.dist-info/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023 +setuptools/_vendor/jaraco.text-3.12.1.dist-info/METADATA,sha256=AzWdm6ViMfDOPoQMfLWn2zgBQSGJScyqeN29TcuWXVI,3658 +setuptools/_vendor/jaraco.text-3.12.1.dist-info/RECORD,sha256=gW2UV0HcokYJk4jKPu10_AZnrLqjb3C1WbJJTDl5sfY,1500 +setuptools/_vendor/jaraco.text-3.12.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/jaraco.text-3.12.1.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92 +setuptools/_vendor/jaraco.text-3.12.1.dist-info/top_level.txt,sha256=0JnN3LfXH4LIRfXL-QFOGCJzQWZO3ELx4R1d_louoQM,7 +setuptools/_vendor/jaraco/__pycache__/context.cpython-310.pyc,, +setuptools/_vendor/jaraco/collections/__init__.py,sha256=Pc1-SqjWm81ad1P0-GttpkwO_LWlnaY6gUq8gcKh2v0,26640 +setuptools/_vendor/jaraco/collections/__pycache__/__init__.cpython-310.pyc,, +setuptools/_vendor/jaraco/collections/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/jaraco/context.py,sha256=REoLIxDkO5MfEYowt_WoupNCRoxBS5v7YX2PbW8lIcs,9552 +setuptools/_vendor/jaraco/functools/__init__.py,sha256=hEAJaS2uSZRuF_JY4CxCHIYh79ZpxaPp9OiHyr9EJ1w,16642 +setuptools/_vendor/jaraco/functools/__init__.pyi,sha256=gk3dsgHzo5F_U74HzAvpNivFAPCkPJ1b2-yCd62dfnw,3878 +setuptools/_vendor/jaraco/functools/__pycache__/__init__.cpython-310.pyc,, +setuptools/_vendor/jaraco/functools/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/jaraco/text/Lorem ipsum.txt,sha256=N_7c_79zxOufBY9HZ3yzMgOkNv-TkOTTio4BydrSjgs,1335 +setuptools/_vendor/jaraco/text/__init__.py,sha256=Y2YUqXR_orUoDaY4SkPRe6ZZhb5HUHB_Ah9RCNsVyho,16250 +setuptools/_vendor/jaraco/text/__pycache__/__init__.cpython-310.pyc,, +setuptools/_vendor/jaraco/text/__pycache__/layouts.cpython-310.pyc,, +setuptools/_vendor/jaraco/text/__pycache__/show-newlines.cpython-310.pyc,, +setuptools/_vendor/jaraco/text/__pycache__/strip-prefix.cpython-310.pyc,, +setuptools/_vendor/jaraco/text/__pycache__/to-dvorak.cpython-310.pyc,, +setuptools/_vendor/jaraco/text/__pycache__/to-qwerty.cpython-310.pyc,, +setuptools/_vendor/jaraco/text/layouts.py,sha256=HTC8aSTLZ7uXipyOXapRMC158juecjK6RVwitfmZ9_w,643 +setuptools/_vendor/jaraco/text/show-newlines.py,sha256=WGQa65e8lyhb92LUOLqVn6KaCtoeVgVws6WtSRmLk6w,904 +setuptools/_vendor/jaraco/text/strip-prefix.py,sha256=NfVXV8JVNo6nqcuYASfMV7_y4Eo8zMQqlCOGvAnRIVw,412 +setuptools/_vendor/jaraco/text/to-dvorak.py,sha256=1SNcbSsvISpXXg-LnybIHHY-RUFOQr36zcHkY1pWFqw,119 +setuptools/_vendor/jaraco/text/to-qwerty.py,sha256=s4UMQUnPwFn_dB5uZC27BurHOQcYondBfzIpVL5pEzw,119 +setuptools/_vendor/more_itertools-10.3.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +setuptools/_vendor/more_itertools-10.3.0.dist-info/LICENSE,sha256=CfHIyelBrz5YTVlkHqm4fYPAyw_QB-te85Gn4mQ8GkY,1053 +setuptools/_vendor/more_itertools-10.3.0.dist-info/METADATA,sha256=BFO90O-fLNiVQMpj7oIS5ztzgJUUQZ3TA32P5HH3N-A,36293 +setuptools/_vendor/more_itertools-10.3.0.dist-info/RECORD,sha256=d8jnPgGNwP1-ntbICwWkQEVF9kH7CFIgzkKzaLWao9M,1259 +setuptools/_vendor/more_itertools-10.3.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/more_itertools-10.3.0.dist-info/WHEEL,sha256=rSgq_JpHF9fHR1lx53qwg_1-2LypZE_qmcuXbVUq948,81 +setuptools/_vendor/more_itertools/__init__.py,sha256=dtAbGjTDmn_ghiU5YXfhyDy0phAlXVdt5klZA5fUa-Q,149 +setuptools/_vendor/more_itertools/__init__.pyi,sha256=5B3eTzON1BBuOLob1vCflyEb2lSd6usXQQ-Cv-hXkeA,43 +setuptools/_vendor/more_itertools/__pycache__/__init__.cpython-310.pyc,, +setuptools/_vendor/more_itertools/__pycache__/more.cpython-310.pyc,, +setuptools/_vendor/more_itertools/__pycache__/recipes.cpython-310.pyc,, +setuptools/_vendor/more_itertools/more.py,sha256=1E5kzFncRKTDw0cYv1yRXMgDdunstLQd1QStcnL6U90,148370 +setuptools/_vendor/more_itertools/more.pyi,sha256=iXXeqt48Nxe8VGmIWpkVXuKpR2FYNuu2DU8nQLWCCu0,21484 +setuptools/_vendor/more_itertools/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/more_itertools/recipes.py,sha256=WedhhfhGVgr6zii8fIbGJVmRTw0ZKRiLKnYBDGJv4nY,28591 +setuptools/_vendor/more_itertools/recipes.pyi,sha256=T_mdGpcFdfrP3JSWbwzYP9JyNV-Go-7RPfpxfftAWlA,4617 +setuptools/_vendor/packaging-24.2.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2 +setuptools/_vendor/packaging-24.2.dist-info/LICENSE,sha256=ytHvW9NA1z4HS6YU0m996spceUDD2MNIUuZcSQlobEg,197 +setuptools/_vendor/packaging-24.2.dist-info/LICENSE.APACHE,sha256=DVQuDIgE45qn836wDaWnYhSdxoLXgpRRKH4RuTjpRZQ,10174 +setuptools/_vendor/packaging-24.2.dist-info/LICENSE.BSD,sha256=tw5-m3QvHMb5SLNMFqo5_-zpQZY2S8iP8NIYDwAo-sU,1344 +setuptools/_vendor/packaging-24.2.dist-info/METADATA,sha256=ohH86s6k5mIfQxY2TS0LcSfADeOFa4BiCC-bxZV-pNs,3204 +setuptools/_vendor/packaging-24.2.dist-info/RECORD,sha256=Y4DrXM0KY0ArfzhbAEa1LYFPwW3WEgEeL4iCqXe-A-M,2009 +setuptools/_vendor/packaging-24.2.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/packaging-24.2.dist-info/WHEEL,sha256=CpUCUxeHQbRN5UGRQHYRJorO5Af-Qy_fHMctcQ8DSGI,82 +setuptools/_vendor/packaging/__init__.py,sha256=dk4Ta_vmdVJxYHDcfyhvQNw8V3PgSBomKNXqg-D2JDY,494 +setuptools/_vendor/packaging/__pycache__/__init__.cpython-310.pyc,, +setuptools/_vendor/packaging/__pycache__/_elffile.cpython-310.pyc,, +setuptools/_vendor/packaging/__pycache__/_manylinux.cpython-310.pyc,, +setuptools/_vendor/packaging/__pycache__/_musllinux.cpython-310.pyc,, +setuptools/_vendor/packaging/__pycache__/_parser.cpython-310.pyc,, +setuptools/_vendor/packaging/__pycache__/_structures.cpython-310.pyc,, +setuptools/_vendor/packaging/__pycache__/_tokenizer.cpython-310.pyc,, +setuptools/_vendor/packaging/__pycache__/markers.cpython-310.pyc,, +setuptools/_vendor/packaging/__pycache__/metadata.cpython-310.pyc,, +setuptools/_vendor/packaging/__pycache__/requirements.cpython-310.pyc,, +setuptools/_vendor/packaging/__pycache__/specifiers.cpython-310.pyc,, +setuptools/_vendor/packaging/__pycache__/tags.cpython-310.pyc,, +setuptools/_vendor/packaging/__pycache__/utils.cpython-310.pyc,, +setuptools/_vendor/packaging/__pycache__/version.cpython-310.pyc,, +setuptools/_vendor/packaging/_elffile.py,sha256=cflAQAkE25tzhYmq_aCi72QfbT_tn891tPzfpbeHOwE,3306 +setuptools/_vendor/packaging/_manylinux.py,sha256=vl5OCoz4kx80H5rwXKeXWjl9WNISGmr4ZgTpTP9lU9c,9612 +setuptools/_vendor/packaging/_musllinux.py,sha256=p9ZqNYiOItGee8KcZFeHF_YcdhVwGHdK6r-8lgixvGQ,2694 +setuptools/_vendor/packaging/_parser.py,sha256=s_TvTvDNK0NrM2QB3VKThdWFM4Nc0P6JnkObkl3MjpM,10236 +setuptools/_vendor/packaging/_structures.py,sha256=q3eVNmbWJGG_S0Dit_S3Ao8qQqz_5PYTXFAKBZe5yr4,1431 +setuptools/_vendor/packaging/_tokenizer.py,sha256=J6v5H7Jzvb-g81xp_2QACKwO7LxHQA6ikryMU7zXwN8,5273 +setuptools/_vendor/packaging/licenses/__init__.py,sha256=1x5M1nEYjcgwEbLt0dXwz2ukjr18DiCzC0sraQqJ-Ww,5715 +setuptools/_vendor/packaging/licenses/__pycache__/__init__.cpython-310.pyc,, +setuptools/_vendor/packaging/licenses/__pycache__/_spdx.cpython-310.pyc,, +setuptools/_vendor/packaging/licenses/_spdx.py,sha256=oAm1ztPFwlsmCKe7lAAsv_OIOfS1cWDu9bNBkeu-2ns,48398 +setuptools/_vendor/packaging/markers.py,sha256=c89TNzB7ZdGYhkovm6PYmqGyHxXlYVaLW591PHUNKD8,10561 +setuptools/_vendor/packaging/metadata.py,sha256=YJibM7GYe4re8-0a3OlXmGS-XDgTEoO4tlBt2q25Bng,34762 +setuptools/_vendor/packaging/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/packaging/requirements.py,sha256=gYyRSAdbrIyKDY66ugIDUQjRMvxkH2ALioTmX3tnL6o,2947 +setuptools/_vendor/packaging/specifiers.py,sha256=GG1wPNMcL0fMJO68vF53wKMdwnfehDcaI-r9NpTfilA,40074 +setuptools/_vendor/packaging/tags.py,sha256=CFqrJzAzc2XNGexerH__T-Y5Iwq7WbsYXsiLERLWxY0,21014 +setuptools/_vendor/packaging/utils.py,sha256=0F3Hh9OFuRgrhTgGZUl5K22Fv1YP2tZl1z_2gO6kJiA,5050 +setuptools/_vendor/packaging/version.py,sha256=olfyuk_DPbflNkJ4wBWetXQ17c74x3DB501degUv7DY,16676 +setuptools/_vendor/platformdirs-4.2.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +setuptools/_vendor/platformdirs-4.2.2.dist-info/METADATA,sha256=zmsie01G1MtXR0wgIv5XpVeTO7idr0WWvfmxKsKWuGk,11429 +setuptools/_vendor/platformdirs-4.2.2.dist-info/RECORD,sha256=TCEddtQu1A78Os_Mhm2JEqcYr7yit-UYSUQjZtbpn-g,1642 +setuptools/_vendor/platformdirs-4.2.2.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/platformdirs-4.2.2.dist-info/WHEEL,sha256=zEMcRr9Kr03x1ozGwg5v9NQBKn3kndp6LSoSlVg-jhU,87 +setuptools/_vendor/platformdirs-4.2.2.dist-info/licenses/LICENSE,sha256=KeD9YukphQ6G6yjD_czwzv30-pSHkBHP-z0NS-1tTbY,1089 +setuptools/_vendor/platformdirs/__init__.py,sha256=EMGE8qeHRR9CzDFr8kL3tA8hdZZniYjXBVZd0UGTWK0,22225 +setuptools/_vendor/platformdirs/__main__.py,sha256=HnsUQHpiBaiTxwcmwVw-nFaPdVNZtQIdi1eWDtI-MzI,1493 +setuptools/_vendor/platformdirs/__pycache__/__init__.cpython-310.pyc,, +setuptools/_vendor/platformdirs/__pycache__/__main__.cpython-310.pyc,, +setuptools/_vendor/platformdirs/__pycache__/android.cpython-310.pyc,, +setuptools/_vendor/platformdirs/__pycache__/api.cpython-310.pyc,, +setuptools/_vendor/platformdirs/__pycache__/macos.cpython-310.pyc,, +setuptools/_vendor/platformdirs/__pycache__/unix.cpython-310.pyc,, +setuptools/_vendor/platformdirs/__pycache__/version.cpython-310.pyc,, +setuptools/_vendor/platformdirs/__pycache__/windows.cpython-310.pyc,, +setuptools/_vendor/platformdirs/android.py,sha256=xZXY9Jd46WOsxT2U6-5HsNtDZ-IQqxcEUrBLl3hYk4o,9016 +setuptools/_vendor/platformdirs/api.py,sha256=QBYdUac2eC521ek_y53uD1Dcq-lJX8IgSRVd4InC6uc,8996 +setuptools/_vendor/platformdirs/macos.py,sha256=wftsbsvq6nZ0WORXSiCrZNkRHz_WKuktl0a6mC7MFkI,5580 +setuptools/_vendor/platformdirs/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/platformdirs/unix.py,sha256=Cci9Wqt35dAMsg6HT9nRGHSBW5obb0pR3AE1JJnsCXg,10643 +setuptools/_vendor/platformdirs/version.py,sha256=r7F76tZRjgQKzrpx_I0_ZMQOMU-PS7eGnHD7zEK3KB0,411 +setuptools/_vendor/platformdirs/windows.py,sha256=IFpiohUBwxPtCzlyKwNtxyW4Jk8haa6W8o59mfrDXVo,10125 +setuptools/_vendor/tomli-2.0.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +setuptools/_vendor/tomli-2.0.1.dist-info/LICENSE,sha256=uAgWsNUwuKzLTCIReDeQmEpuO2GSLCte6S8zcqsnQv4,1072 +setuptools/_vendor/tomli-2.0.1.dist-info/METADATA,sha256=zPDceKmPwJGLWtZykrHixL7WVXWmJGzZ1jyRT5lCoPI,8875 +setuptools/_vendor/tomli-2.0.1.dist-info/RECORD,sha256=DLn5pFGh42WsVLTIhmLh2gy1SnLRalJY-wq_-dPhwCI,999 +setuptools/_vendor/tomli-2.0.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/tomli-2.0.1.dist-info/WHEEL,sha256=jPMR_Dzkc4X4icQtmz81lnNY_kAsfog7ry7qoRvYLXw,81 +setuptools/_vendor/tomli/__init__.py,sha256=JhUwV66DB1g4Hvt1UQCVMdfCu-IgAV8FXmvDU9onxd4,396 +setuptools/_vendor/tomli/__pycache__/__init__.cpython-310.pyc,, +setuptools/_vendor/tomli/__pycache__/_parser.cpython-310.pyc,, +setuptools/_vendor/tomli/__pycache__/_re.cpython-310.pyc,, +setuptools/_vendor/tomli/__pycache__/_types.cpython-310.pyc,, +setuptools/_vendor/tomli/_parser.py,sha256=g9-ENaALS-B8dokYpCuzUFalWlog7T-SIYMjLZSWrtM,22633 +setuptools/_vendor/tomli/_re.py,sha256=dbjg5ChZT23Ka9z9DHOXfdtSpPwUfdgMXnj8NOoly-w,2943 +setuptools/_vendor/tomli/_types.py,sha256=-GTG2VUqkpxwMqzmVO4F7ybKddIbAnuAHXfmWQcTi3Q,254 +setuptools/_vendor/tomli/py.typed,sha256=8PjyZ1aVoQpRVvt71muvuq5qE-jTFZkK-GLHkhdebmc,26 +setuptools/_vendor/typeguard-4.3.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +setuptools/_vendor/typeguard-4.3.0.dist-info/LICENSE,sha256=YWP3mH37ONa8MgzitwsvArhivEESZRbVUu8c1DJH51g,1130 +setuptools/_vendor/typeguard-4.3.0.dist-info/METADATA,sha256=z2dcHAp0TwhYCFU5Deh8x31nazElgujUz9tbuP0pjSE,3717 +setuptools/_vendor/typeguard-4.3.0.dist-info/RECORD,sha256=SKUZWVgkeDUidUKM7s1473fXmsna55bjmi6vJUAoJVI,2402 +setuptools/_vendor/typeguard-4.3.0.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92 +setuptools/_vendor/typeguard-4.3.0.dist-info/entry_points.txt,sha256=qp7NQ1aLtiSgMQqo6gWlfGpy0IIXzoMJmeQTLpzqFZQ,48 +setuptools/_vendor/typeguard-4.3.0.dist-info/top_level.txt,sha256=4z28AhuDodwRS_c1J_l8H51t5QuwfTseskYzlxp6grs,10 +setuptools/_vendor/typeguard/__init__.py,sha256=Onh4w38elPCjtlcU3JY9k3h70NjsxXIkAflmQn-Z0FY,2071 +setuptools/_vendor/typeguard/__pycache__/__init__.cpython-310.pyc,, +setuptools/_vendor/typeguard/__pycache__/_checkers.cpython-310.pyc,, +setuptools/_vendor/typeguard/__pycache__/_config.cpython-310.pyc,, +setuptools/_vendor/typeguard/__pycache__/_decorators.cpython-310.pyc,, +setuptools/_vendor/typeguard/__pycache__/_exceptions.cpython-310.pyc,, +setuptools/_vendor/typeguard/__pycache__/_functions.cpython-310.pyc,, +setuptools/_vendor/typeguard/__pycache__/_importhook.cpython-310.pyc,, +setuptools/_vendor/typeguard/__pycache__/_memo.cpython-310.pyc,, +setuptools/_vendor/typeguard/__pycache__/_pytest_plugin.cpython-310.pyc,, +setuptools/_vendor/typeguard/__pycache__/_suppression.cpython-310.pyc,, +setuptools/_vendor/typeguard/__pycache__/_transformer.cpython-310.pyc,, +setuptools/_vendor/typeguard/__pycache__/_union_transformer.cpython-310.pyc,, +setuptools/_vendor/typeguard/__pycache__/_utils.cpython-310.pyc,, +setuptools/_vendor/typeguard/_checkers.py,sha256=JRrgKicdOEfIBoNEtegYCEIlhpad-a1u1Em7GCj0WCI,31360 +setuptools/_vendor/typeguard/_config.py,sha256=nIz8QwDa-oFO3L9O8_6srzlmd99pSby2wOM4Wb7F_B0,2846 +setuptools/_vendor/typeguard/_decorators.py,sha256=v6dsIeWvPhExGLP_wXF-RmDUyjZf_Ak28g7gBJ_v0-0,9033 +setuptools/_vendor/typeguard/_exceptions.py,sha256=ZIPeiV-FBd5Emw2EaWd2Fvlsrwi4ocwT2fVGBIAtHcQ,1121 +setuptools/_vendor/typeguard/_functions.py,sha256=ibgSAKa5ptIm1eR9ARG0BSozAFJPFNASZqhPVyQeqig,10393 +setuptools/_vendor/typeguard/_importhook.py,sha256=ugjCDvFcdWMU7UugqlJG91IpVNpEIxtRr-99s0h1k7M,6389 +setuptools/_vendor/typeguard/_memo.py,sha256=1juQV_vxnD2JYKbSrebiQuj4oKHz6n67v9pYA-CCISg,1303 +setuptools/_vendor/typeguard/_pytest_plugin.py,sha256=-fcSqkv54rIfIF8pDavY5YQPkj4OX8GMt_lL7CQSD4I,4416 +setuptools/_vendor/typeguard/_suppression.py,sha256=VQfzxcwIbu3if0f7VBkKM7hkYOA7tNFw9a7jMBsmMg4,2266 +setuptools/_vendor/typeguard/_transformer.py,sha256=9Ha7_QhdwoUni_6hvdY-hZbuEergowHrNL2vzHIakFY,44937 +setuptools/_vendor/typeguard/_union_transformer.py,sha256=v_42r7-6HuRX2SoFwnyJ-E5PlxXpVeUJPJR1-HU9qSo,1354 +setuptools/_vendor/typeguard/_utils.py,sha256=5HhO1rPn5f1M6ymkVAEv7Xmlz1cX-j0OnTMlyHqqrR8,5270 +setuptools/_vendor/typeguard/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/typing_extensions-4.12.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +setuptools/_vendor/typing_extensions-4.12.2.dist-info/LICENSE,sha256=Oy-B_iHRgcSZxZolbI4ZaEVdZonSaaqFNzv7avQdo78,13936 +setuptools/_vendor/typing_extensions-4.12.2.dist-info/METADATA,sha256=BeUQIa8cnYbrjWx-N8TOznM9UGW5Gm2DicVpDtRA8W0,3018 +setuptools/_vendor/typing_extensions-4.12.2.dist-info/RECORD,sha256=dxAALYGXHmMqpqL8M9xddKr118quIgQKZdPjFQOwXuk,571 +setuptools/_vendor/typing_extensions-4.12.2.dist-info/WHEEL,sha256=EZbGkh7Ie4PoZfRQ8I0ZuP9VklN_TvcZ6DSE5Uar4z4,81 +setuptools/_vendor/typing_extensions.py,sha256=gwekpyG9DVG3lxWKX4ni8u7nk3We5slG98mA9F3DJQw,134451 +setuptools/_vendor/wheel-0.45.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +setuptools/_vendor/wheel-0.45.1.dist-info/LICENSE.txt,sha256=MMI2GGeRCPPo6h0qZYx8pBe9_IkcmO8aifpP8MmChlQ,1107 +setuptools/_vendor/wheel-0.45.1.dist-info/METADATA,sha256=mKz84H7m7jsxJyzeIcTVORiTb0NPMV39KvOIYhGgmjA,2313 +setuptools/_vendor/wheel-0.45.1.dist-info/RECORD,sha256=1jnxrHyZPDcVvULyfGFhiba4Z5L9_RsXr9dxcNbhaYQ,4900 +setuptools/_vendor/wheel-0.45.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/wheel-0.45.1.dist-info/WHEEL,sha256=CpUCUxeHQbRN5UGRQHYRJorO5Af-Qy_fHMctcQ8DSGI,82 +setuptools/_vendor/wheel-0.45.1.dist-info/entry_points.txt,sha256=rTY1BbkPHhkGMm4Q3F0pIzJBzW2kMxoG1oriffvGdA0,104 +setuptools/_vendor/wheel/__init__.py,sha256=mrxMnvdXACur_LWegbUfh5g5ysWZrd63UJn890wvGNk,59 +setuptools/_vendor/wheel/__main__.py,sha256=NkMUnuTCGcOkgY0IBLgBCVC_BGGcWORx2K8jYGS12UE,455 +setuptools/_vendor/wheel/__pycache__/__init__.cpython-310.pyc,, +setuptools/_vendor/wheel/__pycache__/__main__.cpython-310.pyc,, +setuptools/_vendor/wheel/__pycache__/_bdist_wheel.cpython-310.pyc,, +setuptools/_vendor/wheel/__pycache__/_setuptools_logging.cpython-310.pyc,, +setuptools/_vendor/wheel/__pycache__/bdist_wheel.cpython-310.pyc,, +setuptools/_vendor/wheel/__pycache__/macosx_libfile.cpython-310.pyc,, +setuptools/_vendor/wheel/__pycache__/metadata.cpython-310.pyc,, +setuptools/_vendor/wheel/__pycache__/util.cpython-310.pyc,, +setuptools/_vendor/wheel/__pycache__/wheelfile.cpython-310.pyc,, +setuptools/_vendor/wheel/_bdist_wheel.py,sha256=UghCQjSH_pVfcZh6oRjzSw_TQhcf3anSx1OkiLSL82M,21694 +setuptools/_vendor/wheel/_setuptools_logging.py,sha256=-5KC-lne0ilOUWIDfOkqapUWGMFZhuKYDIavIZiB5kM,781 +setuptools/_vendor/wheel/bdist_wheel.py,sha256=tpf9WufiSO1RuEMg5oPhIfSG8DMziCZ_4muCKF69Cqo,1107 +setuptools/_vendor/wheel/cli/__init__.py,sha256=Npq6_jKi03dhIcRnmbuFhwviVJxwO0tYEnEhWMv9cJo,4402 +setuptools/_vendor/wheel/cli/__pycache__/__init__.cpython-310.pyc,, +setuptools/_vendor/wheel/cli/__pycache__/convert.cpython-310.pyc,, +setuptools/_vendor/wheel/cli/__pycache__/pack.cpython-310.pyc,, +setuptools/_vendor/wheel/cli/__pycache__/tags.cpython-310.pyc,, +setuptools/_vendor/wheel/cli/__pycache__/unpack.cpython-310.pyc,, +setuptools/_vendor/wheel/cli/convert.py,sha256=Bi0ntEXb9nTllCxWeTRQ4j-nPs3szWSEKipG_GgnMkQ,12634 +setuptools/_vendor/wheel/cli/pack.py,sha256=CAFcHdBVulvsHYJlndKVO7KMI9JqBTZz5ii0PKxxCOs,3103 +setuptools/_vendor/wheel/cli/tags.py,sha256=lHw-LaWrkS5Jy_qWcw-6pSjeNM6yAjDnqKI3E5JTTCU,4760 +setuptools/_vendor/wheel/cli/unpack.py,sha256=Y_J7ynxPSoFFTT7H0fMgbBlVErwyDGcObgme5MBuz58,1021 +setuptools/_vendor/wheel/macosx_libfile.py,sha256=k1x7CE3LPtOVGqj6NXQ1nTGYVPaeRrhVzUG_KPq3zDs,16572 +setuptools/_vendor/wheel/metadata.py,sha256=JC4p7jlQZu2bUTAQ2fevkqLjg_X6gnNyRhLn6OUO1tc,6171 +setuptools/_vendor/wheel/util.py,sha256=aL7aibHwYUgfc8WlolL5tXdkV4DatbJxZHb1kwHFJAU,423 +setuptools/_vendor/wheel/vendored/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/wheel/vendored/__pycache__/__init__.cpython-310.pyc,, +setuptools/_vendor/wheel/vendored/packaging/LICENSE,sha256=ytHvW9NA1z4HS6YU0m996spceUDD2MNIUuZcSQlobEg,197 +setuptools/_vendor/wheel/vendored/packaging/LICENSE.APACHE,sha256=DVQuDIgE45qn836wDaWnYhSdxoLXgpRRKH4RuTjpRZQ,10174 +setuptools/_vendor/wheel/vendored/packaging/LICENSE.BSD,sha256=tw5-m3QvHMb5SLNMFqo5_-zpQZY2S8iP8NIYDwAo-sU,1344 +setuptools/_vendor/wheel/vendored/packaging/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/wheel/vendored/packaging/__pycache__/__init__.cpython-310.pyc,, +setuptools/_vendor/wheel/vendored/packaging/__pycache__/_elffile.cpython-310.pyc,, +setuptools/_vendor/wheel/vendored/packaging/__pycache__/_manylinux.cpython-310.pyc,, +setuptools/_vendor/wheel/vendored/packaging/__pycache__/_musllinux.cpython-310.pyc,, +setuptools/_vendor/wheel/vendored/packaging/__pycache__/_parser.cpython-310.pyc,, +setuptools/_vendor/wheel/vendored/packaging/__pycache__/_structures.cpython-310.pyc,, +setuptools/_vendor/wheel/vendored/packaging/__pycache__/_tokenizer.cpython-310.pyc,, +setuptools/_vendor/wheel/vendored/packaging/__pycache__/markers.cpython-310.pyc,, +setuptools/_vendor/wheel/vendored/packaging/__pycache__/requirements.cpython-310.pyc,, +setuptools/_vendor/wheel/vendored/packaging/__pycache__/specifiers.cpython-310.pyc,, +setuptools/_vendor/wheel/vendored/packaging/__pycache__/tags.cpython-310.pyc,, +setuptools/_vendor/wheel/vendored/packaging/__pycache__/utils.cpython-310.pyc,, +setuptools/_vendor/wheel/vendored/packaging/__pycache__/version.cpython-310.pyc,, +setuptools/_vendor/wheel/vendored/packaging/_elffile.py,sha256=hbmK8OD6Z7fY6hwinHEUcD1by7czkGiNYu7ShnFEk2k,3266 +setuptools/_vendor/wheel/vendored/packaging/_manylinux.py,sha256=P7sdR5_7XBY09LVYYPhHmydMJIIwPXWsh4olk74Uuj4,9588 +setuptools/_vendor/wheel/vendored/packaging/_musllinux.py,sha256=z1s8To2hQ0vpn_d-O2i5qxGwEK8WmGlLt3d_26V7NeY,2674 +setuptools/_vendor/wheel/vendored/packaging/_parser.py,sha256=4tT4emSl2qTaU7VTQE1Xa9o1jMPCsBezsYBxyNMUN-s,10347 +setuptools/_vendor/wheel/vendored/packaging/_structures.py,sha256=q3eVNmbWJGG_S0Dit_S3Ao8qQqz_5PYTXFAKBZe5yr4,1431 +setuptools/_vendor/wheel/vendored/packaging/_tokenizer.py,sha256=alCtbwXhOFAmFGZ6BQ-wCTSFoRAJ2z-ysIf7__MTJ_k,5292 +setuptools/_vendor/wheel/vendored/packaging/markers.py,sha256=_TSPI1BhJYO7Bp9AzTmHQxIqHEVXaTjmDh9G-w8qzPA,8232 +setuptools/_vendor/wheel/vendored/packaging/requirements.py,sha256=dgoBeVprPu2YE6Q8nGfwOPTjATHbRa_ZGLyXhFEln6Q,2933 +setuptools/_vendor/wheel/vendored/packaging/specifiers.py,sha256=IWSt0SrLSP72heWhAC8UL0eGvas7XIQHjqiViVfmPKE,39778 +setuptools/_vendor/wheel/vendored/packaging/tags.py,sha256=fedHXiOHkBxNZTXotXv8uXPmMFU9ae-TKBujgYHigcA,18950 +setuptools/_vendor/wheel/vendored/packaging/utils.py,sha256=XgdmP3yx9-wQEFjO7OvMj9RjEf5JlR5HFFR69v7SQ9E,5268 +setuptools/_vendor/wheel/vendored/packaging/version.py,sha256=PFJaYZDxBgyxkfYhH3SQw4qfE9ICCWrTmitvq14y3bs,16234 +setuptools/_vendor/wheel/vendored/vendor.txt,sha256=Z2ENjB1i5prfez8CdM1Sdr3c6Zxv2rRRolMpLmBncAE,16 +setuptools/_vendor/wheel/wheelfile.py,sha256=USCttNlJwafxt51YYFFKG7jnxz8dfhbyqAZL6jMTA9s,8411 +setuptools/_vendor/zipp-3.19.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +setuptools/_vendor/zipp-3.19.2.dist-info/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023 +setuptools/_vendor/zipp-3.19.2.dist-info/METADATA,sha256=UIrk_kMIHGSwsKKChYizqMw0MMZpPRZ2ZiVpQAsN_bE,3575 +setuptools/_vendor/zipp-3.19.2.dist-info/RECORD,sha256=8xby4D_ZrefrvAsVRwaEjiu4_VaLkJNRCfDY484rm_4,1039 +setuptools/_vendor/zipp-3.19.2.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/zipp-3.19.2.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92 +setuptools/_vendor/zipp-3.19.2.dist-info/top_level.txt,sha256=iAbdoSHfaGqBfVb2XuR9JqSQHCoOsOtG6y9C_LSpqFw,5 +setuptools/_vendor/zipp/__init__.py,sha256=QuI1g00G4fRAcGt-HqbV0oWIkmSgedCGGYsHHYzNa8A,13412 +setuptools/_vendor/zipp/__pycache__/__init__.cpython-310.pyc,, +setuptools/_vendor/zipp/__pycache__/glob.cpython-310.pyc,, +setuptools/_vendor/zipp/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/zipp/compat/__pycache__/__init__.cpython-310.pyc,, +setuptools/_vendor/zipp/compat/__pycache__/py310.cpython-310.pyc,, +setuptools/_vendor/zipp/compat/py310.py,sha256=eZpkW0zRtunkhEh8jjX3gCGe22emoKCBJw72Zt4RkhA,219 +setuptools/_vendor/zipp/glob.py,sha256=etWpnfEoRyfUvrUsi6sTiGmErvPwe6HzY6pT8jg_lUI,3082 +setuptools/archive_util.py,sha256=Tl_64hSTtc4y8x7xa98rFVUbG24oArpjzLAYGYP2_sI,7356 +setuptools/build_meta.py,sha256=3cHAWucJaLA9DU5OfCbKkkteTDiQ5bB4LokfTRMgJT4,19968 +setuptools/cli-32.exe,sha256=MqzBvFQxFsviz_EMuGd3LfLyVP8mNMhwrvC0bEtpb9s,11776 +setuptools/cli-64.exe,sha256=u7PeVwdinmpgoMI4zUd7KPB_AGaYL9qVP6b87DkHOko,14336 +setuptools/cli-arm64.exe,sha256=uafQjaiA36yLz1SOuksG-1m28JsX0zFIoPZhgyiSbGE,13824 +setuptools/cli.exe,sha256=MqzBvFQxFsviz_EMuGd3LfLyVP8mNMhwrvC0bEtpb9s,11776 +setuptools/command/__init__.py,sha256=wdSrlNR0P6nCz9_oFtCAiAkeFJMsZa1jPcpXT53f0SM,803 +setuptools/command/__pycache__/__init__.cpython-310.pyc,, +setuptools/command/__pycache__/_requirestxt.cpython-310.pyc,, +setuptools/command/__pycache__/alias.cpython-310.pyc,, +setuptools/command/__pycache__/bdist_egg.cpython-310.pyc,, +setuptools/command/__pycache__/bdist_rpm.cpython-310.pyc,, +setuptools/command/__pycache__/bdist_wheel.cpython-310.pyc,, +setuptools/command/__pycache__/build.cpython-310.pyc,, +setuptools/command/__pycache__/build_clib.cpython-310.pyc,, +setuptools/command/__pycache__/build_ext.cpython-310.pyc,, +setuptools/command/__pycache__/build_py.cpython-310.pyc,, +setuptools/command/__pycache__/develop.cpython-310.pyc,, +setuptools/command/__pycache__/dist_info.cpython-310.pyc,, +setuptools/command/__pycache__/easy_install.cpython-310.pyc,, +setuptools/command/__pycache__/editable_wheel.cpython-310.pyc,, +setuptools/command/__pycache__/egg_info.cpython-310.pyc,, +setuptools/command/__pycache__/install.cpython-310.pyc,, +setuptools/command/__pycache__/install_egg_info.cpython-310.pyc,, +setuptools/command/__pycache__/install_lib.cpython-310.pyc,, +setuptools/command/__pycache__/install_scripts.cpython-310.pyc,, +setuptools/command/__pycache__/rotate.cpython-310.pyc,, +setuptools/command/__pycache__/saveopts.cpython-310.pyc,, +setuptools/command/__pycache__/sdist.cpython-310.pyc,, +setuptools/command/__pycache__/setopt.cpython-310.pyc,, +setuptools/command/__pycache__/test.cpython-310.pyc,, +setuptools/command/_requirestxt.py,sha256=ItYMTJGh_i5TlQstX_nFopqEhkC4PJFadBL2Zd3V670,4228 +setuptools/command/alias.py,sha256=rDdrMt32DS6qf3K7tjZZyHD_dMKrm77AXcAtx-nBQ0I,2380 +setuptools/command/bdist_egg.py,sha256=3eDucQ4fdeYMsLO9PhBfY1JkcMLhZXgnAI_9FdFNsEE,16972 +setuptools/command/bdist_rpm.py,sha256=LyqI49w48SKk0FmuHsE9MLzX1SuXjL7YMNbZMFZqFII,1435 +setuptools/command/bdist_wheel.py,sha256=_LfGHB7CV_uyncqlOTSETEi2gjVCoPKuAXcyRFoq7Cs,22246 +setuptools/command/build.py,sha256=eI7STMERGGZEpzk1tvJN8p9IOjAAXMcGLzljv2mwI3M,6052 +setuptools/command/build_clib.py,sha256=AbgpPIF_3qL8fZr3JIebI-WHTMTBiMfrFkVQz8K40G4,4528 +setuptools/command/build_ext.py,sha256=bUH4M0NizaJJrv10wK-ZD3uY0TxCSZlYQDhiwwzHslM,18377 +setuptools/command/build_py.py,sha256=DCbjvB18kkL-xUK5rvlzm0C6twTeOxNhyvJDxxa7fII,15539 +setuptools/command/develop.py,sha256=zX22119sI1G1gfJ1gNCE4hkg2zbLKx0uUwvNmC5bIu8,6886 +setuptools/command/dist_info.py,sha256=HU752iLLmmYMHbsDBgz2ubRjkgJobugOp8H71LzzDys,3450 +setuptools/command/easy_install.py,sha256=0Z4kFlE78Ae2AfHXYTxZFUa2t3qlNqXCtQu4J1Nx8iA,87870 +setuptools/command/editable_wheel.py,sha256=3bBipRZA3E4poQ8LEWhMYEjHjCzqU_pIdO86C3t7oNY,35624 +setuptools/command/egg_info.py,sha256=WWUozR3DZCrWsTQhHXOygMiEUcrjLWphET0-Zsocsm4,25982 +setuptools/command/install.py,sha256=MmTGb8m1R8fJ0cc5FTWCF6uq-s1ZJmvpYm-N_CtqEaI,7046 +setuptools/command/install_egg_info.py,sha256=3I9IPCH7D59Sh-6aVYz-h6wwyxq-wkxrKwKg3nDdJqs,2075 +setuptools/command/install_lib.py,sha256=9n1_U83eHcERL_a_rv_LhHCkhXlLdqyZ4SdBow-9qcE,4319 +setuptools/command/install_scripts.py,sha256=tVOCj3e8OTIrkoL_bGbT5pOksdxZfQblH_bdI4DtVV4,2637 +setuptools/command/launcher manifest.xml,sha256=xlLbjWrB01tKC0-hlVkOKkiSPbzMml2eOPtJ_ucCnbE,628 +setuptools/command/rotate.py,sha256=XNd_BEEOWAJHW1FcLTMUWWl4QB6zAuk7b8VWQg3FHos,2187 +setuptools/command/saveopts.py,sha256=Np0PVb7SD7oTbu9Z9sosS7D-CkkIkU7x4glu5Es1tjA,692 +setuptools/command/sdist.py,sha256=JaQm2-ebXI2kvyrBjJKP8yNLPa5eMbMeis88CXBMYlk,7374 +setuptools/command/setopt.py,sha256=xZF2RCc4ABvE9eHHAzF50-fkQg3au8fcRUVVGd58k3U,5100 +setuptools/command/test.py,sha256=k7xcq7D7bEehgxarbw-dW3AtmGZORqz8HjKR6FGJ3jk,1343 +setuptools/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/compat/__pycache__/__init__.cpython-310.pyc,, +setuptools/compat/__pycache__/py310.cpython-310.pyc,, +setuptools/compat/__pycache__/py311.cpython-310.pyc,, +setuptools/compat/__pycache__/py312.cpython-310.pyc,, +setuptools/compat/__pycache__/py39.cpython-310.pyc,, +setuptools/compat/py310.py,sha256=8sqwWczIcrkzeAbhaim4pKVd4tXZdcqmebgdvzji0rc,141 +setuptools/compat/py311.py,sha256=e6tJAFwZEP82hmMBl10HYeSypelo_Ti2wTjKZVKLwOE,790 +setuptools/compat/py312.py,sha256=vYKVtdrdOTsO_R90dJkEXsFwfMJFuIFJflhIgHrjJ-Y,366 +setuptools/compat/py39.py,sha256=BJMtnkfcqyTfccqjYQxfoRtU2nTnWaEESBVkshTiXqY,493 +setuptools/config/NOTICE,sha256=Ld3wiBgpejuJ1D2V_2WdjahXQRCMkTbfo6TYVsBiO9g,493 +setuptools/config/__init__.py,sha256=aiPnL9BJn1O6MfmuNXyn8W2Lp8u9qizRVqwPiOdPIjY,1499 +setuptools/config/__pycache__/__init__.cpython-310.pyc,, +setuptools/config/__pycache__/_apply_pyprojecttoml.cpython-310.pyc,, +setuptools/config/__pycache__/expand.cpython-310.pyc,, +setuptools/config/__pycache__/pyprojecttoml.cpython-310.pyc,, +setuptools/config/__pycache__/setupcfg.cpython-310.pyc,, +setuptools/config/_apply_pyprojecttoml.py,sha256=SUyTw7A2btZ1lBuWKN5o42-Diyv95eGTiYJ3rZOnGSc,19120 +setuptools/config/_validate_pyproject/NOTICE,sha256=XTANv6ZDE4sBO3WsnK7uWR-VG4sO4kKIw0zNkmxHgMg,18737 +setuptools/config/_validate_pyproject/__init__.py,sha256=dnp6T7ePP1R5z4OuC7Fd2dkFlIrtIfizUfvpGJP6nz0,1042 +setuptools/config/_validate_pyproject/__pycache__/__init__.cpython-310.pyc,, +setuptools/config/_validate_pyproject/__pycache__/error_reporting.cpython-310.pyc,, +setuptools/config/_validate_pyproject/__pycache__/extra_validations.cpython-310.pyc,, +setuptools/config/_validate_pyproject/__pycache__/fastjsonschema_exceptions.cpython-310.pyc,, +setuptools/config/_validate_pyproject/__pycache__/fastjsonschema_validations.cpython-310.pyc,, +setuptools/config/_validate_pyproject/__pycache__/formats.cpython-310.pyc,, +setuptools/config/_validate_pyproject/error_reporting.py,sha256=meldD7nBQdolQhvG-43r1Ue-gU1n7ORAJR86vh3Rrvk,11813 +setuptools/config/_validate_pyproject/extra_validations.py,sha256=-GUG5S--ijY8WfXbdXPoHl6ywGsyEF9dtDpenSoJPHg,2858 +setuptools/config/_validate_pyproject/fastjsonschema_exceptions.py,sha256=w749JgqKi8clBFcObdcbZVqsmF4oJ_QByhZ1SGbUFNw,1612 +setuptools/config/_validate_pyproject/fastjsonschema_validations.py,sha256=FihD5ZcM6p77BPZ04CGqh3BEwVNoPMKJZJAyuJpkAU0,354682 +setuptools/config/_validate_pyproject/formats.py,sha256=TETokJBK9hjl-cVg1olsojkJwLxfP7_chgJQNmzAB98,13564 +setuptools/config/distutils.schema.json,sha256=Tcp32kRnhwORGw_9p6GEi08lj2h15tQRzOYBbzGmcBU,972 +setuptools/config/expand.py,sha256=JNAktRCsyyRB-rQodbPnCucmLWqcYvzCDC8Ebn2Z7xM,16041 +setuptools/config/pyprojecttoml.py,sha256=YMu5PdbJJI5azp6kR_boM1mflf5nqOA-InF4s6LnLgw,18320 +setuptools/config/setupcfg.py,sha256=VZDkwE7DYv45SbadJD8CwKrDtiXvjgllL8PYSvoRCyg,26575 +setuptools/config/setuptools.schema.json,sha256=dZBRuSEnZkatoVlt1kVwG8ocTeRdO7BD0xvOWKH54PY,16071 +setuptools/depends.py,sha256=jKYfjmt_2ZQYVghb8L9bU7LJ6erHJ5ze-K_fKV1BMXk,5965 +setuptools/discovery.py,sha256=-42c3XhwzkfodDKKP50C2YBzr11fncAgmUzBdBRb0-Q,21258 +setuptools/dist.py,sha256=RZz7aj9RxqSYriqgFoZOu-7KIV82cmlaMFx9owZrApQ,44897 +setuptools/errors.py,sha256=gY2x2PIaIgy01yRANRC-zcCwxDCqCScgJoCOZFe0yio,3024 +setuptools/extension.py,sha256=KCnv9p3tgm0ZVqtgE451fyILsm4hCyvOiUtOu787D-4,6683 +setuptools/glob.py,sha256=AC_B33DY8g-CHELxDsJrtwFrpiucSAZsakPFdSOQzhc,6062 +setuptools/gui-32.exe,sha256=hdrh6V13hF8stZvKw9Sv50u-TJGpvMW_SnHNQxBNvnw,11776 +setuptools/gui-64.exe,sha256=NHG2FA6txkEid9u-_j_vjDRaDxpZd2CGuAo2GMOoPjs,14336 +setuptools/gui-arm64.exe,sha256=5pT0dDQFyLWSb_RX22_n8aEt7HwWqcOGR4TT9OB64Jc,13824 +setuptools/gui.exe,sha256=hdrh6V13hF8stZvKw9Sv50u-TJGpvMW_SnHNQxBNvnw,11776 +setuptools/installer.py,sha256=_4Wegx4r3L05sMo3-IlqFp-OuxnWyBqjyMZ7LWQXmh8,5110 +setuptools/launch.py,sha256=IBb5lEv69CyuZ9ewIrmKlXh154kdLmP29LKfTMkximE,820 +setuptools/logging.py,sha256=W16iHJ1HcCXYQ0RxyrEfJ83FT4175tCtoYg-E6uSpVI,1261 +setuptools/modified.py,sha256=ZwbfBfCFP88ltvbv_dJDz-t1LsQjnM-JUpgZnnQZjjM,568 +setuptools/monkey.py,sha256=FwMWl2n1v2bHbeqBy-o9g8yUNaAkYFbszCbXe9d5Za8,3717 +setuptools/msvc.py,sha256=vmM0qL4rIzrtD9pia9ZEwtqZ4LbbrgL0dU0EANVYRm8,41631 +setuptools/namespaces.py,sha256=2GGqYY1BNDEhMtBc1rHTv7klgmNVRdksJeW-L1f--ys,3171 +setuptools/package_index.py,sha256=V5hnQtbDy1R6l3dSBNTuMUBvtrQxNPxgmYyXfpSq79U,40299 +setuptools/sandbox.py,sha256=fMqtcOuipHO6RKPh1YB5o7d985dLKo76Whp3vrIei2E,14906 +setuptools/script (dev).tmpl,sha256=RUzQzCQUaXtwdLtYHWYbIQmOaES5Brqq1FvUA_tu-5I,218 +setuptools/script.tmpl,sha256=WGTt5piezO27c-Dbx6l5Q4T3Ff20A5z7872hv3aAhYY,138 +setuptools/tests/__init__.py,sha256=AnBfls2iJbTDQzmMKeLRt-9lxhaOHUVOZEgXv89Uwvs,335 +setuptools/tests/__pycache__/__init__.cpython-310.pyc,, +setuptools/tests/__pycache__/contexts.cpython-310.pyc,, +setuptools/tests/__pycache__/environment.cpython-310.pyc,, +setuptools/tests/__pycache__/fixtures.cpython-310.pyc,, +setuptools/tests/__pycache__/mod_with_constant.cpython-310.pyc,, +setuptools/tests/__pycache__/namespaces.cpython-310.pyc,, +setuptools/tests/__pycache__/script-with-bom.cpython-310.pyc,, +setuptools/tests/__pycache__/server.cpython-310.pyc,, +setuptools/tests/__pycache__/test_archive_util.cpython-310.pyc,, +setuptools/tests/__pycache__/test_bdist_deprecations.cpython-310.pyc,, +setuptools/tests/__pycache__/test_bdist_egg.cpython-310.pyc,, +setuptools/tests/__pycache__/test_bdist_wheel.cpython-310.pyc,, +setuptools/tests/__pycache__/test_build.cpython-310.pyc,, +setuptools/tests/__pycache__/test_build_clib.cpython-310.pyc,, +setuptools/tests/__pycache__/test_build_ext.cpython-310.pyc,, +setuptools/tests/__pycache__/test_build_meta.cpython-310.pyc,, +setuptools/tests/__pycache__/test_build_py.cpython-310.pyc,, +setuptools/tests/__pycache__/test_config_discovery.cpython-310.pyc,, +setuptools/tests/__pycache__/test_core_metadata.cpython-310.pyc,, +setuptools/tests/__pycache__/test_depends.cpython-310.pyc,, +setuptools/tests/__pycache__/test_develop.cpython-310.pyc,, +setuptools/tests/__pycache__/test_dist.cpython-310.pyc,, +setuptools/tests/__pycache__/test_dist_info.cpython-310.pyc,, +setuptools/tests/__pycache__/test_distutils_adoption.cpython-310.pyc,, +setuptools/tests/__pycache__/test_easy_install.cpython-310.pyc,, +setuptools/tests/__pycache__/test_editable_install.cpython-310.pyc,, +setuptools/tests/__pycache__/test_egg_info.cpython-310.pyc,, +setuptools/tests/__pycache__/test_extern.cpython-310.pyc,, +setuptools/tests/__pycache__/test_find_packages.cpython-310.pyc,, +setuptools/tests/__pycache__/test_find_py_modules.cpython-310.pyc,, +setuptools/tests/__pycache__/test_glob.cpython-310.pyc,, +setuptools/tests/__pycache__/test_install_scripts.cpython-310.pyc,, +setuptools/tests/__pycache__/test_logging.cpython-310.pyc,, +setuptools/tests/__pycache__/test_manifest.cpython-310.pyc,, +setuptools/tests/__pycache__/test_namespaces.cpython-310.pyc,, +setuptools/tests/__pycache__/test_packageindex.cpython-310.pyc,, +setuptools/tests/__pycache__/test_sandbox.cpython-310.pyc,, +setuptools/tests/__pycache__/test_sdist.cpython-310.pyc,, +setuptools/tests/__pycache__/test_setopt.cpython-310.pyc,, +setuptools/tests/__pycache__/test_setuptools.cpython-310.pyc,, +setuptools/tests/__pycache__/test_shutil_wrapper.cpython-310.pyc,, +setuptools/tests/__pycache__/test_unicode_utils.cpython-310.pyc,, +setuptools/tests/__pycache__/test_virtualenv.cpython-310.pyc,, +setuptools/tests/__pycache__/test_warnings.cpython-310.pyc,, +setuptools/tests/__pycache__/test_wheel.cpython-310.pyc,, +setuptools/tests/__pycache__/test_windows_wrappers.cpython-310.pyc,, +setuptools/tests/__pycache__/text.cpython-310.pyc,, +setuptools/tests/__pycache__/textwrap.cpython-310.pyc,, +setuptools/tests/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/tests/compat/__pycache__/__init__.cpython-310.pyc,, +setuptools/tests/compat/__pycache__/py39.cpython-310.pyc,, +setuptools/tests/compat/py39.py,sha256=eUy7_F-6KRTOIKl-veshUu6I0EdTSdBZMh0EV0lZ1-g,135 +setuptools/tests/config/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/tests/config/__pycache__/__init__.cpython-310.pyc,, +setuptools/tests/config/__pycache__/test_apply_pyprojecttoml.cpython-310.pyc,, +setuptools/tests/config/__pycache__/test_expand.cpython-310.pyc,, +setuptools/tests/config/__pycache__/test_pyprojecttoml.cpython-310.pyc,, +setuptools/tests/config/__pycache__/test_pyprojecttoml_dynamic_deps.cpython-310.pyc,, +setuptools/tests/config/__pycache__/test_setupcfg.cpython-310.pyc,, +setuptools/tests/config/downloads/__init__.py,sha256=9ixnDEdyL_arKbUzfuiJftAj9bGxKz8M9alOFZMjx9Y,1827 +setuptools/tests/config/downloads/__pycache__/__init__.cpython-310.pyc,, +setuptools/tests/config/downloads/__pycache__/preload.cpython-310.pyc,, +setuptools/tests/config/downloads/preload.py,sha256=sIGGZpY3cmMpMwiJYYYYHG2ifZJkvJgEotRFtiulV1I,450 +setuptools/tests/config/setupcfg_examples.txt,sha256=cAbVvCbkFZuTUL6xRRzRgqyB0rLvJTfvw3D30glo2OE,1912 +setuptools/tests/config/test_apply_pyprojecttoml.py,sha256=l6nE4d8WLU_eSWRic7VSoqeKv9Bi7CZGHcEuB2ehk2w,28807 +setuptools/tests/config/test_expand.py,sha256=S0oT6JvgA_oujR4YS4RUuf5gmOt1CTQV66RQDzV8xd4,8933 +setuptools/tests/config/test_pyprojecttoml.py,sha256=0LefSljUhA6MqtJ5AVzLhomqZcYiFKdu_1ckDeMT1LY,12406 +setuptools/tests/config/test_pyprojecttoml_dynamic_deps.py,sha256=9W73-yLhZJmvCiO4rTiQoBpZT5wNA90Xbd5n2HCshd4,3271 +setuptools/tests/config/test_setupcfg.py,sha256=ZvN-O-2Dgon1adp6oM6il8JWdgT9y196fRvqESU5ELI,33427 +setuptools/tests/contexts.py,sha256=TAdZKxmmodx1ExMVo01o4QpRjpIpo4X3IWKq_BnjxpU,3480 +setuptools/tests/environment.py,sha256=95_UtTaRiuvwYC9eXKEHbn02kDtZysvZq3UZJmPUj1I,3102 +setuptools/tests/fixtures.py,sha256=-V7iD6BeE2E0Rw6dVvTOCm36JG8ZTTnrXhN0GISlgrg,5197 +setuptools/tests/indexes/test_links_priority/external.html,sha256=eL9euOuE93JKZdqlXxBOlHbKwIuNuIdq7GBRpsaPMcU,92 +setuptools/tests/indexes/test_links_priority/simple/foobar/index.html,sha256=DD-TKr7UU4zAjHHz4VexYDNSAzR27levSh1c-k3ZdLE,174 +setuptools/tests/integration/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/tests/integration/__pycache__/__init__.cpython-310.pyc,, +setuptools/tests/integration/__pycache__/helpers.cpython-310.pyc,, +setuptools/tests/integration/__pycache__/test_pip_install_sdist.cpython-310.pyc,, +setuptools/tests/integration/helpers.py,sha256=3PHcS9SCA-fwVJmUP2ad5NQOttJAETI5Nnoc_xroO5k,2522 +setuptools/tests/integration/test_pip_install_sdist.py,sha256=SFbvuYF_hDzt6OtsQ5GjFNnxmoJ_eElfvpYsiyyGJ-g,8256 +setuptools/tests/mod_with_constant.py,sha256=X_Kj80M55w1tmQ4f7uZY91ZTALo4hKVT6EHxgYocUMQ,22 +setuptools/tests/namespaces.py,sha256=HPcI3nR5MCFWXpaADIJ1fwKxymcQgBkuw87Ic5PUSAQ,2774 +setuptools/tests/script-with-bom.py,sha256=hRRgIizEULGiG_ZTNoMY46HhKhxpWfy5FGcD6Qbh5fc,18 +setuptools/tests/server.py,sha256=0FDZf0cSInCP5n1haK7AxHo3jD261RK7D3-RjP-F53k,2397 +setuptools/tests/test_archive_util.py,sha256=buuKdY8XkW26Pe3IKAoBRGHG0MDumnuNoPg2WsAQzIg,845 +setuptools/tests/test_bdist_deprecations.py,sha256=75Xq3gYn79LIIyusEltbHan0bEgAt2e_CaL7KLS8-KQ,775 +setuptools/tests/test_bdist_egg.py,sha256=6PaYN1F3JDbIh1uK0urv7yJFcx98z5dn9SOJ8Mv91l8,1957 +setuptools/tests/test_bdist_wheel.py,sha256=dZ9a7OT_UyRvLnoCi2KGEIbtzhEQjM3YutYMA6ZCezs,23083 +setuptools/tests/test_build.py,sha256=wJgMz2hwHADcLFg-nXrwRVhus7hjmAeEGgrpIQwCGnA,798 +setuptools/tests/test_build_clib.py,sha256=bX51XRAf4uO7IuHFpjePnoK8mE74N2gsoeEqF-ofgws,3123 +setuptools/tests/test_build_ext.py,sha256=e4ZSxsYPB5zq1KSqGEuATZ0t0PJQzMhjjkKJ-hIjcgc,10099 +setuptools/tests/test_build_meta.py,sha256=kvi0Bn4p9DBVme3zyWQsn3QgB9oPdq8S15agj1m69L0,33289 +setuptools/tests/test_build_py.py,sha256=gobME_Cvzf6Ugxq70iWfXekb_xyyT61khwjFq8zkwfw,14186 +setuptools/tests/test_config_discovery.py,sha256=FqV-lOtkqaI-ayzU2zocSdD5TaRAgCZnixNDilKA6FQ,22580 +setuptools/tests/test_core_metadata.py,sha256=vbVJ5_Lsx_hsO_GdB6nQEXJRjA2ydx6_qSbr5LpheAA,20881 +setuptools/tests/test_depends.py,sha256=yQBXoQbNQlJit6mbRVoz6Bb553f3sNrq02lZimNz5XY,424 +setuptools/tests/test_develop.py,sha256=CLzXZ8-b5-VFTuau4P4yXEdLx1UdyTFcOfrV0qyUIdE,5142 +setuptools/tests/test_dist.py,sha256=GFjyL2etAxvVM3q7NhFEGcXS5gyKj8VzbqcbKzpqbOk,8901 +setuptools/tests/test_dist_info.py,sha256=5kBRj9tuBsVreBsY22H2feMO_JQZsSoOZMU_MJfUevY,7077 +setuptools/tests/test_distutils_adoption.py,sha256=_eynrOfyEqXFEmjUJhzpe8GXPyTUPvNSObs4qAAmBy8,5987 +setuptools/tests/test_easy_install.py,sha256=jx4lpFyee0G432cdnwBow3AkL4ibw-0QILwldwv5SCI,53534 +setuptools/tests/test_editable_install.py,sha256=7eTEtpT0k7QeVyZg64eh3kZn-SjckuB9LcokOuV37DI,43383 +setuptools/tests/test_egg_info.py,sha256=QCzoUOkFocmbkwS6XU7F8WNzKE8CGEMRxYBqKLgfUrc,44866 +setuptools/tests/test_extern.py,sha256=rpKU6oCcksumLwf5TeKlDluFQ0TUfbPwTLQbpxcFrCU,296 +setuptools/tests/test_find_packages.py,sha256=CTLAcTzWGWBLCcd2aAsUVkvO3ibrlqexFBdDKOWPoq8,7819 +setuptools/tests/test_find_py_modules.py,sha256=zQjuhIG5TQN2SJPix9ARo4DL_w84Ln8QsHDUjjbrtAQ,2404 +setuptools/tests/test_glob.py,sha256=P3JvpH-kXQ4BZ3zvRF-zKxOgwyWzwIaQIz0WHdxS0kk,887 +setuptools/tests/test_install_scripts.py,sha256=scIrJ6a_ssKqg4vIBNaUjmAKHEYLUUZ9WKnPeKnE6gc,3433 +setuptools/tests/test_logging.py,sha256=zlE5DlldukC7Jc54FNvDV_7ux3ErAkrfrN5CSsnNOUQ,2099 +setuptools/tests/test_manifest.py,sha256=eMg65pIA52DizB6mpktSU-b8CjwaNCS5MSgL_V1LrFI,18562 +setuptools/tests/test_namespaces.py,sha256=Y6utoe5PHHqL_DlgawqB9F8XpsUDPvvw1sQMenK04e0,4515 +setuptools/tests/test_packageindex.py,sha256=qEjLHpSu2gAkegwEstzHQT-Om1uQIYjA8zeNzEX79uo,8775 +setuptools/tests/test_sandbox.py,sha256=shUWE7fLTWe7Jzdfi6NheBWauG3oUukbUV46cArD0u0,4330 +setuptools/tests/test_sdist.py,sha256=RYLvPa_nfyC1ZmoinzqMzJynTDG4RtPYC19_0LU6pvs,32872 +setuptools/tests/test_setopt.py,sha256=3VxxM4ATfP-P4AGnDjoWCnHr5-i9CSEQTFYU1-FTnvI,1365 +setuptools/tests/test_setuptools.py,sha256=_eIhqKf45-OtHqxRf20KndOZJlJdS0PuFLXBO3M-LN8,9008 +setuptools/tests/test_shutil_wrapper.py,sha256=g15E11PtZxG-InB2BWNFyH-svObXx2XcMhgMLJPuFnc,641 +setuptools/tests/test_unicode_utils.py,sha256=xWfEEl8jkQCt9othUTXJfFmdyATAFggJs2tTxjbumbw,316 +setuptools/tests/test_virtualenv.py,sha256=g-njC_9JTAs1YVx_1dGJ_Q6RlInO4qKVu9-XAgNb6TY,3730 +setuptools/tests/test_warnings.py,sha256=zwR2zcnCeCeDqILZlJOPAcuyPHoDvGu1OtOVYiLMk74,3347 +setuptools/tests/test_wheel.py,sha256=J-83W1KdXTgAjFZE3H-ytohhvDE1iqdbE5YF5jLQlGQ,19370 +setuptools/tests/test_windows_wrappers.py,sha256=aF6UTowN3yzCgdBh9nDQVvYIfSYogrTK776TEyXEBqg,7881 +setuptools/tests/text.py,sha256=a12197pMVTvB6FAWQ0ujT8fIQiLIWJlFAl1UCaDUDfg,123 +setuptools/tests/textwrap.py,sha256=FNNNq_MiaEJx88PnsbJQIRxmj1qmgcAOCXXRsODPJN4,98 +setuptools/unicode_utils.py,sha256=ukMGh8pEAw6F_Ezb-K5D3c-078RgA_GcF0oW6lg4lSs,3189 +setuptools/version.py,sha256=WJCeUuyq74Aok2TeK9-OexZOu8XrlQy7-y0BEuWNovQ,161 +setuptools/warnings.py,sha256=oY0Se5eOqje_FEyjTgonUc0XGwgsrI5cgm1kkwulz_w,3796 +setuptools/wheel.py,sha256=xkAtvgm7uPTyYV2zqVmQ0wA8kLwOyRT2Jes1zAy07Ks,8624 +setuptools/windows_support.py,sha256=wW4IYLM1Bv7Z1MaauP2xmPjyy-wkmQnXdyvXscAf9fw,726 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools-79.0.1.dist-info/REQUESTED b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools-79.0.1.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools-79.0.1.dist-info/WHEEL b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools-79.0.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..8acb95590701b87bf84eec079cf4e3989f63b098 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools-79.0.1.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (79.0.1) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools-79.0.1.dist-info/entry_points.txt b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools-79.0.1.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..0db0a6c8f1b8d9c0ad4a25db6892e29f8988fcf2 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools-79.0.1.dist-info/entry_points.txt @@ -0,0 +1,51 @@ +[distutils.commands] +alias = setuptools.command.alias:alias +bdist_egg = setuptools.command.bdist_egg:bdist_egg +bdist_rpm = setuptools.command.bdist_rpm:bdist_rpm +bdist_wheel = setuptools.command.bdist_wheel:bdist_wheel +build = setuptools.command.build:build +build_clib = setuptools.command.build_clib:build_clib +build_ext = setuptools.command.build_ext:build_ext +build_py = setuptools.command.build_py:build_py +develop = setuptools.command.develop:develop +dist_info = setuptools.command.dist_info:dist_info +easy_install = setuptools.command.easy_install:easy_install +editable_wheel = setuptools.command.editable_wheel:editable_wheel +egg_info = setuptools.command.egg_info:egg_info +install = setuptools.command.install:install +install_egg_info = setuptools.command.install_egg_info:install_egg_info +install_lib = setuptools.command.install_lib:install_lib +install_scripts = setuptools.command.install_scripts:install_scripts +rotate = setuptools.command.rotate:rotate +saveopts = setuptools.command.saveopts:saveopts +sdist = setuptools.command.sdist:sdist +setopt = setuptools.command.setopt:setopt + +[distutils.setup_keywords] +dependency_links = setuptools.dist:assert_string_list +eager_resources = setuptools.dist:assert_string_list +entry_points = setuptools.dist:check_entry_points +exclude_package_data = setuptools.dist:check_package_data +extras_require = setuptools.dist:check_extras +include_package_data = setuptools.dist:assert_bool +install_requires = setuptools.dist:check_requirements +namespace_packages = setuptools.dist:check_nsp +package_data = setuptools.dist:check_package_data +packages = setuptools.dist:check_packages +python_requires = setuptools.dist:check_specifier +setup_requires = setuptools.dist:check_requirements +use_2to3 = setuptools.dist:invalid_unless_false +zip_safe = setuptools.dist:assert_bool + +[egg_info.writers] +PKG-INFO = setuptools.command.egg_info:write_pkg_info +dependency_links.txt = setuptools.command.egg_info:overwrite_arg +eager_resources.txt = setuptools.command.egg_info:overwrite_arg +entry_points.txt = setuptools.command.egg_info:write_entries +namespace_packages.txt = setuptools.command.egg_info:overwrite_arg +requires.txt = setuptools.command.egg_info:write_requirements +top_level.txt = setuptools.command.egg_info:write_toplevel_names + +[setuptools.finalize_distribution_options] +keywords = setuptools.dist:Distribution._finalize_setup_keywords +parent_finalize = setuptools.dist:_Distribution.finalize_options diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools-79.0.1.dist-info/top_level.txt b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools-79.0.1.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..b5ac1070294b478b7cc2ce677207ee08813bfa37 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools-79.0.1.dist-info/top_level.txt @@ -0,0 +1,3 @@ +_distutils_hack +pkg_resources +setuptools diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..64464dfaa38a82e9647a095263d70f12961a1f92 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/__init__.py @@ -0,0 +1,286 @@ +"""Extensions to the 'distutils' for large or complex distributions""" +# mypy: disable_error_code=override +# Command.reinitialize_command has an extra **kw param that distutils doesn't have +# Can't disable on the exact line because distutils doesn't exists on Python 3.12 +# and mypy isn't aware of distutils_hack, causing distutils.core.Command to be Any, +# and a [unused-ignore] to be raised on 3.12+ + +from __future__ import annotations + +import functools +import os +import re +import sys +from abc import abstractmethod +from collections.abc import Mapping +from typing import TYPE_CHECKING, TypeVar, overload + +sys.path.extend(((vendor_path := os.path.join(os.path.dirname(os.path.dirname(__file__)), 'setuptools', '_vendor')) not in sys.path) * [vendor_path]) # fmt: skip +# workaround for #4476 +sys.modules.pop('backports', None) + +import _distutils_hack.override # noqa: F401 + +from . import logging, monkey +from .depends import Require +from .discovery import PackageFinder, PEP420PackageFinder +from .dist import Distribution +from .extension import Extension +from .version import __version__ as __version__ +from .warnings import SetuptoolsDeprecationWarning + +import distutils.core +from distutils.errors import DistutilsOptionError + +__all__ = [ + 'setup', + 'Distribution', + 'Command', + 'Extension', + 'Require', + 'SetuptoolsDeprecationWarning', + 'find_packages', + 'find_namespace_packages', +] + +_CommandT = TypeVar("_CommandT", bound="_Command") + +bootstrap_install_from = None + +find_packages = PackageFinder.find +find_namespace_packages = PEP420PackageFinder.find + + +def _install_setup_requires(attrs): + # Note: do not use `setuptools.Distribution` directly, as + # our PEP 517 backend patch `distutils.core.Distribution`. + class MinimalDistribution(distutils.core.Distribution): + """ + A minimal version of a distribution for supporting the + fetch_build_eggs interface. + """ + + def __init__(self, attrs: Mapping[str, object]) -> None: + _incl = 'dependency_links', 'setup_requires' + filtered = {k: attrs[k] for k in set(_incl) & set(attrs)} + super().__init__(filtered) + # Prevent accidentally triggering discovery with incomplete set of attrs + self.set_defaults._disable() + + def _get_project_config_files(self, filenames=None): + """Ignore ``pyproject.toml``, they are not related to setup_requires""" + try: + cfg, _toml = super()._split_standard_project_metadata(filenames) + except Exception: + return filenames, () + return cfg, () + + def finalize_options(self): + """ + Disable finalize_options to avoid building the working set. + Ref #2158. + """ + + dist = MinimalDistribution(attrs) + + # Honor setup.cfg's options. + dist.parse_config_files(ignore_option_errors=True) + if dist.setup_requires: + _fetch_build_eggs(dist) + + +def _fetch_build_eggs(dist: Distribution): + try: + dist.fetch_build_eggs(dist.setup_requires) + except Exception as ex: + msg = """ + It is possible a package already installed in your system + contains an version that is invalid according to PEP 440. + You can try `pip install --use-pep517` as a workaround for this problem, + or rely on a new virtual environment. + + If the problem refers to a package that is not installed yet, + please contact that package's maintainers or distributors. + """ + if "InvalidVersion" in ex.__class__.__name__: + if hasattr(ex, "add_note"): + ex.add_note(msg) # PEP 678 + else: + dist.announce(f"\n{msg}\n") + raise + + +def setup(**attrs): + logging.configure() + # Make sure we have any requirements needed to interpret 'attrs'. + _install_setup_requires(attrs) + return distutils.core.setup(**attrs) + + +setup.__doc__ = distutils.core.setup.__doc__ + +if TYPE_CHECKING: + # Work around a mypy issue where type[T] can't be used as a base: https://github.com/python/mypy/issues/10962 + from distutils.core import Command as _Command +else: + _Command = monkey.get_unpatched(distutils.core.Command) + + +class Command(_Command): + """ + Setuptools internal actions are organized using a *command design pattern*. + This means that each action (or group of closely related actions) executed during + the build should be implemented as a ``Command`` subclass. + + These commands are abstractions and do not necessarily correspond to a command that + can (or should) be executed via a terminal, in a CLI fashion (although historically + they would). + + When creating a new command from scratch, custom defined classes **SHOULD** inherit + from ``setuptools.Command`` and implement a few mandatory methods. + Between these mandatory methods, are listed: + :meth:`initialize_options`, :meth:`finalize_options` and :meth:`run`. + + A useful analogy for command classes is to think of them as subroutines with local + variables called "options". The options are "declared" in :meth:`initialize_options` + and "defined" (given their final values, aka "finalized") in :meth:`finalize_options`, + both of which must be defined by every command class. The "body" of the subroutine, + (where it does all the work) is the :meth:`run` method. + Between :meth:`initialize_options` and :meth:`finalize_options`, ``setuptools`` may set + the values for options/attributes based on user's input (or circumstance), + which means that the implementation should be careful to not overwrite values in + :meth:`finalize_options` unless necessary. + + Please note that other commands (or other parts of setuptools) may also overwrite + the values of the command's options/attributes multiple times during the build + process. + Therefore it is important to consistently implement :meth:`initialize_options` and + :meth:`finalize_options`. For example, all derived attributes (or attributes that + depend on the value of other attributes) **SHOULD** be recomputed in + :meth:`finalize_options`. + + When overwriting existing commands, custom defined classes **MUST** abide by the + same APIs implemented by the original class. They also **SHOULD** inherit from the + original class. + """ + + command_consumes_arguments = False + distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution + + def __init__(self, dist: Distribution, **kw) -> None: + """ + Construct the command for dist, updating + vars(self) with any keyword parameters. + """ + super().__init__(dist) + vars(self).update(kw) + + def _ensure_stringlike(self, option, what, default=None): + val = getattr(self, option) + if val is None: + setattr(self, option, default) + return default + elif not isinstance(val, str): + raise DistutilsOptionError(f"'{option}' must be a {what} (got `{val}`)") + return val + + def ensure_string_list(self, option: str) -> None: + r"""Ensure that 'option' is a list of strings. If 'option' is + currently a string, we split it either on /,\s*/ or /\s+/, so + "foo bar baz", "foo,bar,baz", and "foo, bar baz" all become + ["foo", "bar", "baz"]. + + .. + TODO: This method seems to be similar to the one in ``distutils.cmd`` + Probably it is just here for backward compatibility with old Python versions? + + :meta private: + """ + val = getattr(self, option) + if val is None: + return + elif isinstance(val, str): + setattr(self, option, re.split(r',\s*|\s+', val)) + else: + if isinstance(val, list): + ok = all(isinstance(v, str) for v in val) + else: + ok = False + if not ok: + raise DistutilsOptionError( + f"'{option}' must be a list of strings (got {val!r})" + ) + + @overload + def reinitialize_command( + self, command: str, reinit_subcommands: bool = False, **kw + ) -> _Command: ... + @overload + def reinitialize_command( + self, command: _CommandT, reinit_subcommands: bool = False, **kw + ) -> _CommandT: ... + def reinitialize_command( + self, command: str | _Command, reinit_subcommands: bool = False, **kw + ) -> _Command: + cmd = _Command.reinitialize_command(self, command, reinit_subcommands) + vars(cmd).update(kw) + return cmd # pyright: ignore[reportReturnType] # pypa/distutils#307 + + @abstractmethod + def initialize_options(self) -> None: + """ + Set or (reset) all options/attributes/caches used by the command + to their default values. Note that these values may be overwritten during + the build. + """ + raise NotImplementedError + + @abstractmethod + def finalize_options(self) -> None: + """ + Set final values for all options/attributes used by the command. + Most of the time, each option/attribute/cache should only be set if it does not + have any value yet (e.g. ``if self.attr is None: self.attr = val``). + """ + raise NotImplementedError + + @abstractmethod + def run(self) -> None: + """ + Execute the actions intended by the command. + (Side effects **SHOULD** only take place when :meth:`run` is executed, + for example, creating new files or writing to the terminal output). + """ + raise NotImplementedError + + +def _find_all_simple(path): + """ + Find all files under 'path' + """ + results = ( + os.path.join(base, file) + for base, dirs, files in os.walk(path, followlinks=True) + for file in files + ) + return filter(os.path.isfile, results) + + +def findall(dir=os.curdir): + """ + Find all files under 'dir' and return the list of full filenames. + Unless dir is '.', return full filenames with dir prepended. + """ + files = _find_all_simple(dir) + if dir == os.curdir: + make_rel = functools.partial(os.path.relpath, start=dir) + files = map(make_rel, files) + return list(files) + + +class sic(str): + """Treat this string as-is (https://en.wikipedia.org/wiki/Sic)""" + + +# Apply monkey patches +monkey.patch_all() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/_core_metadata.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/_core_metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..a52d5cf755cdd6a502e752c2f7a3afa3b25897d5 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/_core_metadata.py @@ -0,0 +1,337 @@ +""" +Handling of Core Metadata for Python packages (including reading and writing). + +See: https://packaging.python.org/en/latest/specifications/core-metadata/ +""" + +from __future__ import annotations + +import os +import stat +import textwrap +from email import message_from_file +from email.message import Message +from tempfile import NamedTemporaryFile + +from packaging.markers import Marker +from packaging.requirements import Requirement +from packaging.utils import canonicalize_name, canonicalize_version +from packaging.version import Version + +from . import _normalization, _reqs +from ._static import is_static +from .warnings import SetuptoolsDeprecationWarning + +from distutils.util import rfc822_escape + + +def get_metadata_version(self): + mv = getattr(self, 'metadata_version', None) + if mv is None: + mv = Version('2.4') + self.metadata_version = mv + return mv + + +def rfc822_unescape(content: str) -> str: + """Reverse RFC-822 escaping by removing leading whitespaces from content.""" + lines = content.splitlines() + if len(lines) == 1: + return lines[0].lstrip() + return '\n'.join((lines[0].lstrip(), textwrap.dedent('\n'.join(lines[1:])))) + + +def _read_field_from_msg(msg: Message, field: str) -> str | None: + """Read Message header field.""" + value = msg[field] + if value == 'UNKNOWN': + return None + return value + + +def _read_field_unescaped_from_msg(msg: Message, field: str) -> str | None: + """Read Message header field and apply rfc822_unescape.""" + value = _read_field_from_msg(msg, field) + if value is None: + return value + return rfc822_unescape(value) + + +def _read_list_from_msg(msg: Message, field: str) -> list[str] | None: + """Read Message header field and return all results as list.""" + values = msg.get_all(field, None) + if values == []: + return None + return values + + +def _read_payload_from_msg(msg: Message) -> str | None: + value = str(msg.get_payload()).strip() + if value == 'UNKNOWN' or not value: + return None + return value + + +def read_pkg_file(self, file): + """Reads the metadata values from a file object.""" + msg = message_from_file(file) + + self.metadata_version = Version(msg['metadata-version']) + self.name = _read_field_from_msg(msg, 'name') + self.version = _read_field_from_msg(msg, 'version') + self.description = _read_field_from_msg(msg, 'summary') + # we are filling author only. + self.author = _read_field_from_msg(msg, 'author') + self.maintainer = None + self.author_email = _read_field_from_msg(msg, 'author-email') + self.maintainer_email = None + self.url = _read_field_from_msg(msg, 'home-page') + self.download_url = _read_field_from_msg(msg, 'download-url') + self.license = _read_field_unescaped_from_msg(msg, 'license') + self.license_expression = _read_field_unescaped_from_msg(msg, 'license-expression') + + self.long_description = _read_field_unescaped_from_msg(msg, 'description') + if self.long_description is None and self.metadata_version >= Version('2.1'): + self.long_description = _read_payload_from_msg(msg) + self.description = _read_field_from_msg(msg, 'summary') + + if 'keywords' in msg: + self.keywords = _read_field_from_msg(msg, 'keywords').split(',') + + self.platforms = _read_list_from_msg(msg, 'platform') + self.classifiers = _read_list_from_msg(msg, 'classifier') + + # PEP 314 - these fields only exist in 1.1 + if self.metadata_version == Version('1.1'): + self.requires = _read_list_from_msg(msg, 'requires') + self.provides = _read_list_from_msg(msg, 'provides') + self.obsoletes = _read_list_from_msg(msg, 'obsoletes') + else: + self.requires = None + self.provides = None + self.obsoletes = None + + self.license_files = _read_list_from_msg(msg, 'license-file') + + +def single_line(val): + """ + Quick and dirty validation for Summary pypa/setuptools#1390. + """ + if '\n' in val: + # TODO: Replace with `raise ValueError("newlines not allowed")` + # after reviewing #2893. + msg = "newlines are not allowed in `summary` and will break in the future" + SetuptoolsDeprecationWarning.emit("Invalid config.", msg) + # due_date is undefined. Controversial change, there was a lot of push back. + val = val.strip().split('\n')[0] + return val + + +def write_pkg_info(self, base_dir): + """Write the PKG-INFO file into the release tree.""" + temp = "" + final = os.path.join(base_dir, 'PKG-INFO') + try: + # Use a temporary file while writing to avoid race conditions + # (e.g. `importlib.metadata` reading `.egg-info/PKG-INFO`): + with NamedTemporaryFile("w", encoding="utf-8", dir=base_dir, delete=False) as f: + temp = f.name + self.write_pkg_file(f) + permissions = stat.S_IMODE(os.lstat(temp).st_mode) + os.chmod(temp, permissions | stat.S_IRGRP | stat.S_IROTH) + os.replace(temp, final) # atomic operation. + finally: + if temp and os.path.exists(temp): + os.remove(temp) + + +# Based on Python 3.5 version +def write_pkg_file(self, file): # noqa: C901 # is too complex (14) # FIXME + """Write the PKG-INFO format data to a file object.""" + version = self.get_metadata_version() + + def write_field(key, value): + file.write(f"{key}: {value}\n") + + write_field('Metadata-Version', str(version)) + write_field('Name', self.get_name()) + write_field('Version', self.get_version()) + + summary = self.get_description() + if summary: + write_field('Summary', single_line(summary)) + + optional_fields = ( + ('Home-page', 'url'), + ('Download-URL', 'download_url'), + ('Author', 'author'), + ('Author-email', 'author_email'), + ('Maintainer', 'maintainer'), + ('Maintainer-email', 'maintainer_email'), + ) + + for field, attr in optional_fields: + attr_val = getattr(self, attr, None) + if attr_val is not None: + write_field(field, attr_val) + + if license_expression := self.license_expression: + write_field('License-Expression', license_expression) + elif license := self.get_license(): + write_field('License', rfc822_escape(license)) + + for label, url in self.project_urls.items(): + write_field('Project-URL', f'{label}, {url}') + + keywords = ','.join(self.get_keywords()) + if keywords: + write_field('Keywords', keywords) + + platforms = self.get_platforms() or [] + for platform in platforms: + write_field('Platform', platform) + + self._write_list(file, 'Classifier', self.get_classifiers()) + + # PEP 314 + self._write_list(file, 'Requires', self.get_requires()) + self._write_list(file, 'Provides', self.get_provides()) + self._write_list(file, 'Obsoletes', self.get_obsoletes()) + + # Setuptools specific for PEP 345 + if hasattr(self, 'python_requires'): + write_field('Requires-Python', self.python_requires) + + # PEP 566 + if self.long_description_content_type: + write_field('Description-Content-Type', self.long_description_content_type) + + safe_license_files = map(_safe_license_file, self.license_files or []) + self._write_list(file, 'License-File', safe_license_files) + _write_requirements(self, file) + + for field, attr in _POSSIBLE_DYNAMIC_FIELDS.items(): + if (val := getattr(self, attr, None)) and not is_static(val): + write_field('Dynamic', field) + + long_description = self.get_long_description() + if long_description: + file.write(f"\n{long_description}") + if not long_description.endswith("\n"): + file.write("\n") + + +def _write_requirements(self, file): + for req in _reqs.parse(self.install_requires): + file.write(f"Requires-Dist: {req}\n") + + processed_extras = {} + for augmented_extra, reqs in self.extras_require.items(): + # Historically, setuptools allows "augmented extras": `:` + unsafe_extra, _, condition = augmented_extra.partition(":") + unsafe_extra = unsafe_extra.strip() + extra = _normalization.safe_extra(unsafe_extra) + + if extra: + _write_provides_extra(file, processed_extras, extra, unsafe_extra) + for req in _reqs.parse_strings(reqs): + r = _include_extra(req, extra, condition.strip()) + file.write(f"Requires-Dist: {r}\n") + + return processed_extras + + +def _include_extra(req: str, extra: str, condition: str) -> Requirement: + r = Requirement(req) # create a fresh object that can be modified + parts = ( + f"({r.marker})" if r.marker else None, + f"({condition})" if condition else None, + f"extra == {extra!r}" if extra else None, + ) + r.marker = Marker(" and ".join(x for x in parts if x)) + return r + + +def _write_provides_extra(file, processed_extras, safe, unsafe): + previous = processed_extras.get(safe) + if previous == unsafe: + SetuptoolsDeprecationWarning.emit( + 'Ambiguity during "extra" normalization for dependencies.', + f""" + {previous!r} and {unsafe!r} normalize to the same value:\n + {safe!r}\n + In future versions, setuptools might halt the build process. + """, + see_url="https://peps.python.org/pep-0685/", + ) + else: + processed_extras[safe] = unsafe + file.write(f"Provides-Extra: {safe}\n") + + +# from pypa/distutils#244; needed only until that logic is always available +def get_fullname(self): + return _distribution_fullname(self.get_name(), self.get_version()) + + +def _distribution_fullname(name: str, version: str) -> str: + """ + >>> _distribution_fullname('setup.tools', '1.0-2') + 'setup_tools-1.0.post2' + >>> _distribution_fullname('setup-tools', '1.2post2') + 'setup_tools-1.2.post2' + >>> _distribution_fullname('setup-tools', '1.0-r2') + 'setup_tools-1.0.post2' + >>> _distribution_fullname('setup.tools', '1.0.post') + 'setup_tools-1.0.post0' + >>> _distribution_fullname('setup.tools', '1.0+ubuntu-1') + 'setup_tools-1.0+ubuntu.1' + """ + return "{}-{}".format( + canonicalize_name(name).replace('-', '_'), + canonicalize_version(version, strip_trailing_zero=False), + ) + + +def _safe_license_file(file): + # XXX: Do we need this after the deprecation discussed in #4892, #4896?? + normalized = os.path.normpath(file).replace(os.sep, "/") + if "../" in normalized: + return os.path.basename(normalized) # Temporarily restore pre PEP639 behaviour + return normalized + + +_POSSIBLE_DYNAMIC_FIELDS = { + # Core Metadata Field x related Distribution attribute + "author": "author", + "author-email": "author_email", + "classifier": "classifiers", + "description": "long_description", + "description-content-type": "long_description_content_type", + "download-url": "download_url", + "home-page": "url", + "keywords": "keywords", + "license": "license", + # XXX: License-File is complicated because the user gives globs that are expanded + # during the build. Without special handling it is likely always + # marked as Dynamic, which is an acceptable outcome according to: + # https://github.com/pypa/setuptools/issues/4629#issuecomment-2331233677 + "license-file": "license_files", + "license-expression": "license_expression", # PEP 639 + "maintainer": "maintainer", + "maintainer-email": "maintainer_email", + "obsoletes": "obsoletes", + # "obsoletes-dist": "obsoletes_dist", # NOT USED + "platform": "platforms", + "project-url": "project_urls", + "provides": "provides", + # "provides-dist": "provides_dist", # NOT USED + "provides-extra": "extras_require", + "requires": "requires", + "requires-dist": "install_requires", + # "requires-external": "requires_external", # NOT USED + "requires-python": "python_requires", + "summary": "description", + # "supported-platform": "supported_platforms", # NOT USED +} diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/_entry_points.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/_entry_points.py new file mode 100644 index 0000000000000000000000000000000000000000..e785fc7df8d51241a38675902fe5e5b78a0cc29c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/_entry_points.py @@ -0,0 +1,90 @@ +import functools +import itertools +import operator + +from jaraco.functools import pass_none +from jaraco.text import yield_lines +from more_itertools import consume + +from ._importlib import metadata +from ._itertools import ensure_unique +from .errors import OptionError + + +def ensure_valid(ep): + """ + Exercise one of the dynamic properties to trigger + the pattern match. + """ + try: + ep.extras + except (AttributeError, AssertionError) as ex: + # Why both? See https://github.com/python/importlib_metadata/issues/488 + msg = ( + f"Problems to parse {ep}.\nPlease ensure entry-point follows the spec: " + "https://packaging.python.org/en/latest/specifications/entry-points/" + ) + raise OptionError(msg) from ex + + +def load_group(value, group): + """ + Given a value of an entry point or series of entry points, + return each as an EntryPoint. + """ + # normalize to a single sequence of lines + lines = yield_lines(value) + text = f'[{group}]\n' + '\n'.join(lines) + return metadata.EntryPoints._from_text(text) + + +def by_group_and_name(ep): + return ep.group, ep.name + + +def validate(eps: metadata.EntryPoints): + """ + Ensure entry points are unique by group and name and validate each. + """ + consume(map(ensure_valid, ensure_unique(eps, key=by_group_and_name))) + return eps + + +@functools.singledispatch +def load(eps): + """ + Given a Distribution.entry_points, produce EntryPoints. + """ + groups = itertools.chain.from_iterable( + load_group(value, group) for group, value in eps.items() + ) + return validate(metadata.EntryPoints(groups)) + + +@load.register(str) +def _(eps): + r""" + >>> ep, = load('[console_scripts]\nfoo=bar') + >>> ep.group + 'console_scripts' + >>> ep.name + 'foo' + >>> ep.value + 'bar' + """ + return validate(metadata.EntryPoints(metadata.EntryPoints._from_text(eps))) + + +load.register(type(None), lambda x: x) + + +@pass_none +def render(eps: metadata.EntryPoints): + by_group = operator.attrgetter('group') + groups = itertools.groupby(sorted(eps, key=by_group), by_group) + + return '\n'.join(f'[{group}]\n{render_items(items)}\n' for group, items in groups) + + +def render_items(eps): + return '\n'.join(f'{ep.name} = {ep.value}' for ep in sorted(eps)) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/_imp.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/_imp.py new file mode 100644 index 0000000000000000000000000000000000000000..f1d9f29218987d4f830f2d57aca9e3f74d00a095 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/_imp.py @@ -0,0 +1,87 @@ +""" +Re-implementation of find_module and get_frozen_object +from the deprecated imp module. +""" + +import importlib.machinery +import importlib.util +import os +import tokenize +from importlib.util import module_from_spec + +PY_SOURCE = 1 +PY_COMPILED = 2 +C_EXTENSION = 3 +C_BUILTIN = 6 +PY_FROZEN = 7 + + +def find_spec(module, paths): + finder = ( + importlib.machinery.PathFinder().find_spec + if isinstance(paths, list) + else importlib.util.find_spec + ) + return finder(module, paths) + + +def find_module(module, paths=None): + """Just like 'imp.find_module()', but with package support""" + spec = find_spec(module, paths) + if spec is None: + raise ImportError(f"Can't find {module}") + if not spec.has_location and hasattr(spec, 'submodule_search_locations'): + spec = importlib.util.spec_from_loader('__init__.py', spec.loader) + + kind = -1 + file = None + static = isinstance(spec.loader, type) + if ( + spec.origin == 'frozen' + or static + and issubclass(spec.loader, importlib.machinery.FrozenImporter) + ): + kind = PY_FROZEN + path = None # imp compabilty + suffix = mode = '' # imp compatibility + elif ( + spec.origin == 'built-in' + or static + and issubclass(spec.loader, importlib.machinery.BuiltinImporter) + ): + kind = C_BUILTIN + path = None # imp compabilty + suffix = mode = '' # imp compatibility + elif spec.has_location: + path = spec.origin + suffix = os.path.splitext(path)[1] + mode = 'r' if suffix in importlib.machinery.SOURCE_SUFFIXES else 'rb' + + if suffix in importlib.machinery.SOURCE_SUFFIXES: + kind = PY_SOURCE + file = tokenize.open(path) + elif suffix in importlib.machinery.BYTECODE_SUFFIXES: + kind = PY_COMPILED + file = open(path, 'rb') + elif suffix in importlib.machinery.EXTENSION_SUFFIXES: + kind = C_EXTENSION + + else: + path = None + suffix = mode = '' + + return file, path, (suffix, mode, kind) + + +def get_frozen_object(module, paths=None): + spec = find_spec(module, paths) + if not spec: + raise ImportError(f"Can't find {module}") + return spec.loader.get_code(module) + + +def get_module(module, paths, info): + spec = find_spec(module, paths) + if not spec: + raise ImportError(f"Can't find {module}") + return module_from_spec(spec) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/_importlib.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/_importlib.py new file mode 100644 index 0000000000000000000000000000000000000000..ce0fd52653b56c9c2cb2b2c7bfb35e3ec3c61408 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/_importlib.py @@ -0,0 +1,9 @@ +import sys + +if sys.version_info < (3, 10): + import importlib_metadata as metadata # pragma: no cover +else: + import importlib.metadata as metadata # noqa: F401 + + +import importlib.resources as resources # noqa: F401 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/_itertools.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/_itertools.py new file mode 100644 index 0000000000000000000000000000000000000000..d6ca841353ce39ac4361013f5c8160d69028d0d8 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/_itertools.py @@ -0,0 +1,23 @@ +from more_itertools import consume # noqa: F401 + + +# copied from jaraco.itertools 6.1 +def ensure_unique(iterable, key=lambda x: x): + """ + Wrap an iterable to raise a ValueError if non-unique values are encountered. + + >>> list(ensure_unique('abc')) + ['a', 'b', 'c'] + >>> consume(ensure_unique('abca')) + Traceback (most recent call last): + ... + ValueError: Duplicate element 'a' encountered. + """ + seen = set() + seen_add = seen.add + for element in iterable: + k = key(element) + if k in seen: + raise ValueError(f"Duplicate element {element!r} encountered.") + seen_add(k) + yield element diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/_normalization.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/_normalization.py new file mode 100644 index 0000000000000000000000000000000000000000..0937a4faf8cf2358ed1ec8a4f12b8260e493fd24 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/_normalization.py @@ -0,0 +1,179 @@ +""" +Helpers for normalization as expected in wheel/sdist/module file names +and core metadata +""" + +import re +from typing import TYPE_CHECKING + +import packaging + +# https://packaging.python.org/en/latest/specifications/core-metadata/#name +_VALID_NAME = re.compile(r"^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$", re.I) +_UNSAFE_NAME_CHARS = re.compile(r"[^A-Z0-9._-]+", re.I) +_NON_ALPHANUMERIC = re.compile(r"[^A-Z0-9]+", re.I) +_PEP440_FALLBACK = re.compile(r"^v?(?P(?:[0-9]+!)?[0-9]+(?:\.[0-9]+)*)", re.I) + + +def safe_identifier(name: str) -> str: + """Make a string safe to be used as Python identifier. + >>> safe_identifier("12abc") + '_12abc' + >>> safe_identifier("__editable__.myns.pkg-78.9.3_local") + '__editable___myns_pkg_78_9_3_local' + """ + safe = re.sub(r'\W|^(?=\d)', '_', name) + assert safe.isidentifier() + return safe + + +def safe_name(component: str) -> str: + """Escape a component used as a project name according to Core Metadata. + >>> safe_name("hello world") + 'hello-world' + >>> safe_name("hello?world") + 'hello-world' + >>> safe_name("hello_world") + 'hello_world' + """ + # See pkg_resources.safe_name + return _UNSAFE_NAME_CHARS.sub("-", component) + + +def safe_version(version: str) -> str: + """Convert an arbitrary string into a valid version string. + Can still raise an ``InvalidVersion`` exception. + To avoid exceptions use ``best_effort_version``. + >>> safe_version("1988 12 25") + '1988.12.25' + >>> safe_version("v0.2.1") + '0.2.1' + >>> safe_version("v0.2?beta") + '0.2b0' + >>> safe_version("v0.2 beta") + '0.2b0' + >>> safe_version("ubuntu lts") + Traceback (most recent call last): + ... + packaging.version.InvalidVersion: Invalid version: 'ubuntu.lts' + """ + v = version.replace(' ', '.') + try: + return str(packaging.version.Version(v)) + except packaging.version.InvalidVersion: + attempt = _UNSAFE_NAME_CHARS.sub("-", v) + return str(packaging.version.Version(attempt)) + + +def best_effort_version(version: str) -> str: + """Convert an arbitrary string into a version-like string. + Fallback when ``safe_version`` is not safe enough. + >>> best_effort_version("v0.2 beta") + '0.2b0' + >>> best_effort_version("ubuntu lts") + '0.dev0+sanitized.ubuntu.lts' + >>> best_effort_version("0.23ubuntu1") + '0.23.dev0+sanitized.ubuntu1' + >>> best_effort_version("0.23-") + '0.23.dev0+sanitized' + >>> best_effort_version("0.-_") + '0.dev0+sanitized' + >>> best_effort_version("42.+?1") + '42.dev0+sanitized.1' + """ + # See pkg_resources._forgiving_version + try: + return safe_version(version) + except packaging.version.InvalidVersion: + v = version.replace(' ', '.') + match = _PEP440_FALLBACK.search(v) + if match: + safe = match["safe"] + rest = v[len(safe) :] + else: + safe = "0" + rest = version + safe_rest = _NON_ALPHANUMERIC.sub(".", rest).strip(".") + local = f"sanitized.{safe_rest}".strip(".") + return safe_version(f"{safe}.dev0+{local}") + + +def safe_extra(extra: str) -> str: + """Normalize extra name according to PEP 685 + >>> safe_extra("_FrIeNdLy-._.-bArD") + 'friendly-bard' + >>> safe_extra("FrIeNdLy-._.-bArD__._-") + 'friendly-bard' + """ + return _NON_ALPHANUMERIC.sub("-", extra).strip("-").lower() + + +def filename_component(value: str) -> str: + """Normalize each component of a filename (e.g. distribution/version part of wheel) + Note: ``value`` needs to be already normalized. + >>> filename_component("my-pkg") + 'my_pkg' + """ + return value.replace("-", "_").strip("_") + + +def filename_component_broken(value: str) -> str: + """ + Produce the incorrect filename component for compatibility. + + See pypa/setuptools#4167 for detailed analysis. + + TODO: replace this with filename_component after pip 24 is + nearly-ubiquitous. + + >>> filename_component_broken('foo_bar-baz') + 'foo-bar-baz' + """ + return value.replace('_', '-') + + +def safer_name(value: str) -> str: + """Like ``safe_name`` but can be used as filename component for wheel""" + # See bdist_wheel.safer_name + return ( + # Per https://packaging.python.org/en/latest/specifications/name-normalization/#name-normalization + re.sub(r"[-_.]+", "-", safe_name(value)) + .lower() + # Per https://packaging.python.org/en/latest/specifications/binary-distribution-format/#escaping-and-unicode + .replace("-", "_") + ) + + +def safer_best_effort_version(value: str) -> str: + """Like ``best_effort_version`` but can be used as filename component for wheel""" + # See bdist_wheel.safer_verion + # TODO: Replace with only safe_version in the future (no need for best effort) + return filename_component(best_effort_version(value)) + + +def _missing_canonicalize_license_expression(expression: str) -> str: + """ + Defer import error to affect only users that actually use it + https://github.com/pypa/setuptools/issues/4894 + >>> _missing_canonicalize_license_expression("a OR b") + Traceback (most recent call last): + ... + ImportError: ...Cannot import `packaging.licenses`... + """ + raise ImportError( + "Cannot import `packaging.licenses`." + """ + Setuptools>=77.0.0 requires "packaging>=24.2" to work properly. + Please make sure you have a suitable version installed. + """ + ) + + +try: + from packaging.licenses import ( + canonicalize_license_expression as _canonicalize_license_expression, + ) +except ImportError: # pragma: nocover + if not TYPE_CHECKING: + # XXX: pyright is still upset even with # pyright: ignore[reportAssignmentType] + _canonicalize_license_expression = _missing_canonicalize_license_expression diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/_path.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/_path.py new file mode 100644 index 0000000000000000000000000000000000000000..0d99b0f539ff5f819b167013c48726180cd83d49 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/_path.py @@ -0,0 +1,84 @@ +from __future__ import annotations + +import contextlib +import os +import sys +from typing import TYPE_CHECKING, TypeVar, Union + +from more_itertools import unique_everseen + +if TYPE_CHECKING: + from typing_extensions import TypeAlias + +StrPath: TypeAlias = Union[str, os.PathLike[str]] # Same as _typeshed.StrPath +StrPathT = TypeVar("StrPathT", bound=Union[str, os.PathLike[str]]) + + +def ensure_directory(path): + """Ensure that the parent directory of `path` exists""" + dirname = os.path.dirname(path) + os.makedirs(dirname, exist_ok=True) + + +def same_path(p1: StrPath, p2: StrPath) -> bool: + """Differs from os.path.samefile because it does not require paths to exist. + Purely string based (no comparison between i-nodes). + >>> same_path("a/b", "./a/b") + True + >>> same_path("a/b", "a/./b") + True + >>> same_path("a/b", "././a/b") + True + >>> same_path("a/b", "./a/b/c/..") + True + >>> same_path("a/b", "../a/b/c") + False + >>> same_path("a", "a/b") + False + """ + return normpath(p1) == normpath(p2) + + +def normpath(filename: StrPath) -> str: + """Normalize a file/dir name for comparison purposes.""" + # See pkg_resources.normalize_path for notes about cygwin + file = os.path.abspath(filename) if sys.platform == 'cygwin' else filename + return os.path.normcase(os.path.realpath(os.path.normpath(file))) + + +@contextlib.contextmanager +def paths_on_pythonpath(paths): + """ + Add the indicated paths to the head of the PYTHONPATH environment + variable so that subprocesses will also see the packages at + these paths. + + Do this in a context that restores the value on exit. + + >>> getfixture('monkeypatch').setenv('PYTHONPATH', 'anything') + >>> with paths_on_pythonpath(['foo', 'bar']): + ... assert 'foo' in os.environ['PYTHONPATH'] + ... assert 'anything' in os.environ['PYTHONPATH'] + >>> os.environ['PYTHONPATH'] + 'anything' + + >>> getfixture('monkeypatch').delenv('PYTHONPATH') + >>> with paths_on_pythonpath(['foo', 'bar']): + ... assert 'foo' in os.environ['PYTHONPATH'] + >>> os.environ.get('PYTHONPATH') + """ + nothing = object() + orig_pythonpath = os.environ.get('PYTHONPATH', nothing) + current_pythonpath = os.environ.get('PYTHONPATH', '') + try: + prefix = os.pathsep.join(unique_everseen(paths)) + to_join = filter(None, [prefix, current_pythonpath]) + new_path = os.pathsep.join(to_join) + if new_path: + os.environ['PYTHONPATH'] = new_path + yield + finally: + if orig_pythonpath is nothing: + os.environ.pop('PYTHONPATH', None) + else: + os.environ['PYTHONPATH'] = orig_pythonpath diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/_reqs.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/_reqs.py new file mode 100644 index 0000000000000000000000000000000000000000..c793be4d6eb3991d7b4ada615201a01cbfbbefd5 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/_reqs.py @@ -0,0 +1,42 @@ +from __future__ import annotations + +from collections.abc import Iterable, Iterator +from functools import lru_cache +from typing import TYPE_CHECKING, Callable, TypeVar, Union, overload + +import jaraco.text as text +from packaging.requirements import Requirement + +if TYPE_CHECKING: + from typing_extensions import TypeAlias + +_T = TypeVar("_T") +_StrOrIter: TypeAlias = Union[str, Iterable[str]] + + +parse_req: Callable[[str], Requirement] = lru_cache()(Requirement) +# Setuptools parses the same requirement many times +# (e.g. first for validation than for normalisation), +# so it might be worth to cache. + + +def parse_strings(strs: _StrOrIter) -> Iterator[str]: + """ + Yield requirement strings for each specification in `strs`. + + `strs` must be a string, or a (possibly-nested) iterable thereof. + """ + return text.join_continuation(map(text.drop_comment, text.yield_lines(strs))) + + +# These overloads are only needed because of a mypy false-positive, pyright gets it right +# https://github.com/python/mypy/issues/3737 +@overload +def parse(strs: _StrOrIter) -> Iterator[Requirement]: ... +@overload +def parse(strs: _StrOrIter, parser: Callable[[str], _T]) -> Iterator[_T]: ... +def parse(strs: _StrOrIter, parser: Callable[[str], _T] = parse_req) -> Iterator[_T]: # type: ignore[assignment] + """ + Replacement for ``pkg_resources.parse_requirements`` that uses ``packaging``. + """ + return map(parser, parse_strings(strs)) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/_shutil.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/_shutil.py new file mode 100644 index 0000000000000000000000000000000000000000..6acbb4281fc986587f52a83395dc63912a863caf --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/_shutil.py @@ -0,0 +1,53 @@ +"""Convenience layer on top of stdlib's shutil and os""" + +import os +import stat +from typing import Callable, TypeVar + +from .compat import py311 + +from distutils import log + +try: + from os import chmod # pyright: ignore[reportAssignmentType] + # Losing type-safety w/ pyright, but that's ok +except ImportError: # pragma: no cover + # Jython compatibility + def chmod(*args: object, **kwargs: object) -> None: # type: ignore[misc] # Mypy reuses the imported definition anyway + pass + + +_T = TypeVar("_T") + + +def attempt_chmod_verbose(path, mode): + log.debug("changing mode of %s to %o", path, mode) + try: + chmod(path, mode) + except OSError as e: # pragma: no cover + log.debug("chmod failed: %s", e) + + +# Must match shutil._OnExcCallback +def _auto_chmod( + func: Callable[..., _T], arg: str, exc: BaseException +) -> _T: # pragma: no cover + """shutils onexc callback to automatically call chmod for certain functions.""" + # Only retry for scenarios known to have an issue + if func in [os.unlink, os.remove] and os.name == 'nt': + attempt_chmod_verbose(arg, stat.S_IWRITE) + return func(arg) + raise exc + + +def rmtree(path, ignore_errors=False, onexc=_auto_chmod): + """ + Similar to ``shutil.rmtree`` but automatically executes ``chmod`` + for well know Windows failure scenarios. + """ + return py311.shutil_rmtree(path, ignore_errors, onexc) + + +def rmdir(path, **opts): + if os.path.isdir(path): + rmtree(path, **opts) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/_static.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/_static.py new file mode 100644 index 0000000000000000000000000000000000000000..af35862cf8b759a0e60110ce9e92bfdb1b49bc5f --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/_static.py @@ -0,0 +1,188 @@ +from functools import wraps +from typing import TypeVar + +import packaging.specifiers + +from .warnings import SetuptoolsDeprecationWarning + + +class Static: + """ + Wrapper for built-in object types that are allow setuptools to identify + static core metadata (in opposition to ``Dynamic``, as defined :pep:`643`). + + The trick is to mark values with :class:`Static` when they come from + ``pyproject.toml`` or ``setup.cfg``, so if any plugin overwrite the value + with a built-in, setuptools will be able to recognise the change. + + We inherit from built-in classes, so that we don't need to change the existing + code base to deal with the new types. + We also should strive for immutability objects to avoid changes after the + initial parsing. + """ + + _mutated_: bool = False # TODO: Remove after deprecation warning is solved + + +def _prevent_modification(target: type, method: str, copying: str) -> None: + """ + Because setuptools is very flexible we cannot fully prevent + plugins and user customizations from modifying static values that were + parsed from config files. + But we can attempt to block "in-place" mutations and identify when they + were done. + """ + fn = getattr(target, method, None) + if fn is None: + return + + @wraps(fn) + def _replacement(self: Static, *args, **kwargs): + # TODO: After deprecation period raise NotImplementedError instead of warning + # which obviated the existence and checks of the `_mutated_` attribute. + self._mutated_ = True + SetuptoolsDeprecationWarning.emit( + "Direct modification of value will be disallowed", + f""" + In an effort to implement PEP 643, direct/in-place changes of static values + that come from configuration files are deprecated. + If you need to modify this value, please first create a copy with {copying} + and make sure conform to all relevant standards when overriding setuptools + functionality (https://packaging.python.org/en/latest/specifications/). + """, + due_date=(2025, 10, 10), # Initially introduced in 2024-09-06 + ) + return fn(self, *args, **kwargs) + + _replacement.__doc__ = "" # otherwise doctest may fail. + setattr(target, method, _replacement) + + +class Str(str, Static): + pass + + +class Tuple(tuple, Static): + pass + + +class List(list, Static): + """ + :meta private: + >>> x = List([1, 2, 3]) + >>> is_static(x) + True + >>> x += [0] # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + SetuptoolsDeprecationWarning: Direct modification ... + >>> is_static(x) # no longer static after modification + False + >>> y = list(x) + >>> y.clear() + >>> y + [] + >>> y == x + False + >>> is_static(List(y)) + True + """ + + +# Make `List` immutable-ish +# (certain places of setuptools/distutils issue a warn if we use tuple instead of list) +for _method in ( + '__delitem__', + '__iadd__', + '__setitem__', + 'append', + 'clear', + 'extend', + 'insert', + 'remove', + 'reverse', + 'pop', +): + _prevent_modification(List, _method, "`list(value)`") + + +class Dict(dict, Static): + """ + :meta private: + >>> x = Dict({'a': 1, 'b': 2}) + >>> is_static(x) + True + >>> x['c'] = 0 # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + SetuptoolsDeprecationWarning: Direct modification ... + >>> x._mutated_ + True + >>> is_static(x) # no longer static after modification + False + >>> y = dict(x) + >>> y.popitem() + ('b', 2) + >>> y == x + False + >>> is_static(Dict(y)) + True + """ + + +# Make `Dict` immutable-ish (we cannot inherit from types.MappingProxyType): +for _method in ( + '__delitem__', + '__ior__', + '__setitem__', + 'clear', + 'pop', + 'popitem', + 'setdefault', + 'update', +): + _prevent_modification(Dict, _method, "`dict(value)`") + + +class SpecifierSet(packaging.specifiers.SpecifierSet, Static): + """Not exactly a built-in type but useful for ``requires-python``""" + + +T = TypeVar("T") + + +def noop(value: T) -> T: + """ + >>> noop(42) + 42 + """ + return value + + +_CONVERSIONS = {str: Str, tuple: Tuple, list: List, dict: Dict} + + +def attempt_conversion(value: T) -> T: + """ + >>> is_static(attempt_conversion("hello")) + True + >>> is_static(object()) + False + """ + return _CONVERSIONS.get(type(value), noop)(value) # type: ignore[call-overload] + + +def is_static(value: object) -> bool: + """ + >>> is_static(a := Dict({'a': 1})) + True + >>> is_static(dict(a)) + False + >>> is_static(b := List([1, 2, 3])) + True + >>> is_static(list(b)) + False + """ + return isinstance(value, Static) and not value._mutated_ + + +EMPTY_LIST = List() +EMPTY_DICT = Dict() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/archive_util.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/archive_util.py new file mode 100644 index 0000000000000000000000000000000000000000..1a02010bb2af2be0487730d6a32080877b9ac220 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/archive_util.py @@ -0,0 +1,219 @@ +"""Utilities for extracting common archive formats""" + +import contextlib +import os +import posixpath +import shutil +import tarfile +import zipfile + +from ._path import ensure_directory + +from distutils.errors import DistutilsError + +__all__ = [ + "unpack_archive", + "unpack_zipfile", + "unpack_tarfile", + "default_filter", + "UnrecognizedFormat", + "extraction_drivers", + "unpack_directory", +] + + +class UnrecognizedFormat(DistutilsError): + """Couldn't recognize the archive type""" + + +def default_filter(src, dst): + """The default progress/filter callback; returns True for all files""" + return dst + + +def unpack_archive( + filename, extract_dir, progress_filter=default_filter, drivers=None +) -> None: + """Unpack `filename` to `extract_dir`, or raise ``UnrecognizedFormat`` + + `progress_filter` is a function taking two arguments: a source path + internal to the archive ('/'-separated), and a filesystem path where it + will be extracted. The callback must return the desired extract path + (which may be the same as the one passed in), or else ``None`` to skip + that file or directory. The callback can thus be used to report on the + progress of the extraction, as well as to filter the items extracted or + alter their extraction paths. + + `drivers`, if supplied, must be a non-empty sequence of functions with the + same signature as this function (minus the `drivers` argument), that raise + ``UnrecognizedFormat`` if they do not support extracting the designated + archive type. The `drivers` are tried in sequence until one is found that + does not raise an error, or until all are exhausted (in which case + ``UnrecognizedFormat`` is raised). If you do not supply a sequence of + drivers, the module's ``extraction_drivers`` constant will be used, which + means that ``unpack_zipfile`` and ``unpack_tarfile`` will be tried, in that + order. + """ + for driver in drivers or extraction_drivers: + try: + driver(filename, extract_dir, progress_filter) + except UnrecognizedFormat: + continue + else: + return + else: + raise UnrecognizedFormat(f"Not a recognized archive type: {filename}") + + +def unpack_directory(filename, extract_dir, progress_filter=default_filter) -> None: + """ "Unpack" a directory, using the same interface as for archives + + Raises ``UnrecognizedFormat`` if `filename` is not a directory + """ + if not os.path.isdir(filename): + raise UnrecognizedFormat(f"{filename} is not a directory") + + paths = { + filename: ('', extract_dir), + } + for base, dirs, files in os.walk(filename): + src, dst = paths[base] + for d in dirs: + paths[os.path.join(base, d)] = src + d + '/', os.path.join(dst, d) + for f in files: + target = os.path.join(dst, f) + target = progress_filter(src + f, target) + if not target: + # skip non-files + continue + ensure_directory(target) + f = os.path.join(base, f) + shutil.copyfile(f, target) + shutil.copystat(f, target) + + +def unpack_zipfile(filename, extract_dir, progress_filter=default_filter) -> None: + """Unpack zip `filename` to `extract_dir` + + Raises ``UnrecognizedFormat`` if `filename` is not a zipfile (as determined + by ``zipfile.is_zipfile()``). See ``unpack_archive()`` for an explanation + of the `progress_filter` argument. + """ + + if not zipfile.is_zipfile(filename): + raise UnrecognizedFormat(f"{filename} is not a zip file") + + with zipfile.ZipFile(filename) as z: + _unpack_zipfile_obj(z, extract_dir, progress_filter) + + +def _unpack_zipfile_obj(zipfile_obj, extract_dir, progress_filter=default_filter): + """Internal/private API used by other parts of setuptools. + Similar to ``unpack_zipfile``, but receives an already opened :obj:`zipfile.ZipFile` + object instead of a filename. + """ + for info in zipfile_obj.infolist(): + name = info.filename + + # don't extract absolute paths or ones with .. in them + if name.startswith('/') or '..' in name.split('/'): + continue + + target = os.path.join(extract_dir, *name.split('/')) + target = progress_filter(name, target) + if not target: + continue + if name.endswith('/'): + # directory + ensure_directory(target) + else: + # file + ensure_directory(target) + data = zipfile_obj.read(info.filename) + with open(target, 'wb') as f: + f.write(data) + unix_attributes = info.external_attr >> 16 + if unix_attributes: + os.chmod(target, unix_attributes) + + +def _resolve_tar_file_or_dir(tar_obj, tar_member_obj): + """Resolve any links and extract link targets as normal files.""" + while tar_member_obj is not None and ( + tar_member_obj.islnk() or tar_member_obj.issym() + ): + linkpath = tar_member_obj.linkname + if tar_member_obj.issym(): + base = posixpath.dirname(tar_member_obj.name) + linkpath = posixpath.join(base, linkpath) + linkpath = posixpath.normpath(linkpath) + tar_member_obj = tar_obj._getmember(linkpath) + + is_file_or_dir = tar_member_obj is not None and ( + tar_member_obj.isfile() or tar_member_obj.isdir() + ) + if is_file_or_dir: + return tar_member_obj + + raise LookupError('Got unknown file type') + + +def _iter_open_tar(tar_obj, extract_dir, progress_filter): + """Emit member-destination pairs from a tar archive.""" + # don't do any chowning! + tar_obj.chown = lambda *args: None + + with contextlib.closing(tar_obj): + for member in tar_obj: + name = member.name + # don't extract absolute paths or ones with .. in them + if name.startswith('/') or '..' in name.split('/'): + continue + + prelim_dst = os.path.join(extract_dir, *name.split('/')) + + try: + member = _resolve_tar_file_or_dir(tar_obj, member) + except LookupError: + continue + + final_dst = progress_filter(name, prelim_dst) + if not final_dst: + continue + + if final_dst.endswith(os.sep): + final_dst = final_dst[:-1] + + yield member, final_dst + + +def unpack_tarfile(filename, extract_dir, progress_filter=default_filter) -> bool: + """Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir` + + Raises ``UnrecognizedFormat`` if `filename` is not a tarfile (as determined + by ``tarfile.open()``). See ``unpack_archive()`` for an explanation + of the `progress_filter` argument. + """ + try: + tarobj = tarfile.open(filename) + except tarfile.TarError as e: + raise UnrecognizedFormat( + f"{filename} is not a compressed or uncompressed tar file" + ) from e + + for member, final_dst in _iter_open_tar( + tarobj, + extract_dir, + progress_filter, + ): + try: + # XXX Ugh + tarobj._extract_member(member, final_dst) + except tarfile.ExtractError: + # chown/chmod/mkfifo/mknode/makedev failed + pass + + return True + + +extraction_drivers = unpack_directory, unpack_zipfile, unpack_tarfile diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/build_meta.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/build_meta.py new file mode 100644 index 0000000000000000000000000000000000000000..8f2e930c73439933b1e15506699ce25ec926c46f --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/build_meta.py @@ -0,0 +1,548 @@ +"""A PEP 517 interface to setuptools + +Previously, when a user or a command line tool (let's call it a "frontend") +needed to make a request of setuptools to take a certain action, for +example, generating a list of installation requirements, the frontend +would call "setup.py egg_info" or "setup.py bdist_wheel" on the command line. + +PEP 517 defines a different method of interfacing with setuptools. Rather +than calling "setup.py" directly, the frontend should: + + 1. Set the current directory to the directory with a setup.py file + 2. Import this module into a safe python interpreter (one in which + setuptools can potentially set global variables or crash hard). + 3. Call one of the functions defined in PEP 517. + +What each function does is defined in PEP 517. However, here is a "casual" +definition of the functions (this definition should not be relied on for +bug reports or API stability): + + - `build_wheel`: build a wheel in the folder and return the basename + - `get_requires_for_build_wheel`: get the `setup_requires` to build + - `prepare_metadata_for_build_wheel`: get the `install_requires` + - `build_sdist`: build an sdist in the folder and return the basename + - `get_requires_for_build_sdist`: get the `setup_requires` to build + +Again, this is not a formal definition! Just a "taste" of the module. +""" + +from __future__ import annotations + +import contextlib +import io +import os +import shlex +import shutil +import sys +import tempfile +import tokenize +import warnings +from collections.abc import Iterable, Iterator, Mapping +from pathlib import Path +from typing import TYPE_CHECKING, Union + +import setuptools + +from . import errors +from ._path import StrPath, same_path +from ._reqs import parse_strings +from .warnings import SetuptoolsDeprecationWarning + +import distutils +from distutils.util import strtobool + +if TYPE_CHECKING: + from typing_extensions import TypeAlias + +__all__ = [ + 'get_requires_for_build_sdist', + 'get_requires_for_build_wheel', + 'prepare_metadata_for_build_wheel', + 'build_wheel', + 'build_sdist', + 'get_requires_for_build_editable', + 'prepare_metadata_for_build_editable', + 'build_editable', + '__legacy__', + 'SetupRequirementsError', +] + + +class SetupRequirementsError(BaseException): + def __init__(self, specifiers) -> None: + self.specifiers = specifiers + + +class Distribution(setuptools.dist.Distribution): + def fetch_build_eggs(self, specifiers): + specifier_list = list(parse_strings(specifiers)) + + raise SetupRequirementsError(specifier_list) + + @classmethod + @contextlib.contextmanager + def patch(cls): + """ + Replace + distutils.dist.Distribution with this class + for the duration of this context. + """ + orig = distutils.core.Distribution + distutils.core.Distribution = cls # type: ignore[misc] # monkeypatching + try: + yield + finally: + distutils.core.Distribution = orig # type: ignore[misc] # monkeypatching + + +@contextlib.contextmanager +def no_install_setup_requires(): + """Temporarily disable installing setup_requires + + Under PEP 517, the backend reports build dependencies to the frontend, + and the frontend is responsible for ensuring they're installed. + So setuptools (acting as a backend) should not try to install them. + """ + orig = setuptools._install_setup_requires + setuptools._install_setup_requires = lambda attrs: None + try: + yield + finally: + setuptools._install_setup_requires = orig + + +def _get_immediate_subdirectories(a_dir): + return [ + name for name in os.listdir(a_dir) if os.path.isdir(os.path.join(a_dir, name)) + ] + + +def _file_with_extension(directory: StrPath, extension: str | tuple[str, ...]): + matching = (f for f in os.listdir(directory) if f.endswith(extension)) + try: + (file,) = matching + except ValueError: + raise ValueError( + 'No distribution was found. Ensure that `setup.py` ' + 'is not empty and that it calls `setup()`.' + ) from None + return file + + +def _open_setup_script(setup_script): + if not os.path.exists(setup_script): + # Supply a default setup.py + return io.StringIO("from setuptools import setup; setup()") + + return tokenize.open(setup_script) + + +@contextlib.contextmanager +def suppress_known_deprecation(): + with warnings.catch_warnings(): + warnings.filterwarnings('ignore', 'setup.py install is deprecated') + yield + + +_ConfigSettings: TypeAlias = Union[Mapping[str, Union[str, list[str], None]], None] +""" +Currently the user can run:: + + pip install -e . --config-settings key=value + python -m build -C--key=value -C key=value + +- pip will pass both key and value as strings and overwriting repeated keys + (pypa/pip#11059). +- build will accumulate values associated with repeated keys in a list. + It will also accept keys with no associated value. + This means that an option passed by build can be ``str | list[str] | None``. +- PEP 517 specifies that ``config_settings`` is an optional dict. +""" + + +class _ConfigSettingsTranslator: + """Translate ``config_settings`` into distutils-style command arguments. + Only a limited number of options is currently supported. + """ + + # See pypa/setuptools#1928 pypa/setuptools#2491 + + def _get_config(self, key: str, config_settings: _ConfigSettings) -> list[str]: + """ + Get the value of a specific key in ``config_settings`` as a list of strings. + + >>> fn = _ConfigSettingsTranslator()._get_config + >>> fn("--global-option", None) + [] + >>> fn("--global-option", {}) + [] + >>> fn("--global-option", {'--global-option': 'foo'}) + ['foo'] + >>> fn("--global-option", {'--global-option': ['foo']}) + ['foo'] + >>> fn("--global-option", {'--global-option': 'foo'}) + ['foo'] + >>> fn("--global-option", {'--global-option': 'foo bar'}) + ['foo', 'bar'] + """ + cfg = config_settings or {} + opts = cfg.get(key) or [] + return shlex.split(opts) if isinstance(opts, str) else opts + + def _global_args(self, config_settings: _ConfigSettings) -> Iterator[str]: + """ + Let the user specify ``verbose`` or ``quiet`` + escape hatch via + ``--global-option``. + Note: ``-v``, ``-vv``, ``-vvv`` have similar effects in setuptools, + so we just have to cover the basic scenario ``-v``. + + >>> fn = _ConfigSettingsTranslator()._global_args + >>> list(fn(None)) + [] + >>> list(fn({"verbose": "False"})) + ['-q'] + >>> list(fn({"verbose": "1"})) + ['-v'] + >>> list(fn({"--verbose": None})) + ['-v'] + >>> list(fn({"verbose": "true", "--global-option": "-q --no-user-cfg"})) + ['-v', '-q', '--no-user-cfg'] + >>> list(fn({"--quiet": None})) + ['-q'] + """ + cfg = config_settings or {} + falsey = {"false", "no", "0", "off"} + if "verbose" in cfg or "--verbose" in cfg: + level = str(cfg.get("verbose") or cfg.get("--verbose") or "1") + yield ("-q" if level.lower() in falsey else "-v") + if "quiet" in cfg or "--quiet" in cfg: + level = str(cfg.get("quiet") or cfg.get("--quiet") or "1") + yield ("-v" if level.lower() in falsey else "-q") + + yield from self._get_config("--global-option", config_settings) + + def __dist_info_args(self, config_settings: _ConfigSettings) -> Iterator[str]: + """ + The ``dist_info`` command accepts ``tag-date`` and ``tag-build``. + + .. warning:: + We cannot use this yet as it requires the ``sdist`` and ``bdist_wheel`` + commands run in ``build_sdist`` and ``build_wheel`` to reuse the egg-info + directory created in ``prepare_metadata_for_build_wheel``. + + >>> fn = _ConfigSettingsTranslator()._ConfigSettingsTranslator__dist_info_args + >>> list(fn(None)) + [] + >>> list(fn({"tag-date": "False"})) + ['--no-date'] + >>> list(fn({"tag-date": None})) + ['--no-date'] + >>> list(fn({"tag-date": "true", "tag-build": ".a"})) + ['--tag-date', '--tag-build', '.a'] + """ + cfg = config_settings or {} + if "tag-date" in cfg: + val = strtobool(str(cfg["tag-date"] or "false")) + yield ("--tag-date" if val else "--no-date") + if "tag-build" in cfg: + yield from ["--tag-build", str(cfg["tag-build"])] + + def _editable_args(self, config_settings: _ConfigSettings) -> Iterator[str]: + """ + The ``editable_wheel`` command accepts ``editable-mode=strict``. + + >>> fn = _ConfigSettingsTranslator()._editable_args + >>> list(fn(None)) + [] + >>> list(fn({"editable-mode": "strict"})) + ['--mode', 'strict'] + """ + cfg = config_settings or {} + mode = cfg.get("editable-mode") or cfg.get("editable_mode") + if not mode: + return + yield from ["--mode", str(mode)] + + def _arbitrary_args(self, config_settings: _ConfigSettings) -> Iterator[str]: + """ + Users may expect to pass arbitrary lists of arguments to a command + via "--global-option" (example provided in PEP 517 of a "escape hatch"). + + >>> fn = _ConfigSettingsTranslator()._arbitrary_args + >>> list(fn(None)) + [] + >>> list(fn({})) + [] + >>> list(fn({'--build-option': 'foo'})) + ['foo'] + >>> list(fn({'--build-option': ['foo']})) + ['foo'] + >>> list(fn({'--build-option': 'foo'})) + ['foo'] + >>> list(fn({'--build-option': 'foo bar'})) + ['foo', 'bar'] + >>> list(fn({'--global-option': 'foo'})) + [] + """ + yield from self._get_config("--build-option", config_settings) + + +class _BuildMetaBackend(_ConfigSettingsTranslator): + def _get_build_requires( + self, config_settings: _ConfigSettings, requirements: list[str] + ): + sys.argv = [ + *sys.argv[:1], + *self._global_args(config_settings), + "egg_info", + ] + try: + with Distribution.patch(): + self.run_setup() + except SetupRequirementsError as e: + requirements += e.specifiers + + return requirements + + def run_setup(self, setup_script: str = 'setup.py'): + # Note that we can reuse our build directory between calls + # Correctness comes first, then optimization later + __file__ = os.path.abspath(setup_script) + __name__ = '__main__' + + with _open_setup_script(__file__) as f: + code = f.read().replace(r'\r\n', r'\n') + + try: + exec(code, locals()) + except SystemExit as e: + if e.code: + raise + # We ignore exit code indicating success + SetuptoolsDeprecationWarning.emit( + "Running `setup.py` directly as CLI tool is deprecated.", + "Please avoid using `sys.exit(0)` or similar statements " + "that don't fit in the paradigm of a configuration file.", + see_url="https://blog.ganssle.io/articles/2021/10/" + "setup-py-deprecated.html", + ) + + def get_requires_for_build_wheel(self, config_settings: _ConfigSettings = None): + return self._get_build_requires(config_settings, requirements=[]) + + def get_requires_for_build_sdist(self, config_settings: _ConfigSettings = None): + return self._get_build_requires(config_settings, requirements=[]) + + def _bubble_up_info_directory( + self, metadata_directory: StrPath, suffix: str + ) -> str: + """ + PEP 517 requires that the .dist-info directory be placed in the + metadata_directory. To comply, we MUST copy the directory to the root. + + Returns the basename of the info directory, e.g. `proj-0.0.0.dist-info`. + """ + info_dir = self._find_info_directory(metadata_directory, suffix) + if not same_path(info_dir.parent, metadata_directory): + shutil.move(str(info_dir), metadata_directory) + # PEP 517 allow other files and dirs to exist in metadata_directory + return info_dir.name + + def _find_info_directory(self, metadata_directory: StrPath, suffix: str) -> Path: + for parent, dirs, _ in os.walk(metadata_directory): + candidates = [f for f in dirs if f.endswith(suffix)] + + if len(candidates) != 0 or len(dirs) != 1: + assert len(candidates) == 1, f"Multiple {suffix} directories found" + return Path(parent, candidates[0]) + + msg = f"No {suffix} directory found in {metadata_directory}" + raise errors.InternalError(msg) + + def prepare_metadata_for_build_wheel( + self, metadata_directory: StrPath, config_settings: _ConfigSettings = None + ): + sys.argv = [ + *sys.argv[:1], + *self._global_args(config_settings), + "dist_info", + "--output-dir", + str(metadata_directory), + "--keep-egg-info", + ] + with no_install_setup_requires(): + self.run_setup() + + self._bubble_up_info_directory(metadata_directory, ".egg-info") + return self._bubble_up_info_directory(metadata_directory, ".dist-info") + + def _build_with_temp_dir( + self, + setup_command: Iterable[str], + result_extension: str | tuple[str, ...], + result_directory: StrPath, + config_settings: _ConfigSettings, + arbitrary_args: Iterable[str] = (), + ): + result_directory = os.path.abspath(result_directory) + + # Build in a temporary directory, then copy to the target. + os.makedirs(result_directory, exist_ok=True) + + with tempfile.TemporaryDirectory( + prefix=".tmp-", dir=result_directory + ) as tmp_dist_dir: + sys.argv = [ + *sys.argv[:1], + *self._global_args(config_settings), + *setup_command, + "--dist-dir", + tmp_dist_dir, + *arbitrary_args, + ] + with no_install_setup_requires(): + self.run_setup() + + result_basename = _file_with_extension(tmp_dist_dir, result_extension) + result_path = os.path.join(result_directory, result_basename) + if os.path.exists(result_path): + # os.rename will fail overwriting on non-Unix. + os.remove(result_path) + os.rename(os.path.join(tmp_dist_dir, result_basename), result_path) + + return result_basename + + def build_wheel( + self, + wheel_directory: StrPath, + config_settings: _ConfigSettings = None, + metadata_directory: StrPath | None = None, + ): + def _build(cmd: list[str]): + with suppress_known_deprecation(): + return self._build_with_temp_dir( + cmd, + '.whl', + wheel_directory, + config_settings, + self._arbitrary_args(config_settings), + ) + + if metadata_directory is None: + return _build(['bdist_wheel']) + + try: + return _build(['bdist_wheel', '--dist-info-dir', str(metadata_directory)]) + except SystemExit as ex: # pragma: nocover + # pypa/setuptools#4683 + if "--dist-info-dir not recognized" not in str(ex): + raise + _IncompatibleBdistWheel.emit() + return _build(['bdist_wheel']) + + def build_sdist( + self, sdist_directory: StrPath, config_settings: _ConfigSettings = None + ): + return self._build_with_temp_dir( + ['sdist', '--formats', 'gztar'], '.tar.gz', sdist_directory, config_settings + ) + + def _get_dist_info_dir(self, metadata_directory: StrPath | None) -> str | None: + if not metadata_directory: + return None + dist_info_candidates = list(Path(metadata_directory).glob("*.dist-info")) + assert len(dist_info_candidates) <= 1 + return str(dist_info_candidates[0]) if dist_info_candidates else None + + def build_editable( + self, + wheel_directory: StrPath, + config_settings: _ConfigSettings = None, + metadata_directory: StrPath | None = None, + ): + # XXX can or should we hide our editable_wheel command normally? + info_dir = self._get_dist_info_dir(metadata_directory) + opts = ["--dist-info-dir", info_dir] if info_dir else [] + cmd = ["editable_wheel", *opts, *self._editable_args(config_settings)] + with suppress_known_deprecation(): + return self._build_with_temp_dir( + cmd, ".whl", wheel_directory, config_settings + ) + + def get_requires_for_build_editable(self, config_settings: _ConfigSettings = None): + return self.get_requires_for_build_wheel(config_settings) + + def prepare_metadata_for_build_editable( + self, metadata_directory: StrPath, config_settings: _ConfigSettings = None + ): + return self.prepare_metadata_for_build_wheel( + metadata_directory, config_settings + ) + + +class _BuildMetaLegacyBackend(_BuildMetaBackend): + """Compatibility backend for setuptools + + This is a version of setuptools.build_meta that endeavors + to maintain backwards + compatibility with pre-PEP 517 modes of invocation. It + exists as a temporary + bridge between the old packaging mechanism and the new + packaging mechanism, + and will eventually be removed. + """ + + def run_setup(self, setup_script: str = 'setup.py'): + # In order to maintain compatibility with scripts assuming that + # the setup.py script is in a directory on the PYTHONPATH, inject + # '' into sys.path. (pypa/setuptools#1642) + sys_path = list(sys.path) # Save the original path + + script_dir = os.path.dirname(os.path.abspath(setup_script)) + if script_dir not in sys.path: + sys.path.insert(0, script_dir) + + # Some setup.py scripts (e.g. in pygame and numpy) use sys.argv[0] to + # get the directory of the source code. They expect it to refer to the + # setup.py script. + sys_argv_0 = sys.argv[0] + sys.argv[0] = setup_script + + try: + super().run_setup(setup_script=setup_script) + finally: + # While PEP 517 frontends should be calling each hook in a fresh + # subprocess according to the standard (and thus it should not be + # strictly necessary to restore the old sys.path), we'll restore + # the original path so that the path manipulation does not persist + # within the hook after run_setup is called. + sys.path[:] = sys_path + sys.argv[0] = sys_argv_0 + + +class _IncompatibleBdistWheel(SetuptoolsDeprecationWarning): + _SUMMARY = "wheel.bdist_wheel is deprecated, please import it from setuptools" + _DETAILS = """ + Ensure that any custom bdist_wheel implementation is a subclass of + setuptools.command.bdist_wheel.bdist_wheel. + """ + _DUE_DATE = (2025, 10, 15) + # Initially introduced in 2024/10/15, but maybe too disruptive to be enforced? + _SEE_URL = "https://github.com/pypa/wheel/pull/631" + + +# The primary backend +_BACKEND = _BuildMetaBackend() + +get_requires_for_build_wheel = _BACKEND.get_requires_for_build_wheel +get_requires_for_build_sdist = _BACKEND.get_requires_for_build_sdist +prepare_metadata_for_build_wheel = _BACKEND.prepare_metadata_for_build_wheel +build_wheel = _BACKEND.build_wheel +build_sdist = _BACKEND.build_sdist +get_requires_for_build_editable = _BACKEND.get_requires_for_build_editable +prepare_metadata_for_build_editable = _BACKEND.prepare_metadata_for_build_editable +build_editable = _BACKEND.build_editable + + +# The legacy backend +__legacy__ = _BuildMetaLegacyBackend() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/cli-32.exe b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/cli-32.exe new file mode 100644 index 0000000000000000000000000000000000000000..65c3cd99cc7433f271a5b9387abdd1ddb949d1a6 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/cli-32.exe differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/cli-64.exe b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/cli-64.exe new file mode 100644 index 0000000000000000000000000000000000000000..3ea50eebfe3f0113b231a318cc1ad6e238afd60d Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/cli-64.exe differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/cli-arm64.exe b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/cli-arm64.exe new file mode 100644 index 0000000000000000000000000000000000000000..da96455a07a0bad4cde5dc5626544325f82c722b Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/cli-arm64.exe differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/cli.exe b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/cli.exe new file mode 100644 index 0000000000000000000000000000000000000000..65c3cd99cc7433f271a5b9387abdd1ddb949d1a6 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/cli.exe differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/depends.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/depends.py new file mode 100644 index 0000000000000000000000000000000000000000..e5223b79561c36d9b6c45ead78288098e1cb0f1d --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/depends.py @@ -0,0 +1,185 @@ +from __future__ import annotations + +import contextlib +import dis +import marshal +import sys +from types import CodeType +from typing import Any, Literal, TypeVar + +from packaging.version import Version + +from . import _imp +from ._imp import PY_COMPILED, PY_FROZEN, PY_SOURCE, find_module + +_T = TypeVar("_T") + +__all__ = ['Require', 'find_module'] + + +class Require: + """A prerequisite to building or installing a distribution""" + + def __init__( + self, + name, + requested_version, + module, + homepage: str = '', + attribute=None, + format=None, + ) -> None: + if format is None and requested_version is not None: + format = Version + + if format is not None: + requested_version = format(requested_version) + if attribute is None: + attribute = '__version__' + + self.__dict__.update(locals()) + del self.self + + def full_name(self): + """Return full package/distribution name, w/version""" + if self.requested_version is not None: + return f'{self.name}-{self.requested_version}' + return self.name + + def version_ok(self, version): + """Is 'version' sufficiently up-to-date?""" + return ( + self.attribute is None + or self.format is None + or str(version) != "unknown" + and self.format(version) >= self.requested_version + ) + + def get_version( + self, paths=None, default: _T | Literal["unknown"] = "unknown" + ) -> _T | Literal["unknown"] | None | Any: + """Get version number of installed module, 'None', or 'default' + + Search 'paths' for module. If not found, return 'None'. If found, + return the extracted version attribute, or 'default' if no version + attribute was specified, or the value cannot be determined without + importing the module. The version is formatted according to the + requirement's version format (if any), unless it is 'None' or the + supplied 'default'. + """ + + if self.attribute is None: + try: + f, _p, _i = find_module(self.module, paths) + except ImportError: + return None + if f: + f.close() + return default + + v = get_module_constant(self.module, self.attribute, default, paths) + + if v is not None and v is not default and self.format is not None: + return self.format(v) + + return v + + def is_present(self, paths=None): + """Return true if dependency is present on 'paths'""" + return self.get_version(paths) is not None + + def is_current(self, paths=None): + """Return true if dependency is present and up-to-date on 'paths'""" + version = self.get_version(paths) + if version is None: + return False + return self.version_ok(str(version)) + + +def maybe_close(f): + @contextlib.contextmanager + def empty(): + yield + return + + if not f: + return empty() + + return contextlib.closing(f) + + +# Some objects are not available on some platforms. +# XXX it'd be better to test assertions about bytecode instead. +if not sys.platform.startswith('java') and sys.platform != 'cli': + + def get_module_constant( + module, symbol, default: _T | int = -1, paths=None + ) -> _T | int | None | Any: + """Find 'module' by searching 'paths', and extract 'symbol' + + Return 'None' if 'module' does not exist on 'paths', or it does not define + 'symbol'. If the module defines 'symbol' as a constant, return the + constant. Otherwise, return 'default'.""" + + try: + f, path, (_suffix, _mode, kind) = info = find_module(module, paths) + except ImportError: + # Module doesn't exist + return None + + with maybe_close(f): + if kind == PY_COMPILED: + f.read(8) # skip magic & date + code = marshal.load(f) + elif kind == PY_FROZEN: + code = _imp.get_frozen_object(module, paths) + elif kind == PY_SOURCE: + code = compile(f.read(), path, 'exec') + else: + # Not something we can parse; we'll have to import it. :( + imported = _imp.get_module(module, paths, info) + return getattr(imported, symbol, None) + + return extract_constant(code, symbol, default) + + def extract_constant( + code: CodeType, symbol: str, default: _T | int = -1 + ) -> _T | int | None | Any: + """Extract the constant value of 'symbol' from 'code' + + If the name 'symbol' is bound to a constant value by the Python code + object 'code', return that value. If 'symbol' is bound to an expression, + return 'default'. Otherwise, return 'None'. + + Return value is based on the first assignment to 'symbol'. 'symbol' must + be a global, or at least a non-"fast" local in the code block. That is, + only 'STORE_NAME' and 'STORE_GLOBAL' opcodes are checked, and 'symbol' + must be present in 'code.co_names'. + """ + if symbol not in code.co_names: + # name's not there, can't possibly be an assignment + return None + + name_idx = list(code.co_names).index(symbol) + + STORE_NAME = dis.opmap['STORE_NAME'] + STORE_GLOBAL = dis.opmap['STORE_GLOBAL'] + LOAD_CONST = dis.opmap['LOAD_CONST'] + + const = default + + for byte_code in dis.Bytecode(code): + op = byte_code.opcode + arg = byte_code.arg + + if op == LOAD_CONST: + assert arg is not None + const = code.co_consts[arg] + elif arg == name_idx and (op == STORE_NAME or op == STORE_GLOBAL): + return const + else: + const = default + + return None + + __all__ += ['get_module_constant', 'extract_constant'] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/discovery.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/discovery.py new file mode 100644 index 0000000000000000000000000000000000000000..c88839918562bad12f1a2e72309f1eacfe23349c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/discovery.py @@ -0,0 +1,614 @@ +"""Automatic discovery of Python modules and packages (for inclusion in the +distribution) and other config values. + +For the purposes of this module, the following nomenclature is used: + +- "src-layout": a directory representing a Python project that contains a "src" + folder. Everything under the "src" folder is meant to be included in the + distribution when packaging the project. Example:: + + . + ├── tox.ini + ├── pyproject.toml + └── src/ + └── mypkg/ + ├── __init__.py + ├── mymodule.py + └── my_data_file.txt + +- "flat-layout": a Python project that does not use "src-layout" but instead + have a directory under the project root for each package:: + + . + ├── tox.ini + ├── pyproject.toml + └── mypkg/ + ├── __init__.py + ├── mymodule.py + └── my_data_file.txt + +- "single-module": a project that contains a single Python script direct under + the project root (no directory used):: + + . + ├── tox.ini + ├── pyproject.toml + └── mymodule.py + +""" + +from __future__ import annotations + +import itertools +import os +from collections.abc import Iterable, Iterator, Mapping +from fnmatch import fnmatchcase +from glob import glob +from pathlib import Path +from typing import TYPE_CHECKING, ClassVar + +import _distutils_hack.override # noqa: F401 + +from ._path import StrPath + +from distutils import log +from distutils.util import convert_path + +if TYPE_CHECKING: + from setuptools import Distribution + +chain_iter = itertools.chain.from_iterable + + +def _valid_name(path: StrPath) -> bool: + # Ignore invalid names that cannot be imported directly + return os.path.basename(path).isidentifier() + + +class _Filter: + """ + Given a list of patterns, create a callable that will be true only if + the input matches at least one of the patterns. + """ + + def __init__(self, *patterns: str) -> None: + self._patterns = dict.fromkeys(patterns) + + def __call__(self, item: str) -> bool: + return any(fnmatchcase(item, pat) for pat in self._patterns) + + def __contains__(self, item: str) -> bool: + return item in self._patterns + + +class _Finder: + """Base class that exposes functionality for module/package finders""" + + ALWAYS_EXCLUDE: ClassVar[tuple[str, ...]] = () + DEFAULT_EXCLUDE: ClassVar[tuple[str, ...]] = () + + @classmethod + def find( + cls, + where: StrPath = '.', + exclude: Iterable[str] = (), + include: Iterable[str] = ('*',), + ) -> list[str]: + """Return a list of all Python items (packages or modules, depending on + the finder implementation) found within directory 'where'. + + 'where' is the root directory which will be searched. + It should be supplied as a "cross-platform" (i.e. URL-style) path; + it will be converted to the appropriate local path syntax. + + 'exclude' is a sequence of names to exclude; '*' can be used + as a wildcard in the names. + When finding packages, 'foo.*' will exclude all subpackages of 'foo' + (but not 'foo' itself). + + 'include' is a sequence of names to include. + If it's specified, only the named items will be included. + If it's not specified, all found items will be included. + 'include' can contain shell style wildcard patterns just like + 'exclude'. + """ + + exclude = exclude or cls.DEFAULT_EXCLUDE + return list( + cls._find_iter( + convert_path(str(where)), + _Filter(*cls.ALWAYS_EXCLUDE, *exclude), + _Filter(*include), + ) + ) + + @classmethod + def _find_iter( + cls, where: StrPath, exclude: _Filter, include: _Filter + ) -> Iterator[str]: + raise NotImplementedError + + +class PackageFinder(_Finder): + """ + Generate a list of all Python packages found within a directory + """ + + ALWAYS_EXCLUDE = ("ez_setup", "*__pycache__") + + @classmethod + def _find_iter( + cls, where: StrPath, exclude: _Filter, include: _Filter + ) -> Iterator[str]: + """ + All the packages found in 'where' that pass the 'include' filter, but + not the 'exclude' filter. + """ + for root, dirs, files in os.walk(str(where), followlinks=True): + # Copy dirs to iterate over it, then empty dirs. + all_dirs = dirs[:] + dirs[:] = [] + + for dir in all_dirs: + full_path = os.path.join(root, dir) + rel_path = os.path.relpath(full_path, where) + package = rel_path.replace(os.path.sep, '.') + + # Skip directory trees that are not valid packages + if '.' in dir or not cls._looks_like_package(full_path, package): + continue + + # Should this package be included? + if include(package) and not exclude(package): + yield package + + # Early pruning if there is nothing else to be scanned + if f"{package}*" in exclude or f"{package}.*" in exclude: + continue + + # Keep searching subdirectories, as there may be more packages + # down there, even if the parent was excluded. + dirs.append(dir) + + @staticmethod + def _looks_like_package(path: StrPath, _package_name: str) -> bool: + """Does a directory look like a package?""" + return os.path.isfile(os.path.join(path, '__init__.py')) + + +class PEP420PackageFinder(PackageFinder): + @staticmethod + def _looks_like_package(_path: StrPath, _package_name: str) -> bool: + return True + + +class ModuleFinder(_Finder): + """Find isolated Python modules. + This function will **not** recurse subdirectories. + """ + + @classmethod + def _find_iter( + cls, where: StrPath, exclude: _Filter, include: _Filter + ) -> Iterator[str]: + for file in glob(os.path.join(where, "*.py")): + module, _ext = os.path.splitext(os.path.basename(file)) + + if not cls._looks_like_module(module): + continue + + if include(module) and not exclude(module): + yield module + + _looks_like_module = staticmethod(_valid_name) + + +# We have to be extra careful in the case of flat layout to not include files +# and directories not meant for distribution (e.g. tool-related) + + +class FlatLayoutPackageFinder(PEP420PackageFinder): + _EXCLUDE = ( + "ci", + "bin", + "debian", + "doc", + "docs", + "documentation", + "manpages", + "news", + "newsfragments", + "changelog", + "test", + "tests", + "unit_test", + "unit_tests", + "example", + "examples", + "scripts", + "tools", + "util", + "utils", + "python", + "build", + "dist", + "venv", + "env", + "requirements", + # ---- Task runners / Build tools ---- + "tasks", # invoke + "fabfile", # fabric + "site_scons", # SCons + # ---- Other tools ---- + "benchmark", + "benchmarks", + "exercise", + "exercises", + "htmlcov", # Coverage.py + # ---- Hidden directories/Private packages ---- + "[._]*", + ) + + DEFAULT_EXCLUDE = tuple(chain_iter((p, f"{p}.*") for p in _EXCLUDE)) + """Reserved package names""" + + @staticmethod + def _looks_like_package(_path: StrPath, package_name: str) -> bool: + names = package_name.split('.') + # Consider PEP 561 + root_pkg_is_valid = names[0].isidentifier() or names[0].endswith("-stubs") + return root_pkg_is_valid and all(name.isidentifier() for name in names[1:]) + + +class FlatLayoutModuleFinder(ModuleFinder): + DEFAULT_EXCLUDE = ( + "setup", + "conftest", + "test", + "tests", + "example", + "examples", + "build", + # ---- Task runners ---- + "toxfile", + "noxfile", + "pavement", + "dodo", + "tasks", + "fabfile", + # ---- Other tools ---- + "[Ss][Cc]onstruct", # SCons + "conanfile", # Connan: C/C++ build tool + "manage", # Django + "benchmark", + "benchmarks", + "exercise", + "exercises", + # ---- Hidden files/Private modules ---- + "[._]*", + ) + """Reserved top-level module names""" + + +def _find_packages_within(root_pkg: str, pkg_dir: StrPath) -> list[str]: + nested = PEP420PackageFinder.find(pkg_dir) + return [root_pkg] + [".".join((root_pkg, n)) for n in nested] + + +class ConfigDiscovery: + """Fill-in metadata and options that can be automatically derived + (from other metadata/options, the file system or conventions) + """ + + def __init__(self, distribution: Distribution) -> None: + self.dist = distribution + self._called = False + self._disabled = False + self._skip_ext_modules = False + + def _disable(self): + """Internal API to disable automatic discovery""" + self._disabled = True + + def _ignore_ext_modules(self): + """Internal API to disregard ext_modules. + + Normally auto-discovery would not be triggered if ``ext_modules`` are set + (this is done for backward compatibility with existing packages relying on + ``setup.py`` or ``setup.cfg``). However, ``setuptools`` can call this function + to ignore given ``ext_modules`` and proceed with the auto-discovery if + ``packages`` and ``py_modules`` are not given (e.g. when using pyproject.toml + metadata). + """ + self._skip_ext_modules = True + + @property + def _root_dir(self) -> StrPath: + # The best is to wait until `src_root` is set in dist, before using _root_dir. + return self.dist.src_root or os.curdir + + @property + def _package_dir(self) -> dict[str, str]: + if self.dist.package_dir is None: + return {} + return self.dist.package_dir + + def __call__( + self, force: bool = False, name: bool = True, ignore_ext_modules: bool = False + ): + """Automatically discover missing configuration fields + and modifies the given ``distribution`` object in-place. + + Note that by default this will only have an effect the first time the + ``ConfigDiscovery`` object is called. + + To repeatedly invoke automatic discovery (e.g. when the project + directory changes), please use ``force=True`` (or create a new + ``ConfigDiscovery`` instance). + """ + if force is False and (self._called or self._disabled): + # Avoid overhead of multiple calls + return + + self._analyse_package_layout(ignore_ext_modules) + if name: + self.analyse_name() # depends on ``packages`` and ``py_modules`` + + self._called = True + + def _explicitly_specified(self, ignore_ext_modules: bool) -> bool: + """``True`` if the user has specified some form of package/module listing""" + ignore_ext_modules = ignore_ext_modules or self._skip_ext_modules + ext_modules = not (self.dist.ext_modules is None or ignore_ext_modules) + return ( + self.dist.packages is not None + or self.dist.py_modules is not None + or ext_modules + or hasattr(self.dist, "configuration") + and self.dist.configuration + # ^ Some projects use numpy.distutils.misc_util.Configuration + ) + + def _analyse_package_layout(self, ignore_ext_modules: bool) -> bool: + if self._explicitly_specified(ignore_ext_modules): + # For backward compatibility, just try to find modules/packages + # when nothing is given + return True + + log.debug( + "No `packages` or `py_modules` configuration, performing " + "automatic discovery." + ) + + return ( + self._analyse_explicit_layout() + or self._analyse_src_layout() + # flat-layout is the trickiest for discovery so it should be last + or self._analyse_flat_layout() + ) + + def _analyse_explicit_layout(self) -> bool: + """The user can explicitly give a package layout via ``package_dir``""" + package_dir = self._package_dir.copy() # don't modify directly + package_dir.pop("", None) # This falls under the "src-layout" umbrella + root_dir = self._root_dir + + if not package_dir: + return False + + log.debug(f"`explicit-layout` detected -- analysing {package_dir}") + pkgs = chain_iter( + _find_packages_within(pkg, os.path.join(root_dir, parent_dir)) + for pkg, parent_dir in package_dir.items() + ) + self.dist.packages = list(pkgs) + log.debug(f"discovered packages -- {self.dist.packages}") + return True + + def _analyse_src_layout(self) -> bool: + """Try to find all packages or modules under the ``src`` directory + (or anything pointed by ``package_dir[""]``). + + The "src-layout" is relatively safe for automatic discovery. + We assume that everything within is meant to be included in the + distribution. + + If ``package_dir[""]`` is not given, but the ``src`` directory exists, + this function will set ``package_dir[""] = "src"``. + """ + package_dir = self._package_dir + src_dir = os.path.join(self._root_dir, package_dir.get("", "src")) + if not os.path.isdir(src_dir): + return False + + log.debug(f"`src-layout` detected -- analysing {src_dir}") + package_dir.setdefault("", os.path.basename(src_dir)) + self.dist.package_dir = package_dir # persist eventual modifications + self.dist.packages = PEP420PackageFinder.find(src_dir) + self.dist.py_modules = ModuleFinder.find(src_dir) + log.debug(f"discovered packages -- {self.dist.packages}") + log.debug(f"discovered py_modules -- {self.dist.py_modules}") + return True + + def _analyse_flat_layout(self) -> bool: + """Try to find all packages and modules under the project root. + + Since the ``flat-layout`` is more dangerous in terms of accidentally including + extra files/directories, this function is more conservative and will raise an + error if multiple packages or modules are found. + + This assumes that multi-package dists are uncommon and refuse to support that + use case in order to be able to prevent unintended errors. + """ + log.debug(f"`flat-layout` detected -- analysing {self._root_dir}") + return self._analyse_flat_packages() or self._analyse_flat_modules() + + def _analyse_flat_packages(self) -> bool: + self.dist.packages = FlatLayoutPackageFinder.find(self._root_dir) + top_level = remove_nested_packages(remove_stubs(self.dist.packages)) + log.debug(f"discovered packages -- {self.dist.packages}") + self._ensure_no_accidental_inclusion(top_level, "packages") + return bool(top_level) + + def _analyse_flat_modules(self) -> bool: + self.dist.py_modules = FlatLayoutModuleFinder.find(self._root_dir) + log.debug(f"discovered py_modules -- {self.dist.py_modules}") + self._ensure_no_accidental_inclusion(self.dist.py_modules, "modules") + return bool(self.dist.py_modules) + + def _ensure_no_accidental_inclusion(self, detected: list[str], kind: str): + if len(detected) > 1: + from inspect import cleandoc + + from setuptools.errors import PackageDiscoveryError + + msg = f"""Multiple top-level {kind} discovered in a flat-layout: {detected}. + + To avoid accidental inclusion of unwanted files or directories, + setuptools will not proceed with this build. + + If you are trying to create a single distribution with multiple {kind} + on purpose, you should not rely on automatic discovery. + Instead, consider the following options: + + 1. set up custom discovery (`find` directive with `include` or `exclude`) + 2. use a `src-layout` + 3. explicitly set `py_modules` or `packages` with a list of names + + To find more information, look for "package discovery" on setuptools docs. + """ + raise PackageDiscoveryError(cleandoc(msg)) + + def analyse_name(self) -> None: + """The packages/modules are the essential contribution of the author. + Therefore the name of the distribution can be derived from them. + """ + if self.dist.metadata.name or self.dist.name: + # get_name() is not reliable (can return "UNKNOWN") + return + + log.debug("No `name` configuration, performing automatic discovery") + + name = ( + self._find_name_single_package_or_module() + or self._find_name_from_packages() + ) + if name: + self.dist.metadata.name = name + + def _find_name_single_package_or_module(self) -> str | None: + """Exactly one module or package""" + for field in ('packages', 'py_modules'): + items = getattr(self.dist, field, None) or [] + if items and len(items) == 1: + log.debug(f"Single module/package detected, name: {items[0]}") + return items[0] + + return None + + def _find_name_from_packages(self) -> str | None: + """Try to find the root package that is not a PEP 420 namespace""" + if not self.dist.packages: + return None + + packages = remove_stubs(sorted(self.dist.packages, key=len)) + package_dir = self.dist.package_dir or {} + + parent_pkg = find_parent_package(packages, package_dir, self._root_dir) + if parent_pkg: + log.debug(f"Common parent package detected, name: {parent_pkg}") + return parent_pkg + + log.warn("No parent package detected, impossible to derive `name`") + return None + + +def remove_nested_packages(packages: list[str]) -> list[str]: + """Remove nested packages from a list of packages. + + >>> remove_nested_packages(["a", "a.b1", "a.b2", "a.b1.c1"]) + ['a'] + >>> remove_nested_packages(["a", "b", "c.d", "c.d.e.f", "g.h", "a.a1"]) + ['a', 'b', 'c.d', 'g.h'] + """ + pkgs = sorted(packages, key=len) + top_level = pkgs[:] + size = len(pkgs) + for i, name in enumerate(reversed(pkgs)): + if any(name.startswith(f"{other}.") for other in top_level): + top_level.pop(size - i - 1) + + return top_level + + +def remove_stubs(packages: list[str]) -> list[str]: + """Remove type stubs (:pep:`561`) from a list of packages. + + >>> remove_stubs(["a", "a.b", "a-stubs", "a-stubs.b.c", "b", "c-stubs"]) + ['a', 'a.b', 'b'] + """ + return [pkg for pkg in packages if not pkg.split(".")[0].endswith("-stubs")] + + +def find_parent_package( + packages: list[str], package_dir: Mapping[str, str], root_dir: StrPath +) -> str | None: + """Find the parent package that is not a namespace.""" + packages = sorted(packages, key=len) + common_ancestors = [] + for i, name in enumerate(packages): + if not all(n.startswith(f"{name}.") for n in packages[i + 1 :]): + # Since packages are sorted by length, this condition is able + # to find a list of all common ancestors. + # When there is divergence (e.g. multiple root packages) + # the list will be empty + break + common_ancestors.append(name) + + for name in common_ancestors: + pkg_path = find_package_path(name, package_dir, root_dir) + init = os.path.join(pkg_path, "__init__.py") + if os.path.isfile(init): + return name + + return None + + +def find_package_path( + name: str, package_dir: Mapping[str, str], root_dir: StrPath +) -> str: + """Given a package name, return the path where it should be found on + disk, considering the ``package_dir`` option. + + >>> path = find_package_path("my.pkg", {"": "root/is/nested"}, ".") + >>> path.replace(os.sep, "/") + './root/is/nested/my/pkg' + + >>> path = find_package_path("my.pkg", {"my": "root/is/nested"}, ".") + >>> path.replace(os.sep, "/") + './root/is/nested/pkg' + + >>> path = find_package_path("my.pkg", {"my.pkg": "root/is/nested"}, ".") + >>> path.replace(os.sep, "/") + './root/is/nested' + + >>> path = find_package_path("other.pkg", {"my.pkg": "root/is/nested"}, ".") + >>> path.replace(os.sep, "/") + './other/pkg' + """ + parts = name.split(".") + for i in range(len(parts), 0, -1): + # Look backwards, the most specific package_dir first + partial_name = ".".join(parts[:i]) + if partial_name in package_dir: + parent = package_dir[partial_name] + return os.path.join(root_dir, parent, *parts[i:]) + + parent = package_dir.get("") or "" + return os.path.join(root_dir, *parent.split("/"), *parts) + + +def construct_package_dir(packages: list[str], package_path: StrPath) -> dict[str, str]: + parent_pkgs = remove_nested_packages(packages) + prefix = Path(package_path).parts + return {pkg: "/".join([*prefix, *pkg.split(".")]) for pkg in parent_pkgs} diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/dist.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/dist.py new file mode 100644 index 0000000000000000000000000000000000000000..8d972cc49bda84edee28c90be172b17107f00b07 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/dist.py @@ -0,0 +1,1121 @@ +from __future__ import annotations + +import functools +import io +import itertools +import numbers +import os +import re +import sys +from collections.abc import Iterable, Iterator, MutableMapping, Sequence +from glob import glob +from pathlib import Path +from typing import TYPE_CHECKING, Any, Union + +from more_itertools import partition, unique_everseen +from packaging.markers import InvalidMarker, Marker +from packaging.specifiers import InvalidSpecifier, SpecifierSet +from packaging.version import Version + +from . import ( + _entry_points, + _reqs, + _static, + command as _, # noqa: F401 # imported for side-effects +) +from ._importlib import metadata +from ._normalization import _canonicalize_license_expression +from ._path import StrPath +from ._reqs import _StrOrIter +from .config import pyprojecttoml, setupcfg +from .discovery import ConfigDiscovery +from .errors import InvalidConfigError +from .monkey import get_unpatched +from .warnings import InformationOnly, SetuptoolsDeprecationWarning + +import distutils.cmd +import distutils.command +import distutils.core +import distutils.dist +import distutils.log +from distutils.debug import DEBUG +from distutils.errors import DistutilsOptionError, DistutilsSetupError +from distutils.fancy_getopt import translate_longopt +from distutils.util import strtobool + +if TYPE_CHECKING: + from typing_extensions import TypeAlias + + from pkg_resources import Distribution as _pkg_resources_Distribution + + +__all__ = ['Distribution'] + +_sequence = tuple, list +""" +:meta private: + +Supported iterable types that are known to be: +- ordered (which `set` isn't) +- not match a str (which `Sequence[str]` does) +- not imply a nested type (like `dict`) +for use with `isinstance`. +""" +_Sequence: TypeAlias = Union[tuple[str, ...], list[str]] +# This is how stringifying _Sequence would look in Python 3.10 +_sequence_type_repr = "tuple[str, ...] | list[str]" +_OrderedStrSequence: TypeAlias = Union[str, dict[str, Any], Sequence[str]] +""" +:meta private: +Avoid single-use iterable. Disallow sets. +A poor approximation of an OrderedSequence (dict doesn't match a Sequence). +""" + + +def __getattr__(name: str) -> Any: # pragma: no cover + if name == "sequence": + SetuptoolsDeprecationWarning.emit( + "`setuptools.dist.sequence` is an internal implementation detail.", + "Please define your own `sequence = tuple, list` instead.", + due_date=(2025, 8, 28), # Originally added on 2024-08-27 + ) + return _sequence + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + + +def check_importable(dist, attr, value): + try: + ep = metadata.EntryPoint(value=value, name=None, group=None) + assert not ep.extras + except (TypeError, ValueError, AttributeError, AssertionError) as e: + raise DistutilsSetupError( + f"{attr!r} must be importable 'module:attrs' string (got {value!r})" + ) from e + + +def assert_string_list(dist, attr: str, value: _Sequence) -> None: + """Verify that value is a string list""" + try: + # verify that value is a list or tuple to exclude unordered + # or single-use iterables + assert isinstance(value, _sequence) + # verify that elements of value are strings + assert ''.join(value) != value + except (TypeError, ValueError, AttributeError, AssertionError) as e: + raise DistutilsSetupError( + f"{attr!r} must be of type <{_sequence_type_repr}> (got {value!r})" + ) from e + + +def check_nsp(dist, attr, value): + """Verify that namespace packages are valid""" + ns_packages = value + assert_string_list(dist, attr, ns_packages) + for nsp in ns_packages: + if not dist.has_contents_for(nsp): + raise DistutilsSetupError( + f"Distribution contains no modules or packages for namespace package {nsp!r}" + ) + parent, _sep, _child = nsp.rpartition('.') + if parent and parent not in ns_packages: + distutils.log.warn( + "WARNING: %r is declared as a package namespace, but %r" + " is not: please correct this in setup.py", + nsp, + parent, + ) + SetuptoolsDeprecationWarning.emit( + "The namespace_packages parameter is deprecated.", + "Please replace its usage with implicit namespaces (PEP 420).", + see_docs="references/keywords.html#keyword-namespace-packages", + # TODO: define due_date, it may break old packages that are no longer + # maintained (e.g. sphinxcontrib extensions) when installed from source. + # Warning officially introduced in May 2022, however the deprecation + # was mentioned much earlier in the docs (May 2020, see #2149). + ) + + +def check_extras(dist, attr, value): + """Verify that extras_require mapping is valid""" + try: + list(itertools.starmap(_check_extra, value.items())) + except (TypeError, ValueError, AttributeError) as e: + raise DistutilsSetupError( + "'extras_require' must be a dictionary whose values are " + "strings or lists of strings containing valid project/version " + "requirement specifiers." + ) from e + + +def _check_extra(extra, reqs): + _name, _sep, marker = extra.partition(':') + try: + _check_marker(marker) + except InvalidMarker: + msg = f"Invalid environment marker: {marker} ({extra!r})" + raise DistutilsSetupError(msg) from None + list(_reqs.parse(reqs)) + + +def _check_marker(marker): + if not marker: + return + m = Marker(marker) + m.evaluate() + + +def assert_bool(dist, attr, value): + """Verify that value is True, False, 0, or 1""" + if bool(value) != value: + raise DistutilsSetupError(f"{attr!r} must be a boolean value (got {value!r})") + + +def invalid_unless_false(dist, attr, value): + if not value: + DistDeprecationWarning.emit(f"{attr} is ignored.") + # TODO: should there be a `due_date` here? + return + raise DistutilsSetupError(f"{attr} is invalid.") + + +def check_requirements(dist, attr: str, value: _OrderedStrSequence) -> None: + """Verify that install_requires is a valid requirements list""" + try: + list(_reqs.parse(value)) + if isinstance(value, set): + raise TypeError("Unordered types are not allowed") + except (TypeError, ValueError) as error: + msg = ( + f"{attr!r} must be a string or iterable of strings " + f"containing valid project/version requirement specifiers; {error}" + ) + raise DistutilsSetupError(msg) from error + + +def check_specifier(dist, attr, value): + """Verify that value is a valid version specifier""" + try: + SpecifierSet(value) + except (InvalidSpecifier, AttributeError) as error: + msg = f"{attr!r} must be a string containing valid version specifiers; {error}" + raise DistutilsSetupError(msg) from error + + +def check_entry_points(dist, attr, value): + """Verify that entry_points map is parseable""" + try: + _entry_points.load(value) + except Exception as e: + raise DistutilsSetupError(e) from e + + +def check_package_data(dist, attr, value): + """Verify that value is a dictionary of package names to glob lists""" + if not isinstance(value, dict): + raise DistutilsSetupError( + f"{attr!r} must be a dictionary mapping package names to lists of " + "string wildcard patterns" + ) + for k, v in value.items(): + if not isinstance(k, str): + raise DistutilsSetupError( + f"keys of {attr!r} dict must be strings (got {k!r})" + ) + assert_string_list(dist, f'values of {attr!r} dict', v) + + +def check_packages(dist, attr, value): + for pkgname in value: + if not re.match(r'\w+(\.\w+)*', pkgname): + distutils.log.warn( + "WARNING: %r not a valid package name; please use only " + ".-separated package names in setup.py", + pkgname, + ) + + +if TYPE_CHECKING: + # Work around a mypy issue where type[T] can't be used as a base: https://github.com/python/mypy/issues/10962 + from distutils.core import Distribution as _Distribution +else: + _Distribution = get_unpatched(distutils.core.Distribution) + + +class Distribution(_Distribution): + """Distribution with support for tests and package data + + This is an enhanced version of 'distutils.dist.Distribution' that + effectively adds the following new optional keyword arguments to 'setup()': + + 'install_requires' -- a string or sequence of strings specifying project + versions that the distribution requires when installed, in the format + used by 'pkg_resources.require()'. They will be installed + automatically when the package is installed. If you wish to use + packages that are not available in PyPI, or want to give your users an + alternate download location, you can add a 'find_links' option to the + '[easy_install]' section of your project's 'setup.cfg' file, and then + setuptools will scan the listed web pages for links that satisfy the + requirements. + + 'extras_require' -- a dictionary mapping names of optional "extras" to the + additional requirement(s) that using those extras incurs. For example, + this:: + + extras_require = dict(reST = ["docutils>=0.3", "reSTedit"]) + + indicates that the distribution can optionally provide an extra + capability called "reST", but it can only be used if docutils and + reSTedit are installed. If the user installs your package using + EasyInstall and requests one of your extras, the corresponding + additional requirements will be installed if needed. + + 'package_data' -- a dictionary mapping package names to lists of filenames + or globs to use to find data files contained in the named packages. + If the dictionary has filenames or globs listed under '""' (the empty + string), those names will be searched for in every package, in addition + to any names for the specific package. Data files found using these + names/globs will be installed along with the package, in the same + location as the package. Note that globs are allowed to reference + the contents of non-package subdirectories, as long as you use '/' as + a path separator. (Globs are automatically converted to + platform-specific paths at runtime.) + + In addition to these new keywords, this class also has several new methods + for manipulating the distribution's contents. For example, the 'include()' + and 'exclude()' methods can be thought of as in-place add and subtract + commands that add or remove packages, modules, extensions, and so on from + the distribution. + """ + + _DISTUTILS_UNSUPPORTED_METADATA = { + 'long_description_content_type': lambda: None, + 'project_urls': dict, + 'provides_extras': dict, # behaves like an ordered set + 'license_expression': lambda: None, + 'license_file': lambda: None, + 'license_files': lambda: None, + 'install_requires': list, + 'extras_require': dict, + } + + # Used by build_py, editable_wheel and install_lib commands for legacy namespaces + namespace_packages: list[str] #: :meta private: DEPRECATED + + # Any: Dynamic assignment results in Incompatible types in assignment + def __init__(self, attrs: MutableMapping[str, Any] | None = None) -> None: + have_package_data = hasattr(self, "package_data") + if not have_package_data: + self.package_data: dict[str, list[str]] = {} + attrs = attrs or {} + self.dist_files: list[tuple[str, str, str]] = [] + self.include_package_data: bool | None = None + self.exclude_package_data: dict[str, list[str]] | None = None + # Filter-out setuptools' specific options. + self.src_root: str | None = attrs.pop("src_root", None) + self.dependency_links: list[str] = attrs.pop('dependency_links', []) + self.setup_requires: list[str] = attrs.pop('setup_requires', []) + for ep in metadata.entry_points(group='distutils.setup_keywords'): + vars(self).setdefault(ep.name, None) + + metadata_only = set(self._DISTUTILS_UNSUPPORTED_METADATA) + metadata_only -= {"install_requires", "extras_require"} + dist_attrs = {k: v for k, v in attrs.items() if k not in metadata_only} + _Distribution.__init__(self, dist_attrs) + + # Private API (setuptools-use only, not restricted to Distribution) + # Stores files that are referenced by the configuration and need to be in the + # sdist (e.g. `version = file: VERSION.txt`) + self._referenced_files = set[str]() + + self.set_defaults = ConfigDiscovery(self) + + self._set_metadata_defaults(attrs) + + self.metadata.version = self._normalize_version(self.metadata.version) + self._finalize_requires() + + def _validate_metadata(self): + required = {"name"} + provided = { + key + for key in vars(self.metadata) + if getattr(self.metadata, key, None) is not None + } + missing = required - provided + + if missing: + msg = f"Required package metadata is missing: {missing}" + raise DistutilsSetupError(msg) + + def _set_metadata_defaults(self, attrs): + """ + Fill-in missing metadata fields not supported by distutils. + Some fields may have been set by other tools (e.g. pbr). + Those fields (vars(self.metadata)) take precedence to + supplied attrs. + """ + for option, default in self._DISTUTILS_UNSUPPORTED_METADATA.items(): + vars(self.metadata).setdefault(option, attrs.get(option, default())) + + @staticmethod + def _normalize_version(version): + from . import sic + + if isinstance(version, numbers.Number): + # Some people apparently take "version number" too literally :) + version = str(version) + elif isinstance(version, sic) or version is None: + return version + + normalized = str(Version(version)) + if version != normalized: + InformationOnly.emit(f"Normalizing '{version}' to '{normalized}'") + return normalized + return version + + def _finalize_requires(self): + """ + Set `metadata.python_requires` and fix environment markers + in `install_requires` and `extras_require`. + """ + if getattr(self, 'python_requires', None): + self.metadata.python_requires = self.python_requires + + self._normalize_requires() + self.metadata.install_requires = self.install_requires + self.metadata.extras_require = self.extras_require + + if self.extras_require: + for extra in self.extras_require.keys(): + # Setuptools allows a weird ": syntax for extras + extra = extra.split(':')[0] + if extra: + self.metadata.provides_extras.setdefault(extra) + + def _normalize_requires(self): + """Make sure requirement-related attributes exist and are normalized""" + install_requires = getattr(self, "install_requires", None) or [] + extras_require = getattr(self, "extras_require", None) or {} + + # Preserve the "static"-ness of values parsed from config files + list_ = _static.List if _static.is_static(install_requires) else list + self.install_requires = list_(map(str, _reqs.parse(install_requires))) + + dict_ = _static.Dict if _static.is_static(extras_require) else dict + self.extras_require = dict_( + (k, list(map(str, _reqs.parse(v or [])))) for k, v in extras_require.items() + ) + + def _finalize_license_expression(self) -> None: + """ + Normalize license and license_expression. + >>> dist = Distribution({"license_expression": _static.Str("mit aNd gpl-3.0-OR-later")}) + >>> _static.is_static(dist.metadata.license_expression) + True + >>> dist._finalize_license_expression() + >>> _static.is_static(dist.metadata.license_expression) # preserve "static-ness" + True + >>> print(dist.metadata.license_expression) + MIT AND GPL-3.0-or-later + """ + classifiers = self.metadata.get_classifiers() + license_classifiers = [cl for cl in classifiers if cl.startswith("License :: ")] + + license_expr = self.metadata.license_expression + if license_expr: + str_ = _static.Str if _static.is_static(license_expr) else str + normalized = str_(_canonicalize_license_expression(license_expr)) + if license_expr != normalized: + InformationOnly.emit(f"Normalizing '{license_expr}' to '{normalized}'") + self.metadata.license_expression = normalized + if license_classifiers: + raise InvalidConfigError( + "License classifiers have been superseded by license expressions " + "(see https://peps.python.org/pep-0639/). Please remove:\n\n" + + "\n".join(license_classifiers), + ) + elif license_classifiers: + pypa_guides = "guides/writing-pyproject-toml/#license" + SetuptoolsDeprecationWarning.emit( + "License classifiers are deprecated.", + "Please consider removing the following classifiers in favor of a " + "SPDX license expression:\n\n" + "\n".join(license_classifiers), + see_url=f"https://packaging.python.org/en/latest/{pypa_guides}", + # Warning introduced on 2025-02-17 + # TODO: Should we add a due date? It may affect old/unmaintained + # packages in the ecosystem and cause problems... + ) + + def _finalize_license_files(self) -> None: + """Compute names of all license files which should be included.""" + license_files: list[str] | None = self.metadata.license_files + patterns = license_files or [] + + license_file: str | None = self.metadata.license_file + if license_file and license_file not in patterns: + patterns.append(license_file) + + if license_files is None and license_file is None: + # Default patterns match the ones wheel uses + # See https://wheel.readthedocs.io/en/stable/user_guide.html + # -> 'Including license files in the generated wheel file' + patterns = ['LICEN[CS]E*', 'COPYING*', 'NOTICE*', 'AUTHORS*'] + files = self._expand_patterns(patterns, enforce_match=False) + else: # Patterns explicitly given by the user + files = self._expand_patterns(patterns, enforce_match=True) + + self.metadata.license_files = list(unique_everseen(files)) + + @classmethod + def _expand_patterns( + cls, patterns: list[str], enforce_match: bool = True + ) -> Iterator[str]: + """ + >>> list(Distribution._expand_patterns(['LICENSE'])) + ['LICENSE'] + >>> list(Distribution._expand_patterns(['pyproject.toml', 'LIC*'])) + ['pyproject.toml', 'LICENSE'] + >>> list(Distribution._expand_patterns(['setuptools/**/pyprojecttoml.py'])) + ['setuptools/config/pyprojecttoml.py'] + """ + return ( + path.replace(os.sep, "/") + for pattern in patterns + for path in sorted(cls._find_pattern(pattern, enforce_match)) + if not path.endswith('~') and os.path.isfile(path) + ) + + @staticmethod + def _find_pattern(pattern: str, enforce_match: bool = True) -> list[str]: + r""" + >>> Distribution._find_pattern("LICENSE") + ['LICENSE'] + >>> Distribution._find_pattern("/LICENSE.MIT") + Traceback (most recent call last): + ... + setuptools.errors.InvalidConfigError: Pattern '/LICENSE.MIT' should be relative... + >>> Distribution._find_pattern("../LICENSE.MIT") + Traceback (most recent call last): + ... + setuptools.warnings.SetuptoolsDeprecationWarning: ...Pattern '../LICENSE.MIT' cannot contain '..'... + >>> Distribution._find_pattern("LICEN{CSE*") + Traceback (most recent call last): + ... + setuptools.warnings.SetuptoolsDeprecationWarning: ...Pattern 'LICEN{CSE*' contains invalid characters... + """ + pypa_guides = "specifications/glob-patterns/" + if ".." in pattern: + SetuptoolsDeprecationWarning.emit( + f"Pattern {pattern!r} cannot contain '..'", + """ + Please ensure the files specified are contained by the root + of the Python package (normally marked by `pyproject.toml`). + """, + see_url=f"https://packaging.python.org/en/latest/{pypa_guides}", + due_date=(2026, 3, 20), # Introduced in 2025-03-20 + # Replace with InvalidConfigError after deprecation + ) + if pattern.startswith((os.sep, "/")) or ":\\" in pattern: + raise InvalidConfigError( + f"Pattern {pattern!r} should be relative and must not start with '/'" + ) + if re.match(r'^[\w\-\.\/\*\?\[\]]+$', pattern) is None: + SetuptoolsDeprecationWarning.emit( + "Please provide a valid glob pattern.", + "Pattern {pattern!r} contains invalid characters.", + pattern=pattern, + see_url=f"https://packaging.python.org/en/latest/{pypa_guides}", + due_date=(2026, 3, 20), # Introduced in 2025-02-20 + ) + + found = glob(pattern, recursive=True) + + if enforce_match and not found: + SetuptoolsDeprecationWarning.emit( + "Cannot find any files for the given pattern.", + "Pattern {pattern!r} did not match any files.", + pattern=pattern, + due_date=(2026, 3, 20), # Introduced in 2025-02-20 + # PEP 639 requires us to error, but as a transition period + # we will only issue a warning to give people time to prepare. + # After the transition, this should raise an InvalidConfigError. + ) + return found + + # FIXME: 'Distribution._parse_config_files' is too complex (14) + def _parse_config_files(self, filenames=None): # noqa: C901 + """ + Adapted from distutils.dist.Distribution.parse_config_files, + this method provides the same functionality in subtly-improved + ways. + """ + from configparser import ConfigParser + + # Ignore install directory options if we have a venv + ignore_options = ( + [] + if sys.prefix == sys.base_prefix + else [ + 'install-base', + 'install-platbase', + 'install-lib', + 'install-platlib', + 'install-purelib', + 'install-headers', + 'install-scripts', + 'install-data', + 'prefix', + 'exec-prefix', + 'home', + 'user', + 'root', + ] + ) + + ignore_options = frozenset(ignore_options) + + if filenames is None: + filenames = self.find_config_files() + + if DEBUG: + self.announce("Distribution.parse_config_files():") + + parser = ConfigParser() + parser.optionxform = str + for filename in filenames: + with open(filename, encoding='utf-8') as reader: + if DEBUG: + self.announce(" reading {filename}".format(**locals())) + parser.read_file(reader) + for section in parser.sections(): + options = parser.options(section) + opt_dict = self.get_option_dict(section) + + for opt in options: + if opt == '__name__' or opt in ignore_options: + continue + + val = parser.get(section, opt) + opt = self._enforce_underscore(opt, section) + opt = self._enforce_option_lowercase(opt, section) + opt_dict[opt] = (filename, val) + + # Make the ConfigParser forget everything (so we retain + # the original filenames that options come from) + parser.__init__() + + if 'global' not in self.command_options: + return + + # If there was a "global" section in the config file, use it + # to set Distribution options. + + for opt, (src, val) in self.command_options['global'].items(): + alias = self.negative_opt.get(opt) + if alias: + val = not strtobool(val) + elif opt in ('verbose', 'dry_run'): # ugh! + val = strtobool(val) + + try: + setattr(self, alias or opt, val) + except ValueError as e: + raise DistutilsOptionError(e) from e + + def _enforce_underscore(self, opt: str, section: str) -> str: + if "-" not in opt or self._skip_setupcfg_normalization(section): + return opt + + underscore_opt = opt.replace('-', '_') + affected = f"(Affected: {self.metadata.name})." if self.metadata.name else "" + SetuptoolsDeprecationWarning.emit( + f"Invalid dash-separated key {opt!r} in {section!r} (setup.cfg), " + f"please use the underscore name {underscore_opt!r} instead.", + f""" + Usage of dash-separated {opt!r} will not be supported in future + versions. Please use the underscore name {underscore_opt!r} instead. + {affected} + """, + see_docs="userguide/declarative_config.html", + due_date=(2026, 3, 3), + # Warning initially introduced in 3 Mar 2021 + ) + return underscore_opt + + def _enforce_option_lowercase(self, opt: str, section: str) -> str: + if opt.islower() or self._skip_setupcfg_normalization(section): + return opt + + lowercase_opt = opt.lower() + affected = f"(Affected: {self.metadata.name})." if self.metadata.name else "" + SetuptoolsDeprecationWarning.emit( + f"Invalid uppercase key {opt!r} in {section!r} (setup.cfg), " + f"please use lowercase {lowercase_opt!r} instead.", + f""" + Usage of uppercase key {opt!r} in {section!r} will not be supported in + future versions. Please use lowercase {lowercase_opt!r} instead. + {affected} + """, + see_docs="userguide/declarative_config.html", + due_date=(2026, 3, 3), + # Warning initially introduced in 6 Mar 2021 + ) + return lowercase_opt + + def _skip_setupcfg_normalization(self, section: str) -> bool: + skip = ( + 'options.extras_require', + 'options.data_files', + 'options.entry_points', + 'options.package_data', + 'options.exclude_package_data', + ) + return section in skip or not self._is_setuptools_section(section) + + def _is_setuptools_section(self, section: str) -> bool: + return ( + section == "metadata" + or section.startswith("options") + or section in _setuptools_commands() + ) + + # FIXME: 'Distribution._set_command_options' is too complex (14) + def _set_command_options(self, command_obj, option_dict=None): # noqa: C901 + """ + Set the options for 'command_obj' from 'option_dict'. Basically + this means copying elements of a dictionary ('option_dict') to + attributes of an instance ('command'). + + 'command_obj' must be a Command instance. If 'option_dict' is not + supplied, uses the standard option dictionary for this command + (from 'self.command_options'). + + (Adopted from distutils.dist.Distribution._set_command_options) + """ + command_name = command_obj.get_command_name() + if option_dict is None: + option_dict = self.get_option_dict(command_name) + + if DEBUG: + self.announce(f" setting options for '{command_name}' command:") + for option, (source, value) in option_dict.items(): + if DEBUG: + self.announce(f" {option} = {value} (from {source})") + try: + bool_opts = [translate_longopt(o) for o in command_obj.boolean_options] + except AttributeError: + bool_opts = [] + try: + neg_opt = command_obj.negative_opt + except AttributeError: + neg_opt = {} + + try: + is_string = isinstance(value, str) + if option in neg_opt and is_string: + setattr(command_obj, neg_opt[option], not strtobool(value)) + elif option in bool_opts and is_string: + setattr(command_obj, option, strtobool(value)) + elif hasattr(command_obj, option): + setattr(command_obj, option, value) + else: + raise DistutilsOptionError( + f"error in {source}: command '{command_name}' has no such option '{option}'" + ) + except ValueError as e: + raise DistutilsOptionError(e) from e + + def _get_project_config_files(self, filenames: Iterable[StrPath] | None): + """Add default file and split between INI and TOML""" + tomlfiles = [] + standard_project_metadata = Path(self.src_root or os.curdir, "pyproject.toml") + if filenames is not None: + parts = partition(lambda f: Path(f).suffix == ".toml", filenames) + filenames = list(parts[0]) # 1st element => predicate is False + tomlfiles = list(parts[1]) # 2nd element => predicate is True + elif standard_project_metadata.exists(): + tomlfiles = [standard_project_metadata] + return filenames, tomlfiles + + def parse_config_files( + self, + filenames: Iterable[StrPath] | None = None, + ignore_option_errors: bool = False, + ) -> None: + """Parses configuration files from various levels + and loads configuration. + """ + inifiles, tomlfiles = self._get_project_config_files(filenames) + + self._parse_config_files(filenames=inifiles) + + setupcfg.parse_configuration( + self, self.command_options, ignore_option_errors=ignore_option_errors + ) + for filename in tomlfiles: + pyprojecttoml.apply_configuration(self, filename, ignore_option_errors) + + self._finalize_requires() + self._finalize_license_expression() + self._finalize_license_files() + + def fetch_build_eggs( + self, requires: _StrOrIter + ) -> list[_pkg_resources_Distribution]: + """Resolve pre-setup requirements""" + from .installer import _fetch_build_eggs + + return _fetch_build_eggs(self, requires) + + def finalize_options(self) -> None: + """ + Allow plugins to apply arbitrary operations to the + distribution. Each hook may optionally define a 'order' + to influence the order of execution. Smaller numbers + go first and the default is 0. + """ + group = 'setuptools.finalize_distribution_options' + + def by_order(hook): + return getattr(hook, 'order', 0) + + defined = metadata.entry_points(group=group) + filtered = itertools.filterfalse(self._removed, defined) + loaded = map(lambda e: e.load(), filtered) + for ep in sorted(loaded, key=by_order): + ep(self) + + @staticmethod + def _removed(ep): + """ + When removing an entry point, if metadata is loaded + from an older version of Setuptools, that removed + entry point will attempt to be loaded and will fail. + See #2765 for more details. + """ + removed = { + # removed 2021-09-05 + '2to3_doctests', + } + return ep.name in removed + + def _finalize_setup_keywords(self): + for ep in metadata.entry_points(group='distutils.setup_keywords'): + value = getattr(self, ep.name, None) + if value is not None: + ep.load()(self, ep.name, value) + + def get_egg_cache_dir(self): + from . import windows_support + + egg_cache_dir = os.path.join(os.curdir, '.eggs') + if not os.path.exists(egg_cache_dir): + os.mkdir(egg_cache_dir) + windows_support.hide_file(egg_cache_dir) + readme_txt_filename = os.path.join(egg_cache_dir, 'README.txt') + with open(readme_txt_filename, 'w', encoding="utf-8") as f: + f.write( + 'This directory contains eggs that were downloaded ' + 'by setuptools to build, test, and run plug-ins.\n\n' + ) + f.write( + 'This directory caches those eggs to prevent ' + 'repeated downloads.\n\n' + ) + f.write('However, it is safe to delete this directory.\n\n') + + return egg_cache_dir + + def fetch_build_egg(self, req): + """Fetch an egg needed for building""" + from .installer import fetch_build_egg + + return fetch_build_egg(self, req) + + def get_command_class(self, command: str) -> type[distutils.cmd.Command]: # type: ignore[override] # Not doing complex overrides yet + """Pluggable version of get_command_class()""" + if command in self.cmdclass: + return self.cmdclass[command] + + # Special case bdist_wheel so it's never loaded from "wheel" + if command == 'bdist_wheel': + from .command.bdist_wheel import bdist_wheel + + return bdist_wheel + + eps = metadata.entry_points(group='distutils.commands', name=command) + for ep in eps: + self.cmdclass[command] = cmdclass = ep.load() + return cmdclass + else: + return _Distribution.get_command_class(self, command) + + def print_commands(self): + for ep in metadata.entry_points(group='distutils.commands'): + if ep.name not in self.cmdclass: + cmdclass = ep.load() + self.cmdclass[ep.name] = cmdclass + return _Distribution.print_commands(self) + + def get_command_list(self): + for ep in metadata.entry_points(group='distutils.commands'): + if ep.name not in self.cmdclass: + cmdclass = ep.load() + self.cmdclass[ep.name] = cmdclass + return _Distribution.get_command_list(self) + + def include(self, **attrs) -> None: + """Add items to distribution that are named in keyword arguments + + For example, 'dist.include(py_modules=["x"])' would add 'x' to + the distribution's 'py_modules' attribute, if it was not already + there. + + Currently, this method only supports inclusion for attributes that are + lists or tuples. If you need to add support for adding to other + attributes in this or a subclass, you can add an '_include_X' method, + where 'X' is the name of the attribute. The method will be called with + the value passed to 'include()'. So, 'dist.include(foo={"bar":"baz"})' + will try to call 'dist._include_foo({"bar":"baz"})', which can then + handle whatever special inclusion logic is needed. + """ + for k, v in attrs.items(): + include = getattr(self, '_include_' + k, None) + if include: + include(v) + else: + self._include_misc(k, v) + + def exclude_package(self, package: str) -> None: + """Remove packages, modules, and extensions in named package""" + + pfx = package + '.' + if self.packages: + self.packages = [ + p for p in self.packages if p != package and not p.startswith(pfx) + ] + + if self.py_modules: + self.py_modules = [ + p for p in self.py_modules if p != package and not p.startswith(pfx) + ] + + if self.ext_modules: + self.ext_modules = [ + p + for p in self.ext_modules + if p.name != package and not p.name.startswith(pfx) + ] + + def has_contents_for(self, package: str) -> bool: + """Return true if 'exclude_package(package)' would do something""" + + pfx = package + '.' + + for p in self.iter_distribution_names(): + if p == package or p.startswith(pfx): + return True + + return False + + def _exclude_misc(self, name: str, value: _Sequence) -> None: + """Handle 'exclude()' for list/tuple attrs without a special handler""" + if not isinstance(value, _sequence): + raise DistutilsSetupError( + f"{name}: setting must be of type <{_sequence_type_repr}> (got {value!r})" + ) + try: + old = getattr(self, name) + except AttributeError as e: + raise DistutilsSetupError(f"{name}: No such distribution setting") from e + if old is not None and not isinstance(old, _sequence): + raise DistutilsSetupError( + name + ": this setting cannot be changed via include/exclude" + ) + elif old: + setattr(self, name, [item for item in old if item not in value]) + + def _include_misc(self, name: str, value: _Sequence) -> None: + """Handle 'include()' for list/tuple attrs without a special handler""" + + if not isinstance(value, _sequence): + raise DistutilsSetupError( + f"{name}: setting must be of type <{_sequence_type_repr}> (got {value!r})" + ) + try: + old = getattr(self, name) + except AttributeError as e: + raise DistutilsSetupError(f"{name}: No such distribution setting") from e + if old is None: + setattr(self, name, value) + elif not isinstance(old, _sequence): + raise DistutilsSetupError( + name + ": this setting cannot be changed via include/exclude" + ) + else: + new = [item for item in value if item not in old] + setattr(self, name, list(old) + new) + + def exclude(self, **attrs) -> None: + """Remove items from distribution that are named in keyword arguments + + For example, 'dist.exclude(py_modules=["x"])' would remove 'x' from + the distribution's 'py_modules' attribute. Excluding packages uses + the 'exclude_package()' method, so all of the package's contained + packages, modules, and extensions are also excluded. + + Currently, this method only supports exclusion from attributes that are + lists or tuples. If you need to add support for excluding from other + attributes in this or a subclass, you can add an '_exclude_X' method, + where 'X' is the name of the attribute. The method will be called with + the value passed to 'exclude()'. So, 'dist.exclude(foo={"bar":"baz"})' + will try to call 'dist._exclude_foo({"bar":"baz"})', which can then + handle whatever special exclusion logic is needed. + """ + for k, v in attrs.items(): + exclude = getattr(self, '_exclude_' + k, None) + if exclude: + exclude(v) + else: + self._exclude_misc(k, v) + + def _exclude_packages(self, packages: _Sequence) -> None: + if not isinstance(packages, _sequence): + raise DistutilsSetupError( + f"packages: setting must be of type <{_sequence_type_repr}> (got {packages!r})" + ) + list(map(self.exclude_package, packages)) + + def _parse_command_opts(self, parser, args): + # Remove --with-X/--without-X options when processing command args + self.global_options = self.__class__.global_options + self.negative_opt = self.__class__.negative_opt + + # First, expand any aliases + command = args[0] + aliases = self.get_option_dict('aliases') + while command in aliases: + _src, alias = aliases[command] + del aliases[command] # ensure each alias can expand only once! + import shlex + + args[:1] = shlex.split(alias, True) + command = args[0] + + nargs = _Distribution._parse_command_opts(self, parser, args) + + # Handle commands that want to consume all remaining arguments + cmd_class = self.get_command_class(command) + if getattr(cmd_class, 'command_consumes_arguments', None): + self.get_option_dict(command)['args'] = ("command line", nargs) + if nargs is not None: + return [] + + return nargs + + def get_cmdline_options(self) -> dict[str, dict[str, str | None]]: + """Return a '{cmd: {opt:val}}' map of all command-line options + + Option names are all long, but do not include the leading '--', and + contain dashes rather than underscores. If the option doesn't take + an argument (e.g. '--quiet'), the 'val' is 'None'. + + Note that options provided by config files are intentionally excluded. + """ + + d: dict[str, dict[str, str | None]] = {} + + for cmd, opts in self.command_options.items(): + val: str | None + for opt, (src, val) in opts.items(): + if src != "command line": + continue + + opt = opt.replace('_', '-') + + if val == 0: + cmdobj = self.get_command_obj(cmd) + neg_opt = self.negative_opt.copy() + neg_opt.update(getattr(cmdobj, 'negative_opt', {})) + for neg, pos in neg_opt.items(): + if pos == opt: + opt = neg + val = None + break + else: + raise AssertionError("Shouldn't be able to get here") + + elif val == 1: + val = None + + d.setdefault(cmd, {})[opt] = val + + return d + + def iter_distribution_names(self): + """Yield all packages, modules, and extension names in distribution""" + + yield from self.packages or () + + yield from self.py_modules or () + + for ext in self.ext_modules or (): + if isinstance(ext, tuple): + name, _buildinfo = ext + else: + name = ext.name + if name.endswith('module'): + name = name[:-6] + yield name + + def handle_display_options(self, option_order): + """If there were any non-global "display-only" options + (--help-commands or the metadata display options) on the command + line, display the requested info and return true; else return + false. + """ + import sys + + if self.help_commands: + return _Distribution.handle_display_options(self, option_order) + + # Stdout may be StringIO (e.g. in tests) + if not isinstance(sys.stdout, io.TextIOWrapper): + return _Distribution.handle_display_options(self, option_order) + + # Don't wrap stdout if utf-8 is already the encoding. Provides + # workaround for #334. + if sys.stdout.encoding.lower() in ('utf-8', 'utf8'): + return _Distribution.handle_display_options(self, option_order) + + # Print metadata in UTF-8 no matter the platform + encoding = sys.stdout.encoding + sys.stdout.reconfigure(encoding='utf-8') + try: + return _Distribution.handle_display_options(self, option_order) + finally: + sys.stdout.reconfigure(encoding=encoding) + + def run_command(self, command) -> None: + self.set_defaults() + # Postpone defaults until all explicit configuration is considered + # (setup() args, config files, command line and plugins) + + super().run_command(command) + + +@functools.cache +def _setuptools_commands() -> set[str]: + try: + # Use older API for importlib.metadata compatibility + entry_points = metadata.distribution('setuptools').entry_points + eps: Iterable[str] = (ep.name for ep in entry_points) + except metadata.PackageNotFoundError: + # during bootstrapping, distribution doesn't exist + eps = [] + return {*distutils.command.__all__, *eps} + + +class DistDeprecationWarning(SetuptoolsDeprecationWarning): + """Class for warning about deprecations in dist in + setuptools. Not ignored by default, unlike DeprecationWarning.""" diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/errors.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..990ecbf4e2f18eb188addc9e0466152a20193a90 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/errors.py @@ -0,0 +1,67 @@ +"""setuptools.errors + +Provides exceptions used by setuptools modules. +""" + +from __future__ import annotations + +from distutils import errors as _distutils_errors + +# Re-export errors from distutils to facilitate the migration to PEP632 + +ByteCompileError = _distutils_errors.DistutilsByteCompileError +CCompilerError = _distutils_errors.CCompilerError +ClassError = _distutils_errors.DistutilsClassError +CompileError = _distutils_errors.CompileError +ExecError = _distutils_errors.DistutilsExecError +FileError = _distutils_errors.DistutilsFileError +InternalError = _distutils_errors.DistutilsInternalError +LibError = _distutils_errors.LibError +LinkError = _distutils_errors.LinkError +ModuleError = _distutils_errors.DistutilsModuleError +OptionError = _distutils_errors.DistutilsOptionError +PlatformError = _distutils_errors.DistutilsPlatformError +PreprocessError = _distutils_errors.PreprocessError +SetupError = _distutils_errors.DistutilsSetupError +TemplateError = _distutils_errors.DistutilsTemplateError +UnknownFileError = _distutils_errors.UnknownFileError + +# The root error class in the hierarchy +BaseError = _distutils_errors.DistutilsError + + +class InvalidConfigError(OptionError): # type: ignore[valid-type, misc] # distutils imports are `Any` on python 3.12+ + """Error used for invalid configurations.""" + + +class RemovedConfigError(OptionError): # type: ignore[valid-type, misc] # distutils imports are `Any` on python 3.12+ + """Error used for configurations that were deprecated and removed.""" + + +class RemovedCommandError(BaseError, RuntimeError): # type: ignore[valid-type, misc] # distutils imports are `Any` on python 3.12+ + """Error used for commands that have been removed in setuptools. + + Since ``setuptools`` is built on ``distutils``, simply removing a command + from ``setuptools`` will make the behavior fall back to ``distutils``; this + error is raised if a command exists in ``distutils`` but has been actively + removed in ``setuptools``. + """ + + +class PackageDiscoveryError(BaseError, RuntimeError): # type: ignore[valid-type, misc] # distutils imports are `Any` on python 3.12+ + """Impossible to perform automatic discovery of packages and/or modules. + + The current project layout or given discovery options can lead to problems when + scanning the project directory. + + Setuptools might also refuse to complete auto-discovery if an error prone condition + is detected (e.g. when a project is organised as a flat-layout but contains + multiple directories that can be taken as top-level packages inside a single + distribution [*]_). In these situations the users are encouraged to be explicit + about which packages to include or to make the discovery parameters more specific. + + .. [*] Since multi-package distributions are uncommon it is very likely that the + developers did not intend for all the directories to be packaged, and are just + leaving auxiliary code in the repository top-level, such as maintenance-related + scripts. + """ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/extension.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/extension.py new file mode 100644 index 0000000000000000000000000000000000000000..76e03d9d6bdcdbd72e443e90c85d34429c22c261 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/extension.py @@ -0,0 +1,177 @@ +from __future__ import annotations + +import functools +import re +from typing import TYPE_CHECKING + +from setuptools._path import StrPath + +from .monkey import get_unpatched + +import distutils.core +import distutils.errors +import distutils.extension + + +def _have_cython(): + """ + Return True if Cython can be imported. + """ + cython_impl = 'Cython.Distutils.build_ext' + try: + # from (cython_impl) import build_ext + __import__(cython_impl, fromlist=['build_ext']).build_ext + except Exception: + return False + return True + + +# for compatibility +have_pyrex = _have_cython +if TYPE_CHECKING: + # Work around a mypy issue where type[T] can't be used as a base: https://github.com/python/mypy/issues/10962 + from distutils.core import Extension as _Extension +else: + _Extension = get_unpatched(distutils.core.Extension) + + +class Extension(_Extension): + """ + Describes a single extension module. + + This means that all source files will be compiled into a single binary file + ``.`` (with ```` derived from ``name`` and + ```` defined by one of the values in + ``importlib.machinery.EXTENSION_SUFFIXES``). + + In the case ``.pyx`` files are passed as ``sources and`` ``Cython`` is **not** + installed in the build environment, ``setuptools`` may also try to look for the + equivalent ``.cpp`` or ``.c`` files. + + :arg str name: + the full name of the extension, including any packages -- ie. + *not* a filename or pathname, but Python dotted name + + :arg list[str|os.PathLike[str]] sources: + list of source filenames, relative to the distribution root + (where the setup script lives), in Unix form (slash-separated) + for portability. Source files may be C, C++, SWIG (.i), + platform-specific resource files, or whatever else is recognized + by the "build_ext" command as source for a Python extension. + + :keyword list[str] include_dirs: + list of directories to search for C/C++ header files (in Unix + form for portability) + + :keyword list[tuple[str, str|None]] define_macros: + list of macros to define; each macro is defined using a 2-tuple: + the first item corresponding to the name of the macro and the second + item either a string with its value or None to + define it without a particular value (equivalent of "#define + FOO" in source or -DFOO on Unix C compiler command line) + + :keyword list[str] undef_macros: + list of macros to undefine explicitly + + :keyword list[str] library_dirs: + list of directories to search for C/C++ libraries at link time + + :keyword list[str] libraries: + list of library names (not filenames or paths) to link against + + :keyword list[str] runtime_library_dirs: + list of directories to search for C/C++ libraries at run time + (for shared extensions, this is when the extension is loaded). + Setting this will cause an exception during build on Windows + platforms. + + :keyword list[str] extra_objects: + list of extra files to link with (eg. object files not implied + by 'sources', static library that must be explicitly specified, + binary resource files, etc.) + + :keyword list[str] extra_compile_args: + any extra platform- and compiler-specific information to use + when compiling the source files in 'sources'. For platforms and + compilers where "command line" makes sense, this is typically a + list of command-line arguments, but for other platforms it could + be anything. + + :keyword list[str] extra_link_args: + any extra platform- and compiler-specific information to use + when linking object files together to create the extension (or + to create a new static Python interpreter). Similar + interpretation as for 'extra_compile_args'. + + :keyword list[str] export_symbols: + list of symbols to be exported from a shared extension. Not + used on all platforms, and not generally necessary for Python + extensions, which typically export exactly one symbol: "init" + + extension_name. + + :keyword list[str] swig_opts: + any extra options to pass to SWIG if a source file has the .i + extension. + + :keyword list[str] depends: + list of files that the extension depends on + + :keyword str language: + extension language (i.e. "c", "c++", "objc"). Will be detected + from the source extensions if not provided. + + :keyword bool optional: + specifies that a build failure in the extension should not abort the + build process, but simply not install the failing extension. + + :keyword bool py_limited_api: + opt-in flag for the usage of :doc:`Python's limited API `. + + :raises setuptools.errors.PlatformError: if ``runtime_library_dirs`` is + specified on Windows. (since v63) + """ + + # These 4 are set and used in setuptools/command/build_ext.py + # The lack of a default value and risk of `AttributeError` is purposeful + # to avoid people forgetting to call finalize_options if they modify the extension list. + # See example/rationale in https://github.com/pypa/setuptools/issues/4529. + _full_name: str #: Private API, internal use only. + _links_to_dynamic: bool #: Private API, internal use only. + _needs_stub: bool #: Private API, internal use only. + _file_name: str #: Private API, internal use only. + + def __init__( + self, + name: str, + sources: list[StrPath], + *args, + py_limited_api: bool = False, + **kw, + ) -> None: + # The *args is needed for compatibility as calls may use positional + # arguments. py_limited_api may be set only via keyword. + self.py_limited_api = py_limited_api + super().__init__( + name, + sources, # type: ignore[arg-type] # Vendored version of setuptools supports PathLike + *args, + **kw, + ) + + def _convert_pyx_sources_to_lang(self): + """ + Replace sources with .pyx extensions to sources with the target + language extension. This mechanism allows language authors to supply + pre-converted sources but to prefer the .pyx sources. + """ + if _have_cython(): + # the build has Cython, so allow it to compile the .pyx files + return + lang = self.language or '' + target_ext = '.cpp' if lang.lower() == 'c++' else '.c' + sub = functools.partial(re.sub, '.pyx$', target_ext) + self.sources = list(map(sub, self.sources)) + + +class Library(Extension): + """Just like a regular Extension, but built as a library instead""" diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/glob.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/glob.py new file mode 100644 index 0000000000000000000000000000000000000000..1dfff2cd50ff87b8cef9d936f1fc9d4a2478b136 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/glob.py @@ -0,0 +1,185 @@ +""" +Filename globbing utility. Mostly a copy of `glob` from Python 3.5. + +Changes include: + * `yield from` and PEP3102 `*` removed. + * Hidden files are not ignored. +""" + +from __future__ import annotations + +import fnmatch +import os +import re +from collections.abc import Iterable, Iterator +from typing import TYPE_CHECKING, AnyStr, overload + +if TYPE_CHECKING: + from _typeshed import BytesPath, StrOrBytesPath, StrPath + +__all__ = ["glob", "iglob", "escape"] + + +def glob(pathname: AnyStr, recursive: bool = False) -> list[AnyStr]: + """Return a list of paths matching a pathname pattern. + + The pattern may contain simple shell-style wildcards a la + fnmatch. However, unlike fnmatch, filenames starting with a + dot are special cases that are not matched by '*' and '?' + patterns. + + If recursive is true, the pattern '**' will match any files and + zero or more directories and subdirectories. + """ + return list(iglob(pathname, recursive=recursive)) + + +def iglob(pathname: AnyStr, recursive: bool = False) -> Iterator[AnyStr]: + """Return an iterator which yields the paths matching a pathname pattern. + + The pattern may contain simple shell-style wildcards a la + fnmatch. However, unlike fnmatch, filenames starting with a + dot are special cases that are not matched by '*' and '?' + patterns. + + If recursive is true, the pattern '**' will match any files and + zero or more directories and subdirectories. + """ + it = _iglob(pathname, recursive) + if recursive and _isrecursive(pathname): + s = next(it) # skip empty string + assert not s + return it + + +def _iglob(pathname: AnyStr, recursive: bool) -> Iterator[AnyStr]: + dirname, basename = os.path.split(pathname) + glob_in_dir = glob2 if recursive and _isrecursive(basename) else glob1 + + if not has_magic(pathname): + if basename: + if os.path.lexists(pathname): + yield pathname + else: + # Patterns ending with a slash should match only directories + if os.path.isdir(dirname): + yield pathname + return + + if not dirname: + yield from glob_in_dir(dirname, basename) + return + # `os.path.split()` returns the argument itself as a dirname if it is a + # drive or UNC path. Prevent an infinite recursion if a drive or UNC path + # contains magic characters (i.e. r'\\?\C:'). + if dirname != pathname and has_magic(dirname): + dirs: Iterable[AnyStr] = _iglob(dirname, recursive) + else: + dirs = [dirname] + if not has_magic(basename): + glob_in_dir = glob0 + for dirname in dirs: + for name in glob_in_dir(dirname, basename): + yield os.path.join(dirname, name) + + +# These 2 helper functions non-recursively glob inside a literal directory. +# They return a list of basenames. `glob1` accepts a pattern while `glob0` +# takes a literal basename (so it only has to check for its existence). + + +@overload +def glob1(dirname: StrPath, pattern: str) -> list[str]: ... +@overload +def glob1(dirname: BytesPath, pattern: bytes) -> list[bytes]: ... +def glob1(dirname: StrOrBytesPath, pattern: str | bytes) -> list[str] | list[bytes]: + if not dirname: + if isinstance(pattern, bytes): + dirname = os.curdir.encode('ASCII') + else: + dirname = os.curdir + try: + names = os.listdir(dirname) + except OSError: + return [] + # mypy false-positives: str or bytes type possibility is always kept in sync + return fnmatch.filter(names, pattern) # type: ignore[type-var, return-value] + + +def glob0(dirname, basename): + if not basename: + # `os.path.split()` returns an empty basename for paths ending with a + # directory separator. 'q*x/' should match only directories. + if os.path.isdir(dirname): + return [basename] + else: + if os.path.lexists(os.path.join(dirname, basename)): + return [basename] + return [] + + +# This helper function recursively yields relative pathnames inside a literal +# directory. + + +@overload +def glob2(dirname: StrPath, pattern: str) -> Iterator[str]: ... +@overload +def glob2(dirname: BytesPath, pattern: bytes) -> Iterator[bytes]: ... +def glob2(dirname: StrOrBytesPath, pattern: str | bytes) -> Iterator[str | bytes]: + assert _isrecursive(pattern) + yield pattern[:0] + yield from _rlistdir(dirname) + + +# Recursively yields relative pathnames inside a literal directory. +@overload +def _rlistdir(dirname: StrPath) -> Iterator[str]: ... +@overload +def _rlistdir(dirname: BytesPath) -> Iterator[bytes]: ... +def _rlistdir(dirname: StrOrBytesPath) -> Iterator[str | bytes]: + if not dirname: + if isinstance(dirname, bytes): + dirname = os.curdir.encode('ASCII') + else: + dirname = os.curdir + try: + names = os.listdir(dirname) + except OSError: + return + for x in names: + yield x + # mypy false-positives: str or bytes type possibility is always kept in sync + path = os.path.join(dirname, x) if dirname else x # type: ignore[arg-type] + for y in _rlistdir(path): + yield os.path.join(x, y) # type: ignore[arg-type] + + +magic_check = re.compile('([*?[])') +magic_check_bytes = re.compile(b'([*?[])') + + +def has_magic(s: str | bytes) -> bool: + if isinstance(s, bytes): + return magic_check_bytes.search(s) is not None + else: + return magic_check.search(s) is not None + + +def _isrecursive(pattern: str | bytes) -> bool: + if isinstance(pattern, bytes): + return pattern == b'**' + else: + return pattern == '**' + + +def escape(pathname): + """Escape all special characters.""" + # Escaping is done by wrapping any of "*?[" between square brackets. + # Metacharacters do not work in the drive part and shouldn't be escaped. + drive, pathname = os.path.splitdrive(pathname) + if isinstance(pathname, bytes): + pathname = magic_check_bytes.sub(rb'[\1]', pathname) + else: + pathname = magic_check.sub(r'[\1]', pathname) + return drive + pathname diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/gui-32.exe b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/gui-32.exe new file mode 100644 index 0000000000000000000000000000000000000000..1eb430c6d614a5daea4139badc09c222a4b0e72a Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/gui-32.exe differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/gui-64.exe b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/gui-64.exe new file mode 100644 index 0000000000000000000000000000000000000000..031cb77c17ba8d8a983448268851d612e05e80d1 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/gui-64.exe differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/gui-arm64.exe b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/gui-arm64.exe new file mode 100644 index 0000000000000000000000000000000000000000..1e00ffacb182c2af206e5dd9d9fbc41d236da0d1 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/gui-arm64.exe differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/gui.exe b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/gui.exe new file mode 100644 index 0000000000000000000000000000000000000000..1eb430c6d614a5daea4139badc09c222a4b0e72a Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/gui.exe differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/installer.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/installer.py new file mode 100644 index 0000000000000000000000000000000000000000..64bc2def078bab5e4fb6aba26981e7b73bfc37a5 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/installer.py @@ -0,0 +1,150 @@ +from __future__ import annotations + +import glob +import os +import subprocess +import sys +import tempfile +from functools import partial + +from pkg_resources import Distribution + +from . import _reqs +from ._reqs import _StrOrIter +from .warnings import SetuptoolsDeprecationWarning +from .wheel import Wheel + +from distutils import log +from distutils.errors import DistutilsError + + +def _fixup_find_links(find_links): + """Ensure find-links option end-up being a list of strings.""" + if isinstance(find_links, str): + return find_links.split() + assert isinstance(find_links, (tuple, list)) + return find_links + + +def fetch_build_egg(dist, req): + """Fetch an egg needed for building. + + Use pip/wheel to fetch/build a wheel.""" + _DeprecatedInstaller.emit() + _warn_wheel_not_available(dist) + return _fetch_build_egg_no_warn(dist, req) + + +def _fetch_build_eggs(dist, requires: _StrOrIter) -> list[Distribution]: + import pkg_resources # Delay import to avoid unnecessary side-effects + + _DeprecatedInstaller.emit(stacklevel=3) + _warn_wheel_not_available(dist) + + resolved_dists = pkg_resources.working_set.resolve( + _reqs.parse(requires, pkg_resources.Requirement), # required for compatibility + installer=partial(_fetch_build_egg_no_warn, dist), # avoid warning twice + replace_conflicting=True, + ) + for dist in resolved_dists: + pkg_resources.working_set.add(dist, replace=True) + return resolved_dists + + +def _fetch_build_egg_no_warn(dist, req): # noqa: C901 # is too complex (16) # FIXME + import pkg_resources # Delay import to avoid unnecessary side-effects + + # Ignore environment markers; if supplied, it is required. + req = strip_marker(req) + # Take easy_install options into account, but do not override relevant + # pip environment variables (like PIP_INDEX_URL or PIP_QUIET); they'll + # take precedence. + opts = dist.get_option_dict('easy_install') + if 'allow_hosts' in opts: + raise DistutilsError( + 'the `allow-hosts` option is not supported ' + 'when using pip to install requirements.' + ) + quiet = 'PIP_QUIET' not in os.environ and 'PIP_VERBOSE' not in os.environ + if 'PIP_INDEX_URL' in os.environ: + index_url = None + elif 'index_url' in opts: + index_url = opts['index_url'][1] + else: + index_url = None + find_links = ( + _fixup_find_links(opts['find_links'][1])[:] if 'find_links' in opts else [] + ) + if dist.dependency_links: + find_links.extend(dist.dependency_links) + eggs_dir = os.path.realpath(dist.get_egg_cache_dir()) + environment = pkg_resources.Environment() + for egg_dist in pkg_resources.find_distributions(eggs_dir): + if egg_dist in req and environment.can_add(egg_dist): + return egg_dist + with tempfile.TemporaryDirectory() as tmpdir: + cmd = [ + sys.executable, + '-m', + 'pip', + '--disable-pip-version-check', + 'wheel', + '--no-deps', + '-w', + tmpdir, + ] + if quiet: + cmd.append('--quiet') + if index_url is not None: + cmd.extend(('--index-url', index_url)) + for link in find_links or []: + cmd.extend(('--find-links', link)) + # If requirement is a PEP 508 direct URL, directly pass + # the URL to pip, as `req @ url` does not work on the + # command line. + cmd.append(req.url or str(req)) + try: + subprocess.check_call(cmd) + except subprocess.CalledProcessError as e: + raise DistutilsError(str(e)) from e + wheel = Wheel(glob.glob(os.path.join(tmpdir, '*.whl'))[0]) + dist_location = os.path.join(eggs_dir, wheel.egg_name()) + wheel.install_as_egg(dist_location) + dist_metadata = pkg_resources.PathMetadata( + dist_location, os.path.join(dist_location, 'EGG-INFO') + ) + return pkg_resources.Distribution.from_filename( + dist_location, metadata=dist_metadata + ) + + +def strip_marker(req): + """ + Return a new requirement without the environment marker to avoid + calling pip with something like `babel; extra == "i18n"`, which + would always be ignored. + """ + import pkg_resources # Delay import to avoid unnecessary side-effects + + # create a copy to avoid mutating the input + req = pkg_resources.Requirement.parse(str(req)) + req.marker = None + return req + + +def _warn_wheel_not_available(dist): + import pkg_resources # Delay import to avoid unnecessary side-effects + + try: + pkg_resources.get_distribution('wheel') + except pkg_resources.DistributionNotFound: + dist.announce('WARNING: The wheel package is not available.', log.WARN) + + +class _DeprecatedInstaller(SetuptoolsDeprecationWarning): + _SUMMARY = "setuptools.installer and fetch_build_eggs are deprecated." + _DETAILS = """ + Requirements should be satisfied by a PEP 517 installer. + If you are using pip, you can try `pip install --use-pep517`. + """ + # _DUE_DATE not decided yet diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/launch.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/launch.py new file mode 100644 index 0000000000000000000000000000000000000000..0d162647d55777d7afa1bf1e44a6c200a3f82419 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/launch.py @@ -0,0 +1,36 @@ +""" +Launch the Python script on the command line after +setuptools is bootstrapped via import. +""" + +# Note that setuptools gets imported implicitly by the +# invocation of this script using python -m setuptools.launch + +import sys +import tokenize + + +def run() -> None: + """ + Run the script in sys.argv[1] as if it had + been invoked naturally. + """ + __builtins__ + script_name = sys.argv[1] + namespace = dict( + __file__=script_name, + __name__='__main__', + __doc__=None, + ) + sys.argv[:] = sys.argv[1:] + + open_ = getattr(tokenize, 'open', open) + with open_(script_name) as fid: + script = fid.read() + norm_script = script.replace('\\r\\n', '\\n') + code = compile(norm_script, script_name, 'exec') + exec(code, namespace) + + +if __name__ == '__main__': + run() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/logging.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/logging.py new file mode 100644 index 0000000000000000000000000000000000000000..532da899f7dc02f9fea9a44c429086b98fe043d8 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/logging.py @@ -0,0 +1,40 @@ +import inspect +import logging +import sys + +from . import monkey + +import distutils.log + + +def _not_warning(record): + return record.levelno < logging.WARNING + + +def configure() -> None: + """ + Configure logging to emit warning and above to stderr + and everything else to stdout. This behavior is provided + for compatibility with distutils.log but may change in + the future. + """ + err_handler = logging.StreamHandler() + err_handler.setLevel(logging.WARNING) + out_handler = logging.StreamHandler(sys.stdout) + out_handler.addFilter(_not_warning) + handlers = err_handler, out_handler + logging.basicConfig( + format="{message}", style='{', handlers=handlers, level=logging.DEBUG + ) + if inspect.ismodule(distutils.dist.log): + monkey.patch_func(set_threshold, distutils.log, 'set_threshold') + # For some reason `distutils.log` module is getting cached in `distutils.dist` + # and then loaded again when patched, + # implying: id(distutils.log) != id(distutils.dist.log). + # Make sure the same module object is used everywhere: + distutils.dist.log = distutils.log + + +def set_threshold(level: int) -> int: + logging.root.setLevel(level * 10) + return set_threshold.unpatched(level) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/modified.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/modified.py new file mode 100644 index 0000000000000000000000000000000000000000..6ba02fab68734e1e96fd50d7c4b6ffb1442717fb --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/modified.py @@ -0,0 +1,18 @@ +try: + # Ensure a DistutilsError raised by these methods is the same as distutils.errors.DistutilsError + from distutils._modified import ( + newer, + newer_group, + newer_pairwise, + newer_pairwise_group, + ) +except ImportError: + # fallback for SETUPTOOLS_USE_DISTUTILS=stdlib, because _modified never existed in stdlib + from ._distutils._modified import ( + newer, + newer_group, + newer_pairwise, + newer_pairwise_group, + ) + +__all__ = ['newer', 'newer_pairwise', 'newer_group', 'newer_pairwise_group'] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/monkey.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/monkey.py new file mode 100644 index 0000000000000000000000000000000000000000..6ad1abac295c1df613942b8896edf089a103ae1f --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/monkey.py @@ -0,0 +1,126 @@ +""" +Monkey patching of distutils. +""" + +from __future__ import annotations + +import inspect +import platform +import sys +import types +from typing import TypeVar, cast, overload + +import distutils.filelist + +_T = TypeVar("_T") +_UnpatchT = TypeVar("_UnpatchT", type, types.FunctionType) + + +__all__: list[str] = [] +""" +Everything is private. Contact the project team +if you think you need this functionality. +""" + + +def _get_mro(cls): + """ + Returns the bases classes for cls sorted by the MRO. + + Works around an issue on Jython where inspect.getmro will not return all + base classes if multiple classes share the same name. Instead, this + function will return a tuple containing the class itself, and the contents + of cls.__bases__. See https://github.com/pypa/setuptools/issues/1024. + """ + if platform.python_implementation() == "Jython": + return (cls,) + cls.__bases__ + return inspect.getmro(cls) + + +@overload +def get_unpatched(item: _UnpatchT) -> _UnpatchT: ... +@overload +def get_unpatched(item: object) -> None: ... +def get_unpatched( + item: type | types.FunctionType | object, +) -> type | types.FunctionType | None: + if isinstance(item, type): + return get_unpatched_class(item) + if isinstance(item, types.FunctionType): + return get_unpatched_function(item) + return None + + +def get_unpatched_class(cls: type[_T]) -> type[_T]: + """Protect against re-patching the distutils if reloaded + + Also ensures that no other distutils extension monkeypatched the distutils + first. + """ + external_bases = ( + cast(type[_T], cls) + for cls in _get_mro(cls) + if not cls.__module__.startswith('setuptools') + ) + base = next(external_bases) + if not base.__module__.startswith('distutils'): + msg = f"distutils has already been patched by {cls!r}" + raise AssertionError(msg) + return base + + +def patch_all(): + import setuptools + + # we can't patch distutils.cmd, alas + distutils.core.Command = setuptools.Command # type: ignore[misc,assignment] # monkeypatching + + _patch_distribution_metadata() + + # Install Distribution throughout the distutils + for module in distutils.dist, distutils.core, distutils.cmd: + module.Distribution = setuptools.dist.Distribution + + # Install the patched Extension + distutils.core.Extension = setuptools.extension.Extension # type: ignore[misc,assignment] # monkeypatching + distutils.extension.Extension = setuptools.extension.Extension # type: ignore[misc,assignment] # monkeypatching + if 'distutils.command.build_ext' in sys.modules: + sys.modules[ + 'distutils.command.build_ext' + ].Extension = setuptools.extension.Extension + + +def _patch_distribution_metadata(): + from . import _core_metadata + + """Patch write_pkg_file and read_pkg_file for higher metadata standards""" + for attr in ( + 'write_pkg_info', + 'write_pkg_file', + 'read_pkg_file', + 'get_metadata_version', + 'get_fullname', + ): + new_val = getattr(_core_metadata, attr) + setattr(distutils.dist.DistributionMetadata, attr, new_val) + + +def patch_func(replacement, target_mod, func_name): + """ + Patch func_name in target_mod with replacement + + Important - original must be resolved by name to avoid + patching an already patched function. + """ + original = getattr(target_mod, func_name) + + # set the 'unpatched' attribute on the replacement to + # point to the original. + vars(replacement).setdefault('unpatched', original) + + # replace the function in the original module + setattr(target_mod, func_name, replacement) + + +def get_unpatched_function(candidate): + return candidate.unpatched diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/msvc.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/msvc.py new file mode 100644 index 0000000000000000000000000000000000000000..313a781ae095bbb20874795e5b87396790f0b9c9 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/msvc.py @@ -0,0 +1,1536 @@ +""" +Environment info about Microsoft Compilers. + +>>> getfixture('windows_only') +>>> ei = EnvironmentInfo('amd64') +""" + +from __future__ import annotations + +import contextlib +import itertools +import json +import os +import os.path +import platform +from typing import TYPE_CHECKING, TypedDict + +from more_itertools import unique_everseen + +import distutils.errors + +if TYPE_CHECKING: + from typing_extensions import LiteralString, NotRequired + +# https://github.com/python/mypy/issues/8166 +if not TYPE_CHECKING and platform.system() == 'Windows': + import winreg + from os import environ +else: + # Mock winreg and environ so the module can be imported on this platform. + + class winreg: + HKEY_USERS = None + HKEY_CURRENT_USER = None + HKEY_LOCAL_MACHINE = None + HKEY_CLASSES_ROOT = None + + environ: dict[str, str] = dict() + + +class PlatformInfo: + """ + Current and Target Architectures information. + + Parameters + ---------- + arch: str + Target architecture. + """ + + current_cpu = environ.get('processor_architecture', '').lower() + + def __init__(self, arch) -> None: + self.arch = arch.lower().replace('x64', 'amd64') + + @property + def target_cpu(self): + """ + Return Target CPU architecture. + + Return + ------ + str + Target CPU + """ + return self.arch[self.arch.find('_') + 1 :] + + def target_is_x86(self): + """ + Return True if target CPU is x86 32 bits.. + + Return + ------ + bool + CPU is x86 32 bits + """ + return self.target_cpu == 'x86' + + def current_is_x86(self): + """ + Return True if current CPU is x86 32 bits.. + + Return + ------ + bool + CPU is x86 32 bits + """ + return self.current_cpu == 'x86' + + def current_dir(self, hidex86=False, x64=False) -> str: + """ + Current platform specific subfolder. + + Parameters + ---------- + hidex86: bool + return '' and not '\x86' if architecture is x86. + x64: bool + return '\x64' and not '\amd64' if architecture is amd64. + + Return + ------ + str + subfolder: '\target', or '' (see hidex86 parameter) + """ + return ( + '' + if (self.current_cpu == 'x86' and hidex86) + else r'\x64' + if (self.current_cpu == 'amd64' and x64) + else rf'\{self.current_cpu}' + ) + + def target_dir(self, hidex86=False, x64=False) -> str: + r""" + Target platform specific subfolder. + + Parameters + ---------- + hidex86: bool + return '' and not '\x86' if architecture is x86. + x64: bool + return '\x64' and not '\amd64' if architecture is amd64. + + Return + ------ + str + subfolder: '\current', or '' (see hidex86 parameter) + """ + return ( + '' + if (self.target_cpu == 'x86' and hidex86) + else r'\x64' + if (self.target_cpu == 'amd64' and x64) + else rf'\{self.target_cpu}' + ) + + def cross_dir(self, forcex86=False): + r""" + Cross platform specific subfolder. + + Parameters + ---------- + forcex86: bool + Use 'x86' as current architecture even if current architecture is + not x86. + + Return + ------ + str + subfolder: '' if target architecture is current architecture, + '\current_target' if not. + """ + current = 'x86' if forcex86 else self.current_cpu + return ( + '' + if self.target_cpu == current + else self.target_dir().replace('\\', f'\\{current}_') + ) + + +class RegistryInfo: + """ + Microsoft Visual Studio related registry information. + + Parameters + ---------- + platform_info: PlatformInfo + "PlatformInfo" instance. + """ + + HKEYS = ( + winreg.HKEY_USERS, + winreg.HKEY_CURRENT_USER, + winreg.HKEY_LOCAL_MACHINE, + winreg.HKEY_CLASSES_ROOT, + ) + + def __init__(self, platform_info) -> None: + self.pi = platform_info + + @property + def visualstudio(self) -> str: + """ + Microsoft Visual Studio root registry key. + + Return + ------ + str + Registry key + """ + return 'VisualStudio' + + @property + def sxs(self): + """ + Microsoft Visual Studio SxS registry key. + + Return + ------ + str + Registry key + """ + return os.path.join(self.visualstudio, 'SxS') + + @property + def vc(self): + """ + Microsoft Visual C++ VC7 registry key. + + Return + ------ + str + Registry key + """ + return os.path.join(self.sxs, 'VC7') + + @property + def vs(self): + """ + Microsoft Visual Studio VS7 registry key. + + Return + ------ + str + Registry key + """ + return os.path.join(self.sxs, 'VS7') + + @property + def vc_for_python(self) -> str: + """ + Microsoft Visual C++ for Python registry key. + + Return + ------ + str + Registry key + """ + return r'DevDiv\VCForPython' + + @property + def microsoft_sdk(self) -> str: + """ + Microsoft SDK registry key. + + Return + ------ + str + Registry key + """ + return 'Microsoft SDKs' + + @property + def windows_sdk(self): + """ + Microsoft Windows/Platform SDK registry key. + + Return + ------ + str + Registry key + """ + return os.path.join(self.microsoft_sdk, 'Windows') + + @property + def netfx_sdk(self): + """ + Microsoft .NET Framework SDK registry key. + + Return + ------ + str + Registry key + """ + return os.path.join(self.microsoft_sdk, 'NETFXSDK') + + @property + def windows_kits_roots(self) -> str: + """ + Microsoft Windows Kits Roots registry key. + + Return + ------ + str + Registry key + """ + return r'Windows Kits\Installed Roots' + + def microsoft(self, key, x86=False): + """ + Return key in Microsoft software registry. + + Parameters + ---------- + key: str + Registry key path where look. + x86: str + Force x86 software registry. + + Return + ------ + str + Registry key + """ + node64 = '' if self.pi.current_is_x86() or x86 else 'Wow6432Node' + return os.path.join('Software', node64, 'Microsoft', key) + + def lookup(self, key, name): + """ + Look for values in registry in Microsoft software registry. + + Parameters + ---------- + key: str + Registry key path where look. + name: str + Value name to find. + + Return + ------ + str + value + """ + key_read = winreg.KEY_READ + openkey = winreg.OpenKey + closekey = winreg.CloseKey + ms = self.microsoft + for hkey in self.HKEYS: + bkey = None + try: + bkey = openkey(hkey, ms(key), 0, key_read) + except OSError: + if not self.pi.current_is_x86(): + try: + bkey = openkey(hkey, ms(key, True), 0, key_read) + except OSError: + continue + else: + continue + try: + return winreg.QueryValueEx(bkey, name)[0] + except OSError: + pass + finally: + if bkey: + closekey(bkey) + return None + + +class SystemInfo: + """ + Microsoft Windows and Visual Studio related system information. + + Parameters + ---------- + registry_info: RegistryInfo + "RegistryInfo" instance. + vc_ver: float + Required Microsoft Visual C++ version. + """ + + # Variables and properties in this class use originals CamelCase variables + # names from Microsoft source files for more easy comparison. + WinDir = environ.get('WinDir', '') + ProgramFiles = environ.get('ProgramFiles', '') + ProgramFilesx86 = environ.get('ProgramFiles(x86)', ProgramFiles) + + def __init__(self, registry_info, vc_ver=None) -> None: + self.ri = registry_info + self.pi = self.ri.pi + + self.known_vs_paths = self.find_programdata_vs_vers() + + # Except for VS15+, VC version is aligned with VS version + self.vs_ver = self.vc_ver = vc_ver or self._find_latest_available_vs_ver() + + def _find_latest_available_vs_ver(self): + """ + Find the latest VC version + + Return + ------ + float + version + """ + reg_vc_vers = self.find_reg_vs_vers() + + if not (reg_vc_vers or self.known_vs_paths): + raise distutils.errors.DistutilsPlatformError( + 'No Microsoft Visual C++ version found' + ) + + vc_vers = set(reg_vc_vers) + vc_vers.update(self.known_vs_paths) + return sorted(vc_vers)[-1] + + def find_reg_vs_vers(self): + """ + Find Microsoft Visual Studio versions available in registry. + + Return + ------ + list of float + Versions + """ + ms = self.ri.microsoft + vckeys = (self.ri.vc, self.ri.vc_for_python, self.ri.vs) + vs_vers = [] + for hkey, key in itertools.product(self.ri.HKEYS, vckeys): + try: + bkey = winreg.OpenKey(hkey, ms(key), 0, winreg.KEY_READ) + except OSError: + continue + with bkey: + subkeys, values, _ = winreg.QueryInfoKey(bkey) + for i in range(values): + with contextlib.suppress(ValueError): + ver = float(winreg.EnumValue(bkey, i)[0]) + if ver not in vs_vers: + vs_vers.append(ver) + for i in range(subkeys): + with contextlib.suppress(ValueError): + ver = float(winreg.EnumKey(bkey, i)) + if ver not in vs_vers: + vs_vers.append(ver) + return sorted(vs_vers) + + def find_programdata_vs_vers(self) -> dict[float, str]: + r""" + Find Visual studio 2017+ versions from information in + "C:\ProgramData\Microsoft\VisualStudio\Packages\_Instances". + + Return + ------ + dict + float version as key, path as value. + """ + vs_versions: dict[float, str] = {} + instances_dir = r'C:\ProgramData\Microsoft\VisualStudio\Packages\_Instances' + + try: + hashed_names = os.listdir(instances_dir) + + except OSError: + # Directory not exists with all Visual Studio versions + return vs_versions + + for name in hashed_names: + try: + # Get VS installation path from "state.json" file + state_path = os.path.join(instances_dir, name, 'state.json') + with open(state_path, 'rt', encoding='utf-8') as state_file: + state = json.load(state_file) + vs_path = state['installationPath'] + + # Raises OSError if this VS installation does not contain VC + os.listdir(os.path.join(vs_path, r'VC\Tools\MSVC')) + + # Store version and path + vs_versions[self._as_float_version(state['installationVersion'])] = ( + vs_path + ) + + except (OSError, KeyError): + # Skip if "state.json" file is missing or bad format + continue + + return vs_versions + + @staticmethod + def _as_float_version(version): + """ + Return a string version as a simplified float version (major.minor) + + Parameters + ---------- + version: str + Version. + + Return + ------ + float + version + """ + return float('.'.join(version.split('.')[:2])) + + @property + def VSInstallDir(self): + """ + Microsoft Visual Studio directory. + + Return + ------ + str + path + """ + # Default path + default = os.path.join( + self.ProgramFilesx86, f'Microsoft Visual Studio {self.vs_ver:0.1f}' + ) + + # Try to get path from registry, if fail use default path + return self.ri.lookup(self.ri.vs, f'{self.vs_ver:0.1f}') or default + + @property + def VCInstallDir(self): + """ + Microsoft Visual C++ directory. + + Return + ------ + str + path + """ + path = self._guess_vc() or self._guess_vc_legacy() + + if not os.path.isdir(path): + msg = 'Microsoft Visual C++ directory not found' + raise distutils.errors.DistutilsPlatformError(msg) + + return path + + def _guess_vc(self): + """ + Locate Visual C++ for VS2017+. + + Return + ------ + str + path + """ + if self.vs_ver <= 14.0: + return '' + + try: + # First search in known VS paths + vs_dir = self.known_vs_paths[self.vs_ver] + except KeyError: + # Else, search with path from registry + vs_dir = self.VSInstallDir + + guess_vc = os.path.join(vs_dir, r'VC\Tools\MSVC') + + # Subdir with VC exact version as name + try: + # Update the VC version with real one instead of VS version + vc_ver = os.listdir(guess_vc)[-1] + self.vc_ver = self._as_float_version(vc_ver) + return os.path.join(guess_vc, vc_ver) + except (OSError, IndexError): + return '' + + def _guess_vc_legacy(self): + """ + Locate Visual C++ for versions prior to 2017. + + Return + ------ + str + path + """ + default = os.path.join( + self.ProgramFilesx86, + rf'Microsoft Visual Studio {self.vs_ver:0.1f}\VC', + ) + + # Try to get "VC++ for Python" path from registry as default path + reg_path = os.path.join(self.ri.vc_for_python, f'{self.vs_ver:0.1f}') + python_vc = self.ri.lookup(reg_path, 'installdir') + default_vc = os.path.join(python_vc, 'VC') if python_vc else default + + # Try to get path from registry, if fail use default path + return self.ri.lookup(self.ri.vc, f'{self.vs_ver:0.1f}') or default_vc + + @property + def WindowsSdkVersion(self) -> tuple[LiteralString, ...]: + """ + Microsoft Windows SDK versions for specified MSVC++ version. + + Return + ------ + tuple of str + versions + """ + if self.vs_ver <= 9.0: + return '7.0', '6.1', '6.0a' + elif self.vs_ver == 10.0: + return '7.1', '7.0a' + elif self.vs_ver == 11.0: + return '8.0', '8.0a' + elif self.vs_ver == 12.0: + return '8.1', '8.1a' + elif self.vs_ver >= 14.0: + return '10.0', '8.1' + return () + + @property + def WindowsSdkLastVersion(self): + """ + Microsoft Windows SDK last version. + + Return + ------ + str + version + """ + return self._use_last_dir_name(os.path.join(self.WindowsSdkDir, 'lib')) + + @property + def WindowsSdkDir(self) -> str | None: # noqa: C901 # is too complex (12) # FIXME + """ + Microsoft Windows SDK directory. + + Return + ------ + str + path + """ + sdkdir: str | None = '' + for ver in self.WindowsSdkVersion: + # Try to get it from registry + loc = os.path.join(self.ri.windows_sdk, f'v{ver}') + sdkdir = self.ri.lookup(loc, 'installationfolder') + if sdkdir: + break + if not sdkdir or not os.path.isdir(sdkdir): + # Try to get "VC++ for Python" version from registry + path = os.path.join(self.ri.vc_for_python, f'{self.vc_ver:0.1f}') + install_base = self.ri.lookup(path, 'installdir') + if install_base: + sdkdir = os.path.join(install_base, 'WinSDK') + if not sdkdir or not os.path.isdir(sdkdir): + # If fail, use default new path + for ver in self.WindowsSdkVersion: + intver = ver[: ver.rfind('.')] + path = rf'Microsoft SDKs\Windows Kits\{intver}' + d = os.path.join(self.ProgramFiles, path) + if os.path.isdir(d): + sdkdir = d + if not sdkdir or not os.path.isdir(sdkdir): + # If fail, use default old path + for ver in self.WindowsSdkVersion: + path = rf'Microsoft SDKs\Windows\v{ver}' + d = os.path.join(self.ProgramFiles, path) + if os.path.isdir(d): + sdkdir = d + if not sdkdir: + # If fail, use Platform SDK + sdkdir = os.path.join(self.VCInstallDir, 'PlatformSDK') + return sdkdir + + @property + def WindowsSDKExecutablePath(self): + """ + Microsoft Windows SDK executable directory. + + Return + ------ + str + path + """ + # Find WinSDK NetFx Tools registry dir name + if self.vs_ver <= 11.0: + netfxver = 35 + arch = '' + else: + netfxver = 40 + hidex86 = True if self.vs_ver <= 12.0 else False + arch = self.pi.current_dir(x64=True, hidex86=hidex86).replace('\\', '-') + fx = f'WinSDK-NetFx{netfxver}Tools{arch}' + + # list all possibles registry paths + regpaths = [] + if self.vs_ver >= 14.0: + for ver in self.NetFxSdkVersion: + regpaths += [os.path.join(self.ri.netfx_sdk, ver, fx)] + + for ver in self.WindowsSdkVersion: + regpaths += [os.path.join(self.ri.windows_sdk, f'v{ver}A', fx)] + + # Return installation folder from the more recent path + for path in regpaths: + execpath = self.ri.lookup(path, 'installationfolder') + if execpath: + return execpath + + return None + + @property + def FSharpInstallDir(self): + """ + Microsoft Visual F# directory. + + Return + ------ + str + path + """ + path = os.path.join(self.ri.visualstudio, rf'{self.vs_ver:0.1f}\Setup\F#') + return self.ri.lookup(path, 'productdir') or '' + + @property + def UniversalCRTSdkDir(self): + """ + Microsoft Universal CRT SDK directory. + + Return + ------ + str + path + """ + # Set Kit Roots versions for specified MSVC++ version + vers = ('10', '81') if self.vs_ver >= 14.0 else () + + # Find path of the more recent Kit + for ver in vers: + sdkdir = self.ri.lookup(self.ri.windows_kits_roots, f'kitsroot{ver}') + if sdkdir: + return sdkdir or '' + + return None + + @property + def UniversalCRTSdkLastVersion(self): + """ + Microsoft Universal C Runtime SDK last version. + + Return + ------ + str + version + """ + return self._use_last_dir_name(os.path.join(self.UniversalCRTSdkDir, 'lib')) + + @property + def NetFxSdkVersion(self): + """ + Microsoft .NET Framework SDK versions. + + Return + ------ + tuple of str + versions + """ + # Set FxSdk versions for specified VS version + return ( + ('4.7.2', '4.7.1', '4.7', '4.6.2', '4.6.1', '4.6', '4.5.2', '4.5.1', '4.5') + if self.vs_ver >= 14.0 + else () + ) + + @property + def NetFxSdkDir(self): + """ + Microsoft .NET Framework SDK directory. + + Return + ------ + str + path + """ + sdkdir = '' + for ver in self.NetFxSdkVersion: + loc = os.path.join(self.ri.netfx_sdk, ver) + sdkdir = self.ri.lookup(loc, 'kitsinstallationfolder') + if sdkdir: + break + return sdkdir + + @property + def FrameworkDir32(self): + """ + Microsoft .NET Framework 32bit directory. + + Return + ------ + str + path + """ + # Default path + guess_fw = os.path.join(self.WinDir, r'Microsoft.NET\Framework') + + # Try to get path from registry, if fail use default path + return self.ri.lookup(self.ri.vc, 'frameworkdir32') or guess_fw + + @property + def FrameworkDir64(self): + """ + Microsoft .NET Framework 64bit directory. + + Return + ------ + str + path + """ + # Default path + guess_fw = os.path.join(self.WinDir, r'Microsoft.NET\Framework64') + + # Try to get path from registry, if fail use default path + return self.ri.lookup(self.ri.vc, 'frameworkdir64') or guess_fw + + @property + def FrameworkVersion32(self) -> tuple[str, ...]: + """ + Microsoft .NET Framework 32bit versions. + + Return + ------ + tuple of str + versions + """ + return self._find_dot_net_versions(32) + + @property + def FrameworkVersion64(self) -> tuple[str, ...]: + """ + Microsoft .NET Framework 64bit versions. + + Return + ------ + tuple of str + versions + """ + return self._find_dot_net_versions(64) + + def _find_dot_net_versions(self, bits) -> tuple[str, ...]: + """ + Find Microsoft .NET Framework versions. + + Parameters + ---------- + bits: int + Platform number of bits: 32 or 64. + + Return + ------ + tuple of str + versions + """ + # Find actual .NET version in registry + reg_ver = self.ri.lookup(self.ri.vc, f'frameworkver{bits}') + dot_net_dir = getattr(self, f'FrameworkDir{bits}') + ver = reg_ver or self._use_last_dir_name(dot_net_dir, 'v') or '' + + # Set .NET versions for specified MSVC++ version + if self.vs_ver >= 12.0: + return ver, 'v4.0' + elif self.vs_ver >= 10.0: + return 'v4.0.30319' if ver.lower()[:2] != 'v4' else ver, 'v3.5' + elif self.vs_ver == 9.0: + return 'v3.5', 'v2.0.50727' + elif self.vs_ver == 8.0: + return 'v3.0', 'v2.0.50727' + return () + + @staticmethod + def _use_last_dir_name(path, prefix=''): + """ + Return name of the last dir in path or '' if no dir found. + + Parameters + ---------- + path: str + Use dirs in this path + prefix: str + Use only dirs starting by this prefix + + Return + ------ + str + name + """ + matching_dirs = ( + dir_name + for dir_name in reversed(os.listdir(path)) + if os.path.isdir(os.path.join(path, dir_name)) + and dir_name.startswith(prefix) + ) + return next(matching_dirs, None) or '' + + +class _EnvironmentDict(TypedDict): + include: str + lib: str + libpath: str + path: str + py_vcruntime_redist: NotRequired[str | None] + + +class EnvironmentInfo: + """ + Return environment variables for specified Microsoft Visual C++ version + and platform : Lib, Include, Path and libpath. + + This function is compatible with Microsoft Visual C++ 9.0 to 14.X. + + Script created by analysing Microsoft environment configuration files like + "vcvars[...].bat", "SetEnv.Cmd", "vcbuildtools.bat", ... + + Parameters + ---------- + arch: str + Target architecture. + vc_ver: float + Required Microsoft Visual C++ version. If not set, autodetect the last + version. + vc_min_ver: float + Minimum Microsoft Visual C++ version. + """ + + # Variables and properties in this class use originals CamelCase variables + # names from Microsoft source files for more easy comparison. + + def __init__(self, arch, vc_ver=None, vc_min_ver=0) -> None: + self.pi = PlatformInfo(arch) + self.ri = RegistryInfo(self.pi) + self.si = SystemInfo(self.ri, vc_ver) + + if self.vc_ver < vc_min_ver: + err = 'No suitable Microsoft Visual C++ version found' + raise distutils.errors.DistutilsPlatformError(err) + + @property + def vs_ver(self): + """ + Microsoft Visual Studio. + + Return + ------ + float + version + """ + return self.si.vs_ver + + @property + def vc_ver(self): + """ + Microsoft Visual C++ version. + + Return + ------ + float + version + """ + return self.si.vc_ver + + @property + def VSTools(self): + """ + Microsoft Visual Studio Tools. + + Return + ------ + list of str + paths + """ + paths = [r'Common7\IDE', r'Common7\Tools'] + + if self.vs_ver >= 14.0: + arch_subdir = self.pi.current_dir(hidex86=True, x64=True) + paths += [r'Common7\IDE\CommonExtensions\Microsoft\TestWindow'] + paths += [r'Team Tools\Performance Tools'] + paths += [rf'Team Tools\Performance Tools{arch_subdir}'] + + return [os.path.join(self.si.VSInstallDir, path) for path in paths] + + @property + def VCIncludes(self): + """ + Microsoft Visual C++ & Microsoft Foundation Class Includes. + + Return + ------ + list of str + paths + """ + return [ + os.path.join(self.si.VCInstallDir, 'Include'), + os.path.join(self.si.VCInstallDir, r'ATLMFC\Include'), + ] + + @property + def VCLibraries(self): + """ + Microsoft Visual C++ & Microsoft Foundation Class Libraries. + + Return + ------ + list of str + paths + """ + if self.vs_ver >= 15.0: + arch_subdir = self.pi.target_dir(x64=True) + else: + arch_subdir = self.pi.target_dir(hidex86=True) + paths = [f'Lib{arch_subdir}', rf'ATLMFC\Lib{arch_subdir}'] + + if self.vs_ver >= 14.0: + paths += [rf'Lib\store{arch_subdir}'] + + return [os.path.join(self.si.VCInstallDir, path) for path in paths] + + @property + def VCStoreRefs(self): + """ + Microsoft Visual C++ store references Libraries. + + Return + ------ + list of str + paths + """ + if self.vs_ver < 14.0: + return [] + return [os.path.join(self.si.VCInstallDir, r'Lib\store\references')] + + @property + def VCTools(self): + """ + Microsoft Visual C++ Tools. + + Return + ------ + list of str + paths + + When host CPU is ARM, the tools should be found for ARM. + + >>> getfixture('windows_only') + >>> mp = getfixture('monkeypatch') + >>> mp.setattr(PlatformInfo, 'current_cpu', 'arm64') + >>> ei = EnvironmentInfo(arch='irrelevant') + >>> paths = ei.VCTools + >>> any('HostARM64' in path for path in paths) + True + """ + si = self.si + tools = [os.path.join(si.VCInstallDir, 'VCPackages')] + + forcex86 = True if self.vs_ver <= 10.0 else False + arch_subdir = self.pi.cross_dir(forcex86) + if arch_subdir: + tools += [os.path.join(si.VCInstallDir, f'Bin{arch_subdir}')] + + if self.vs_ver == 14.0: + path = f'Bin{self.pi.current_dir(hidex86=True)}' + tools += [os.path.join(si.VCInstallDir, path)] + + elif self.vs_ver >= 15.0: + host_id = self.pi.current_cpu.replace('amd64', 'x64').upper() + host_dir = os.path.join('bin', f'Host{host_id}%s') + tools += [ + os.path.join(si.VCInstallDir, host_dir % self.pi.target_dir(x64=True)) + ] + + if self.pi.current_cpu != self.pi.target_cpu: + tools += [ + os.path.join( + si.VCInstallDir, host_dir % self.pi.current_dir(x64=True) + ) + ] + + else: + tools += [os.path.join(si.VCInstallDir, 'Bin')] + + return tools + + @property + def OSLibraries(self): + """ + Microsoft Windows SDK Libraries. + + Return + ------ + list of str + paths + """ + if self.vs_ver <= 10.0: + arch_subdir = self.pi.target_dir(hidex86=True, x64=True) + return [os.path.join(self.si.WindowsSdkDir, f'Lib{arch_subdir}')] + + else: + arch_subdir = self.pi.target_dir(x64=True) + lib = os.path.join(self.si.WindowsSdkDir, 'lib') + libver = self._sdk_subdir + return [os.path.join(lib, f'{libver}um{arch_subdir}')] + + @property + def OSIncludes(self): + """ + Microsoft Windows SDK Include. + + Return + ------ + list of str + paths + """ + include = os.path.join(self.si.WindowsSdkDir, 'include') + + if self.vs_ver <= 10.0: + return [include, os.path.join(include, 'gl')] + + else: + if self.vs_ver >= 14.0: + sdkver = self._sdk_subdir + else: + sdkver = '' + return [ + os.path.join(include, f'{sdkver}shared'), + os.path.join(include, f'{sdkver}um'), + os.path.join(include, f'{sdkver}winrt'), + ] + + @property + def OSLibpath(self): + """ + Microsoft Windows SDK Libraries Paths. + + Return + ------ + list of str + paths + """ + ref = os.path.join(self.si.WindowsSdkDir, 'References') + libpath = [] + + if self.vs_ver <= 9.0: + libpath += self.OSLibraries + + if self.vs_ver >= 11.0: + libpath += [os.path.join(ref, r'CommonConfiguration\Neutral')] + + if self.vs_ver >= 14.0: + libpath += [ + ref, + os.path.join(self.si.WindowsSdkDir, 'UnionMetadata'), + os.path.join(ref, 'Windows.Foundation.UniversalApiContract', '1.0.0.0'), + os.path.join(ref, 'Windows.Foundation.FoundationContract', '1.0.0.0'), + os.path.join( + ref, 'Windows.Networking.Connectivity.WwanContract', '1.0.0.0' + ), + os.path.join( + self.si.WindowsSdkDir, + 'ExtensionSDKs', + 'Microsoft.VCLibs', + f'{self.vs_ver:0.1f}', + 'References', + 'CommonConfiguration', + 'neutral', + ), + ] + return libpath + + @property + def SdkTools(self): + """ + Microsoft Windows SDK Tools. + + Return + ------ + list of str + paths + """ + return list(self._sdk_tools()) + + def _sdk_tools(self): + """ + Microsoft Windows SDK Tools paths generator. + + Return + ------ + generator of str + paths + """ + if self.vs_ver < 15.0: + bin_dir = 'Bin' if self.vs_ver <= 11.0 else r'Bin\x86' + yield os.path.join(self.si.WindowsSdkDir, bin_dir) + + if not self.pi.current_is_x86(): + arch_subdir = self.pi.current_dir(x64=True) + path = f'Bin{arch_subdir}' + yield os.path.join(self.si.WindowsSdkDir, path) + + if self.vs_ver in (10.0, 11.0): + if self.pi.target_is_x86(): + arch_subdir = '' + else: + arch_subdir = self.pi.current_dir(hidex86=True, x64=True) + path = rf'Bin\NETFX 4.0 Tools{arch_subdir}' + yield os.path.join(self.si.WindowsSdkDir, path) + + elif self.vs_ver >= 15.0: + path = os.path.join(self.si.WindowsSdkDir, 'Bin') + arch_subdir = self.pi.current_dir(x64=True) + sdkver = self.si.WindowsSdkLastVersion + yield os.path.join(path, f'{sdkver}{arch_subdir}') + + if self.si.WindowsSDKExecutablePath: + yield self.si.WindowsSDKExecutablePath + + @property + def _sdk_subdir(self): + """ + Microsoft Windows SDK version subdir. + + Return + ------ + str + subdir + """ + ucrtver = self.si.WindowsSdkLastVersion + return (f'{ucrtver}\\') if ucrtver else '' + + @property + def SdkSetup(self): + """ + Microsoft Windows SDK Setup. + + Return + ------ + list of str + paths + """ + if self.vs_ver > 9.0: + return [] + + return [os.path.join(self.si.WindowsSdkDir, 'Setup')] + + @property + def FxTools(self): + """ + Microsoft .NET Framework Tools. + + Return + ------ + list of str + paths + """ + pi = self.pi + si = self.si + + if self.vs_ver <= 10.0: + include32 = True + include64 = not pi.target_is_x86() and not pi.current_is_x86() + else: + include32 = pi.target_is_x86() or pi.current_is_x86() + include64 = pi.current_cpu == 'amd64' or pi.target_cpu == 'amd64' + + tools = [] + if include32: + tools += [ + os.path.join(si.FrameworkDir32, ver) for ver in si.FrameworkVersion32 + ] + if include64: + tools += [ + os.path.join(si.FrameworkDir64, ver) for ver in si.FrameworkVersion64 + ] + return tools + + @property + def NetFxSDKLibraries(self): + """ + Microsoft .Net Framework SDK Libraries. + + Return + ------ + list of str + paths + """ + if self.vs_ver < 14.0 or not self.si.NetFxSdkDir: + return [] + + arch_subdir = self.pi.target_dir(x64=True) + return [os.path.join(self.si.NetFxSdkDir, rf'lib\um{arch_subdir}')] + + @property + def NetFxSDKIncludes(self): + """ + Microsoft .Net Framework SDK Includes. + + Return + ------ + list of str + paths + """ + if self.vs_ver < 14.0 or not self.si.NetFxSdkDir: + return [] + + return [os.path.join(self.si.NetFxSdkDir, r'include\um')] + + @property + def VsTDb(self): + """ + Microsoft Visual Studio Team System Database. + + Return + ------ + list of str + paths + """ + return [os.path.join(self.si.VSInstallDir, r'VSTSDB\Deploy')] + + @property + def MSBuild(self): + """ + Microsoft Build Engine. + + Return + ------ + list of str + paths + """ + if self.vs_ver < 12.0: + return [] + elif self.vs_ver < 15.0: + base_path = self.si.ProgramFilesx86 + arch_subdir = self.pi.current_dir(hidex86=True) + else: + base_path = self.si.VSInstallDir + arch_subdir = '' + + path = rf'MSBuild\{self.vs_ver:0.1f}\bin{arch_subdir}' + build = [os.path.join(base_path, path)] + + if self.vs_ver >= 15.0: + # Add Roslyn C# & Visual Basic Compiler + build += [os.path.join(base_path, path, 'Roslyn')] + + return build + + @property + def HTMLHelpWorkshop(self): + """ + Microsoft HTML Help Workshop. + + Return + ------ + list of str + paths + """ + if self.vs_ver < 11.0: + return [] + + return [os.path.join(self.si.ProgramFilesx86, 'HTML Help Workshop')] + + @property + def UCRTLibraries(self): + """ + Microsoft Universal C Runtime SDK Libraries. + + Return + ------ + list of str + paths + """ + if self.vs_ver < 14.0: + return [] + + arch_subdir = self.pi.target_dir(x64=True) + lib = os.path.join(self.si.UniversalCRTSdkDir, 'lib') + ucrtver = self._ucrt_subdir + return [os.path.join(lib, f'{ucrtver}ucrt{arch_subdir}')] + + @property + def UCRTIncludes(self): + """ + Microsoft Universal C Runtime SDK Include. + + Return + ------ + list of str + paths + """ + if self.vs_ver < 14.0: + return [] + + include = os.path.join(self.si.UniversalCRTSdkDir, 'include') + return [os.path.join(include, f'{self._ucrt_subdir}ucrt')] + + @property + def _ucrt_subdir(self): + """ + Microsoft Universal C Runtime SDK version subdir. + + Return + ------ + str + subdir + """ + ucrtver = self.si.UniversalCRTSdkLastVersion + return (f'{ucrtver}\\') if ucrtver else '' + + @property + def FSharp(self): + """ + Microsoft Visual F#. + + Return + ------ + list of str + paths + """ + if 11.0 > self.vs_ver > 12.0: + return [] + + return [self.si.FSharpInstallDir] + + @property + def VCRuntimeRedist(self) -> str | None: + """ + Microsoft Visual C++ runtime redistributable dll. + + Returns the first suitable path found or None. + """ + vcruntime = f'vcruntime{self.vc_ver}0.dll' + arch_subdir = self.pi.target_dir(x64=True).strip('\\') + + # Installation prefixes candidates + prefixes = [] + tools_path = self.si.VCInstallDir + redist_path = os.path.dirname(tools_path.replace(r'\Tools', r'\Redist')) + if os.path.isdir(redist_path): + # Redist version may not be exactly the same as tools + redist_path = os.path.join(redist_path, os.listdir(redist_path)[-1]) + prefixes += [redist_path, os.path.join(redist_path, 'onecore')] + + prefixes += [os.path.join(tools_path, 'redist')] # VS14 legacy path + + # CRT directory + crt_dirs = ( + f'Microsoft.VC{self.vc_ver * 10}.CRT', + # Sometime store in directory with VS version instead of VC + f'Microsoft.VC{int(self.vs_ver) * 10}.CRT', + ) + + # vcruntime path + candidate_paths = ( + os.path.join(prefix, arch_subdir, crt_dir, vcruntime) + for (prefix, crt_dir) in itertools.product(prefixes, crt_dirs) + ) + return next(filter(os.path.isfile, candidate_paths), None) # type: ignore[arg-type] #python/mypy#12682 + + def return_env(self, exists: bool = True) -> _EnvironmentDict: + """ + Return environment dict. + + Parameters + ---------- + exists: bool + It True, only return existing paths. + + Return + ------ + dict + environment + """ + env = _EnvironmentDict( + include=self._build_paths( + 'include', + [ + self.VCIncludes, + self.OSIncludes, + self.UCRTIncludes, + self.NetFxSDKIncludes, + ], + exists, + ), + lib=self._build_paths( + 'lib', + [ + self.VCLibraries, + self.OSLibraries, + self.FxTools, + self.UCRTLibraries, + self.NetFxSDKLibraries, + ], + exists, + ), + libpath=self._build_paths( + 'libpath', + [self.VCLibraries, self.FxTools, self.VCStoreRefs, self.OSLibpath], + exists, + ), + path=self._build_paths( + 'path', + [ + self.VCTools, + self.VSTools, + self.VsTDb, + self.SdkTools, + self.SdkSetup, + self.FxTools, + self.MSBuild, + self.HTMLHelpWorkshop, + self.FSharp, + ], + exists, + ), + ) + if self.vs_ver >= 14 and self.VCRuntimeRedist: + env['py_vcruntime_redist'] = self.VCRuntimeRedist + return env + + def _build_paths(self, name, spec_path_lists, exists): + """ + Given an environment variable name and specified paths, + return a pathsep-separated string of paths containing + unique, extant, directories from those paths and from + the environment variable. Raise an error if no paths + are resolved. + + Parameters + ---------- + name: str + Environment variable name + spec_path_lists: list of str + Paths + exists: bool + It True, only return existing paths. + + Return + ------ + str + Pathsep-separated paths + """ + # flatten spec_path_lists + spec_paths = itertools.chain.from_iterable(spec_path_lists) + env_paths = environ.get(name, '').split(os.pathsep) + paths = itertools.chain(spec_paths, env_paths) + extant_paths = list(filter(os.path.isdir, paths)) if exists else paths + if not extant_paths: + msg = f"{name.upper()} environment variable is empty" + raise distutils.errors.DistutilsPlatformError(msg) + unique_paths = unique_everseen(extant_paths) + return os.pathsep.join(unique_paths) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/namespaces.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/namespaces.py new file mode 100644 index 0000000000000000000000000000000000000000..85ea2ebd654c480b8c19d1715b3772c4bcfd812e --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/namespaces.py @@ -0,0 +1,106 @@ +import itertools +import os + +from .compat import py312 + +from distutils import log + +flatten = itertools.chain.from_iterable + + +class Installer: + nspkg_ext = '-nspkg.pth' + + def install_namespaces(self) -> None: + nsp = self._get_all_ns_packages() + if not nsp: + return + filename = self._get_nspkg_file() + self.outputs.append(filename) + log.info("Installing %s", filename) + lines = map(self._gen_nspkg_line, nsp) + + if self.dry_run: + # always generate the lines, even in dry run + list(lines) + return + + with open(filename, 'wt', encoding=py312.PTH_ENCODING) as f: + # Python<3.13 requires encoding="locale" instead of "utf-8" + # See: python/cpython#77102 + f.writelines(lines) + + def uninstall_namespaces(self) -> None: + filename = self._get_nspkg_file() + if not os.path.exists(filename): + return + log.info("Removing %s", filename) + os.remove(filename) + + def _get_nspkg_file(self): + filename, _ = os.path.splitext(self._get_target()) + return filename + self.nspkg_ext + + def _get_target(self): + return self.target + + _nspkg_tmpl = ( + "import sys, types, os", + "p = os.path.join(%(root)s, *%(pth)r)", + "importlib = __import__('importlib.util')", + "__import__('importlib.machinery')", + ( + "m = " + "sys.modules.setdefault(%(pkg)r, " + "importlib.util.module_from_spec(" + "importlib.machinery.PathFinder.find_spec(%(pkg)r, " + "[os.path.dirname(p)])))" + ), + ("m = m or sys.modules.setdefault(%(pkg)r, types.ModuleType(%(pkg)r))"), + "mp = (m or []) and m.__dict__.setdefault('__path__',[])", + "(p not in mp) and mp.append(p)", + ) + "lines for the namespace installer" + + _nspkg_tmpl_multi = ('m and setattr(sys.modules[%(parent)r], %(child)r, m)',) + "additional line(s) when a parent package is indicated" + + def _get_root(self): + return "sys._getframe(1).f_locals['sitedir']" + + def _gen_nspkg_line(self, pkg): + pth = tuple(pkg.split('.')) + root = self._get_root() + tmpl_lines = self._nspkg_tmpl + parent, sep, child = pkg.rpartition('.') + if parent: + tmpl_lines += self._nspkg_tmpl_multi + return ';'.join(tmpl_lines) % locals() + '\n' + + def _get_all_ns_packages(self): + """Return sorted list of all package namespaces""" + pkgs = self.distribution.namespace_packages or [] + return sorted(set(flatten(map(self._pkg_names, pkgs)))) + + @staticmethod + def _pkg_names(pkg): + """ + Given a namespace package, yield the components of that + package. + + >>> names = Installer._pkg_names('a.b.c') + >>> set(names) == set(['a', 'a.b', 'a.b.c']) + True + """ + parts = pkg.split('.') + while parts: + yield '.'.join(parts) + parts.pop() + + +class DevelopInstaller(Installer): + def _get_root(self): + return repr(str(self.egg_path)) + + def _get_target(self): + return self.egg_link diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/package_index.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/package_index.py new file mode 100644 index 0000000000000000000000000000000000000000..3500c2d86f15395b1e8be9535b36b90b7f2453f2 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/package_index.py @@ -0,0 +1,1179 @@ +"""PyPI and direct package downloading.""" + +from __future__ import annotations + +import base64 +import configparser +import hashlib +import html +import http.client +import io +import itertools +import os +import re +import shutil +import socket +import subprocess +import sys +import urllib.error +import urllib.parse +import urllib.request +from fnmatch import translate +from functools import wraps +from typing import NamedTuple + +from more_itertools import unique_everseen + +import setuptools +from pkg_resources import ( + BINARY_DIST, + CHECKOUT_DIST, + DEVELOP_DIST, + EGG_DIST, + SOURCE_DIST, + Distribution, + Environment, + Requirement, + find_distributions, + normalize_path, + parse_version, + safe_name, + safe_version, + to_filename, +) +from setuptools.wheel import Wheel + +from .unicode_utils import _cfg_read_utf8_with_fallback, _read_utf8_with_fallback + +from distutils import log +from distutils.errors import DistutilsError + +EGG_FRAGMENT = re.compile(r'^egg=([-A-Za-z0-9_.+!]+)$') +HREF = re.compile(r"""href\s*=\s*['"]?([^'"> ]+)""", re.I) +PYPI_MD5 = re.compile( + r'
([^<]+)\n\s+\(md5\)' +) +URL_SCHEME = re.compile('([-+.a-z0-9]{2,}):', re.I).match +EXTENSIONS = ".tar.gz .tar.bz2 .tar .zip .tgz".split() + +__all__ = [ + 'PackageIndex', + 'distros_for_url', + 'parse_bdist_wininst', + 'interpret_distro_name', +] + +_SOCKET_TIMEOUT = 15 + +user_agent = f"setuptools/{setuptools.__version__} Python-urllib/{sys.version_info.major}.{sys.version_info.minor}" + + +def parse_requirement_arg(spec): + try: + return Requirement.parse(spec) + except ValueError as e: + raise DistutilsError( + f"Not a URL, existing file, or requirement spec: {spec!r}" + ) from e + + +def parse_bdist_wininst(name): + """Return (base,pyversion) or (None,None) for possible .exe name""" + + lower = name.lower() + base, py_ver, plat = None, None, None + + if lower.endswith('.exe'): + if lower.endswith('.win32.exe'): + base = name[:-10] + plat = 'win32' + elif lower.startswith('.win32-py', -16): + py_ver = name[-7:-4] + base = name[:-16] + plat = 'win32' + elif lower.endswith('.win-amd64.exe'): + base = name[:-14] + plat = 'win-amd64' + elif lower.startswith('.win-amd64-py', -20): + py_ver = name[-7:-4] + base = name[:-20] + plat = 'win-amd64' + return base, py_ver, plat + + +def egg_info_for_url(url): + parts = urllib.parse.urlparse(url) + _scheme, server, path, _parameters, _query, fragment = parts + base = urllib.parse.unquote(path.split('/')[-1]) + if server == 'sourceforge.net' and base == 'download': # XXX Yuck + base = urllib.parse.unquote(path.split('/')[-2]) + if '#' in base: + base, fragment = base.split('#', 1) + return base, fragment + + +def distros_for_url(url, metadata=None): + """Yield egg or source distribution objects that might be found at a URL""" + base, fragment = egg_info_for_url(url) + yield from distros_for_location(url, base, metadata) + if fragment: + match = EGG_FRAGMENT.match(fragment) + if match: + yield from interpret_distro_name( + url, match.group(1), metadata, precedence=CHECKOUT_DIST + ) + + +def distros_for_location(location, basename, metadata=None): + """Yield egg or source distribution objects based on basename""" + if basename.endswith('.egg.zip'): + basename = basename[:-4] # strip the .zip + if basename.endswith('.egg') and '-' in basename: + # only one, unambiguous interpretation + return [Distribution.from_location(location, basename, metadata)] + if basename.endswith('.whl') and '-' in basename: + wheel = Wheel(basename) + if not wheel.is_compatible(): + return [] + return [ + Distribution( + location=location, + project_name=wheel.project_name, + version=wheel.version, + # Increase priority over eggs. + precedence=EGG_DIST + 1, + ) + ] + if basename.endswith('.exe'): + win_base, py_ver, platform = parse_bdist_wininst(basename) + if win_base is not None: + return interpret_distro_name( + location, win_base, metadata, py_ver, BINARY_DIST, platform + ) + # Try source distro extensions (.zip, .tgz, etc.) + # + for ext in EXTENSIONS: + if basename.endswith(ext): + basename = basename[: -len(ext)] + return interpret_distro_name(location, basename, metadata) + return [] # no extension matched + + +def distros_for_filename(filename, metadata=None): + """Yield possible egg or source distribution objects based on a filename""" + return distros_for_location( + normalize_path(filename), os.path.basename(filename), metadata + ) + + +def interpret_distro_name( + location, basename, metadata, py_version=None, precedence=SOURCE_DIST, platform=None +): + """Generate the interpretation of a source distro name + + Note: if `location` is a filesystem filename, you should call + ``pkg_resources.normalize_path()`` on it before passing it to this + routine! + """ + + parts = basename.split('-') + if not py_version and any(re.match(r'py\d\.\d$', p) for p in parts[2:]): + # it is a bdist_dumb, not an sdist -- bail out + return + + # find the pivot (p) that splits the name from the version. + # infer the version as the first item that has a digit. + for p in range(len(parts)): + if parts[p][:1].isdigit(): + break + else: + p = len(parts) + + yield Distribution( + location, + metadata, + '-'.join(parts[:p]), + '-'.join(parts[p:]), + py_version=py_version, + precedence=precedence, + platform=platform, + ) + + +def unique_values(func): + """ + Wrap a function returning an iterable such that the resulting iterable + only ever yields unique items. + """ + + @wraps(func) + def wrapper(*args, **kwargs): + return unique_everseen(func(*args, **kwargs)) + + return wrapper + + +REL = re.compile(r"""<([^>]*\srel\s{0,10}=\s{0,10}['"]?([^'" >]+)[^>]*)>""", re.I) +""" +Regex for an HTML tag with 'rel="val"' attributes. +""" + + +@unique_values +def find_external_links(url, page): + """Find rel="homepage" and rel="download" links in `page`, yielding URLs""" + + for match in REL.finditer(page): + tag, rel = match.groups() + rels = set(map(str.strip, rel.lower().split(','))) + if 'homepage' in rels or 'download' in rels: + for match in HREF.finditer(tag): + yield urllib.parse.urljoin(url, htmldecode(match.group(1))) + + for tag in ("Home Page", "Download URL"): + pos = page.find(tag) + if pos != -1: + match = HREF.search(page, pos) + if match: + yield urllib.parse.urljoin(url, htmldecode(match.group(1))) + + +class ContentChecker: + """ + A null content checker that defines the interface for checking content + """ + + def feed(self, block): + """ + Feed a block of data to the hash. + """ + return + + def is_valid(self): + """ + Check the hash. Return False if validation fails. + """ + return True + + def report(self, reporter, template): + """ + Call reporter with information about the checker (hash name) + substituted into the template. + """ + return + + +class HashChecker(ContentChecker): + pattern = re.compile( + r'(?Psha1|sha224|sha384|sha256|sha512|md5)=' + r'(?P[a-f0-9]+)' + ) + + def __init__(self, hash_name, expected) -> None: + self.hash_name = hash_name + self.hash = hashlib.new(hash_name) + self.expected = expected + + @classmethod + def from_url(cls, url): + "Construct a (possibly null) ContentChecker from a URL" + fragment = urllib.parse.urlparse(url)[-1] + if not fragment: + return ContentChecker() + match = cls.pattern.search(fragment) + if not match: + return ContentChecker() + return cls(**match.groupdict()) + + def feed(self, block): + self.hash.update(block) + + def is_valid(self): + return self.hash.hexdigest() == self.expected + + def report(self, reporter, template): + msg = template % self.hash_name + return reporter(msg) + + +class PackageIndex(Environment): + """A distribution index that scans web pages for download URLs""" + + def __init__( + self, + index_url: str = "https://pypi.org/simple/", + hosts=('*',), + ca_bundle=None, + verify_ssl: bool = True, + *args, + **kw, + ) -> None: + super().__init__(*args, **kw) + self.index_url = index_url + "/"[: not index_url.endswith('/')] + self.scanned_urls: dict = {} + self.fetched_urls: dict = {} + self.package_pages: dict = {} + self.allows = re.compile('|'.join(map(translate, hosts))).match + self.to_scan: list = [] + self.opener = urllib.request.urlopen + + def add(self, dist): + # ignore invalid versions + try: + parse_version(dist.version) + except Exception: + return None + return super().add(dist) + + # FIXME: 'PackageIndex.process_url' is too complex (14) + def process_url(self, url, retrieve: bool = False) -> None: # noqa: C901 + """Evaluate a URL as a possible download, and maybe retrieve it""" + if url in self.scanned_urls and not retrieve: + return + self.scanned_urls[url] = True + if not URL_SCHEME(url): + self.process_filename(url) + return + else: + dists = list(distros_for_url(url)) + if dists: + if not self.url_ok(url): + return + self.debug("Found link: %s", url) + + if dists or not retrieve or url in self.fetched_urls: + list(map(self.add, dists)) + return # don't need the actual page + + if not self.url_ok(url): + self.fetched_urls[url] = True + return + + self.info("Reading %s", url) + self.fetched_urls[url] = True # prevent multiple fetch attempts + tmpl = "Download error on %s: %%s -- Some packages may not be found!" + f = self.open_url(url, tmpl % url) + if f is None: + return + if isinstance(f, urllib.error.HTTPError) and f.code == 401: + self.info(f"Authentication error: {f.msg}") + self.fetched_urls[f.url] = True + if 'html' not in f.headers.get('content-type', '').lower(): + f.close() # not html, we can't process it + return + + base = f.url # handle redirects + page = f.read() + if not isinstance(page, str): + # In Python 3 and got bytes but want str. + if isinstance(f, urllib.error.HTTPError): + # Errors have no charset, assume latin1: + charset = 'latin-1' + else: + charset = f.headers.get_param('charset') or 'latin-1' + page = page.decode(charset, "ignore") + f.close() + for match in HREF.finditer(page): + link = urllib.parse.urljoin(base, htmldecode(match.group(1))) + self.process_url(link) + if url.startswith(self.index_url) and getattr(f, 'code', None) != 404: + page = self.process_index(url, page) + + def process_filename(self, fn, nested: bool = False) -> None: + # process filenames or directories + if not os.path.exists(fn): + self.warn("Not found: %s", fn) + return + + if os.path.isdir(fn) and not nested: + path = os.path.realpath(fn) + for item in os.listdir(path): + self.process_filename(os.path.join(path, item), True) + + dists = distros_for_filename(fn) + if dists: + self.debug("Found: %s", fn) + list(map(self.add, dists)) + + def url_ok(self, url, fatal: bool = False) -> bool: + s = URL_SCHEME(url) + is_file = s and s.group(1).lower() == 'file' + if is_file or self.allows(urllib.parse.urlparse(url)[1]): + return True + msg = ( + "\nNote: Bypassing %s (disallowed host; see " + "https://setuptools.pypa.io/en/latest/deprecated/" + "easy_install.html#restricting-downloads-with-allow-hosts for details).\n" + ) + if fatal: + raise DistutilsError(msg % url) + else: + self.warn(msg, url) + return False + + def scan_egg_links(self, search_path) -> None: + dirs = filter(os.path.isdir, search_path) + egg_links = ( + (path, entry) + for path in dirs + for entry in os.listdir(path) + if entry.endswith('.egg-link') + ) + list(itertools.starmap(self.scan_egg_link, egg_links)) + + def scan_egg_link(self, path, entry) -> None: + content = _read_utf8_with_fallback(os.path.join(path, entry)) + # filter non-empty lines + lines = list(filter(None, map(str.strip, content.splitlines()))) + + if len(lines) != 2: + # format is not recognized; punt + return + + egg_path, _setup_path = lines + + for dist in find_distributions(os.path.join(path, egg_path)): + dist.location = os.path.join(path, *lines) + dist.precedence = SOURCE_DIST + self.add(dist) + + def _scan(self, link): + # Process a URL to see if it's for a package page + NO_MATCH_SENTINEL = None, None + if not link.startswith(self.index_url): + return NO_MATCH_SENTINEL + + parts = list(map(urllib.parse.unquote, link[len(self.index_url) :].split('/'))) + if len(parts) != 2 or '#' in parts[1]: + return NO_MATCH_SENTINEL + + # it's a package page, sanitize and index it + pkg = safe_name(parts[0]) + ver = safe_version(parts[1]) + self.package_pages.setdefault(pkg.lower(), {})[link] = True + return to_filename(pkg), to_filename(ver) + + def process_index(self, url, page): + """Process the contents of a PyPI page""" + + # process an index page into the package-page index + for match in HREF.finditer(page): + try: + self._scan(urllib.parse.urljoin(url, htmldecode(match.group(1)))) + except ValueError: + pass + + pkg, ver = self._scan(url) # ensure this page is in the page index + if not pkg: + return "" # no sense double-scanning non-package pages + + # process individual package page + for new_url in find_external_links(url, page): + # Process the found URL + base, frag = egg_info_for_url(new_url) + if base.endswith('.py') and not frag: + if ver: + new_url += f'#egg={pkg}-{ver}' + else: + self.need_version_info(url) + self.scan_url(new_url) + + return PYPI_MD5.sub( + lambda m: '{}'.format(*m.group(1, 3, 2)), page + ) + + def need_version_info(self, url) -> None: + self.scan_all( + "Page at %s links to .py file(s) without version info; an index " + "scan is required.", + url, + ) + + def scan_all(self, msg=None, *args) -> None: + if self.index_url not in self.fetched_urls: + if msg: + self.warn(msg, *args) + self.info("Scanning index of all packages (this may take a while)") + self.scan_url(self.index_url) + + def find_packages(self, requirement) -> None: + self.scan_url(self.index_url + requirement.unsafe_name + '/') + + if not self.package_pages.get(requirement.key): + # Fall back to safe version of the name + self.scan_url(self.index_url + requirement.project_name + '/') + + if not self.package_pages.get(requirement.key): + # We couldn't find the target package, so search the index page too + self.not_found_in_index(requirement) + + for url in list(self.package_pages.get(requirement.key, ())): + # scan each page that might be related to the desired package + self.scan_url(url) + + def obtain(self, requirement, installer=None): + self.prescan() + self.find_packages(requirement) + for dist in self[requirement.key]: + if dist in requirement: + return dist + self.debug("%s does not match %s", requirement, dist) + return super().obtain(requirement, installer) + + def check_hash(self, checker, filename, tfp) -> None: + """ + checker is a ContentChecker + """ + checker.report(self.debug, f"Validating %s checksum for {filename}") + if not checker.is_valid(): + tfp.close() + os.unlink(filename) + raise DistutilsError( + f"{checker.hash.name} validation failed for {os.path.basename(filename)}; " + "possible download problem?" + ) + + def add_find_links(self, urls) -> None: + """Add `urls` to the list that will be prescanned for searches""" + for url in urls: + if ( + self.to_scan is None # if we have already "gone online" + or not URL_SCHEME(url) # or it's a local file/directory + or url.startswith('file:') + or list(distros_for_url(url)) # or a direct package link + ): + # then go ahead and process it now + self.scan_url(url) + else: + # otherwise, defer retrieval till later + self.to_scan.append(url) + + def prescan(self): + """Scan urls scheduled for prescanning (e.g. --find-links)""" + if self.to_scan: + list(map(self.scan_url, self.to_scan)) + self.to_scan = None # from now on, go ahead and process immediately + + def not_found_in_index(self, requirement) -> None: + if self[requirement.key]: # we've seen at least one distro + meth, msg = self.info, "Couldn't retrieve index page for %r" + else: # no distros seen for this name, might be misspelled + meth, msg = self.warn, "Couldn't find index page for %r (maybe misspelled?)" + meth(msg, requirement.unsafe_name) + self.scan_all() + + def download(self, spec, tmpdir): + """Locate and/or download `spec` to `tmpdir`, returning a local path + + `spec` may be a ``Requirement`` object, or a string containing a URL, + an existing local filename, or a project/version requirement spec + (i.e. the string form of a ``Requirement`` object). If it is the URL + of a .py file with an unambiguous ``#egg=name-version`` tag (i.e., one + that escapes ``-`` as ``_`` throughout), a trivial ``setup.py`` is + automatically created alongside the downloaded file. + + If `spec` is a ``Requirement`` object or a string containing a + project/version requirement spec, this method returns the location of + a matching distribution (possibly after downloading it to `tmpdir`). + If `spec` is a locally existing file or directory name, it is simply + returned unchanged. If `spec` is a URL, it is downloaded to a subpath + of `tmpdir`, and the local filename is returned. Various errors may be + raised if a problem occurs during downloading. + """ + if not isinstance(spec, Requirement): + scheme = URL_SCHEME(spec) + if scheme: + # It's a url, download it to tmpdir + found = self._download_url(spec, tmpdir) + base, fragment = egg_info_for_url(spec) + if base.endswith('.py'): + found = self.gen_setup(found, fragment, tmpdir) + return found + elif os.path.exists(spec): + # Existing file or directory, just return it + return spec + else: + spec = parse_requirement_arg(spec) + return getattr(self.fetch_distribution(spec, tmpdir), 'location', None) + + def fetch_distribution( # noqa: C901 # is too complex (14) # FIXME + self, + requirement, + tmpdir, + force_scan: bool = False, + source: bool = False, + develop_ok: bool = False, + local_index=None, + ) -> Distribution | None: + """Obtain a distribution suitable for fulfilling `requirement` + + `requirement` must be a ``pkg_resources.Requirement`` instance. + If necessary, or if the `force_scan` flag is set, the requirement is + searched for in the (online) package index as well as the locally + installed packages. If a distribution matching `requirement` is found, + the returned distribution's ``location`` is the value you would have + gotten from calling the ``download()`` method with the matching + distribution's URL or filename. If no matching distribution is found, + ``None`` is returned. + + If the `source` flag is set, only source distributions and source + checkout links will be considered. Unless the `develop_ok` flag is + set, development and system eggs (i.e., those using the ``.egg-info`` + format) will be ignored. + """ + # process a Requirement + self.info("Searching for %s", requirement) + skipped = set() + dist = None + + def find(req, env: Environment | None = None): + if env is None: + env = self + # Find a matching distribution; may be called more than once + + for dist in env[req.key]: + if dist.precedence == DEVELOP_DIST and not develop_ok: + if dist not in skipped: + self.warn( + "Skipping development or system egg: %s", + dist, + ) + skipped.add(dist) + continue + + test = dist in req and (dist.precedence <= SOURCE_DIST or not source) + if test: + loc = self.download(dist.location, tmpdir) + dist.download_location = loc + if os.path.exists(dist.download_location): + return dist + + return None + + if force_scan: + self.prescan() + self.find_packages(requirement) + dist = find(requirement) + + if not dist and local_index is not None: + dist = find(requirement, local_index) + + if dist is None: + if self.to_scan is not None: + self.prescan() + dist = find(requirement) + + if dist is None and not force_scan: + self.find_packages(requirement) + dist = find(requirement) + + if dist is None: + self.warn( + "No local packages or working download links found for %s%s", + (source and "a source distribution of " or ""), + requirement, + ) + return None + else: + self.info("Best match: %s", dist) + return dist.clone(location=dist.download_location) + + def fetch( + self, requirement, tmpdir, force_scan: bool = False, source: bool = False + ) -> str | None: + """Obtain a file suitable for fulfilling `requirement` + + DEPRECATED; use the ``fetch_distribution()`` method now instead. For + backward compatibility, this routine is identical but returns the + ``location`` of the downloaded distribution instead of a distribution + object. + """ + dist = self.fetch_distribution(requirement, tmpdir, force_scan, source) + if dist is not None: + return dist.location + return None + + def gen_setup(self, filename, fragment, tmpdir): + match = EGG_FRAGMENT.match(fragment) + dists = ( + match + and [ + d + for d in interpret_distro_name(filename, match.group(1), None) + if d.version + ] + or [] + ) + + if len(dists) == 1: # unambiguous ``#egg`` fragment + basename = os.path.basename(filename) + + # Make sure the file has been downloaded to the temp dir. + if os.path.dirname(filename) != tmpdir: + dst = os.path.join(tmpdir, basename) + if not (os.path.exists(dst) and os.path.samefile(filename, dst)): + shutil.copy2(filename, dst) + filename = dst + + with open(os.path.join(tmpdir, 'setup.py'), 'w', encoding="utf-8") as file: + file.write( + "from setuptools import setup\n" + f"setup(name={dists[0].project_name!r}, version={dists[0].version!r}, py_modules=[{os.path.splitext(basename)[0]!r}])\n" + ) + return filename + + elif match: + raise DistutilsError( + f"Can't unambiguously interpret project/version identifier {fragment!r}; " + "any dashes in the name or version should be escaped using " + f"underscores. {dists!r}" + ) + else: + raise DistutilsError( + "Can't process plain .py files without an '#egg=name-version'" + " suffix to enable automatic setup script generation." + ) + + dl_blocksize = 8192 + + def _download_to(self, url, filename): + self.info("Downloading %s", url) + # Download the file + fp = None + try: + checker = HashChecker.from_url(url) + fp = self.open_url(url) + if isinstance(fp, urllib.error.HTTPError): + raise DistutilsError(f"Can't download {url}: {fp.code} {fp.msg}") + headers = fp.info() + blocknum = 0 + bs = self.dl_blocksize + size = -1 + if "content-length" in headers: + # Some servers return multiple Content-Length headers :( + sizes = headers.get_all('Content-Length') + size = max(map(int, sizes)) + self.reporthook(url, filename, blocknum, bs, size) + with open(filename, 'wb') as tfp: + while True: + block = fp.read(bs) + if block: + checker.feed(block) + tfp.write(block) + blocknum += 1 + self.reporthook(url, filename, blocknum, bs, size) + else: + break + self.check_hash(checker, filename, tfp) + return headers + finally: + if fp: + fp.close() + + def reporthook(self, url, filename, blocknum, blksize, size) -> None: + pass # no-op + + # FIXME: + def open_url(self, url, warning=None): # noqa: C901 # is too complex (12) + if url.startswith('file:'): + return local_open(url) + try: + return open_with_auth(url, self.opener) + except (ValueError, http.client.InvalidURL) as v: + msg = ' '.join([str(arg) for arg in v.args]) + if warning: + self.warn(warning, msg) + else: + raise DistutilsError(f'{url} {msg}') from v + except urllib.error.HTTPError as v: + return v + except urllib.error.URLError as v: + if warning: + self.warn(warning, v.reason) + else: + raise DistutilsError(f"Download error for {url}: {v.reason}") from v + except http.client.BadStatusLine as v: + if warning: + self.warn(warning, v.line) + else: + raise DistutilsError( + f'{url} returned a bad status line. The server might be ' + f'down, {v.line}' + ) from v + except (http.client.HTTPException, OSError) as v: + if warning: + self.warn(warning, v) + else: + raise DistutilsError(f"Download error for {url}: {v}") from v + + @staticmethod + def _sanitize(name): + r""" + Replace unsafe path directives with underscores. + + >>> san = PackageIndex._sanitize + >>> san('/home/user/.ssh/authorized_keys') + '_home_user_.ssh_authorized_keys' + >>> san('..\\foo\\bing') + '__foo_bing' + >>> san('D:bar') + 'D_bar' + >>> san('C:\\bar') + 'C__bar' + >>> san('foo..bar') + 'foo..bar' + >>> san('D:../foo') + 'D___foo' + """ + pattern = '|'.join(( + # drive letters + r':', + # path separators + r'[/\\]', + # parent dirs + r'(?:(?<=([/\\]|:))\.\.(?=[/\\]|$))|(?:^\.\.(?=[/\\]|$))', + )) + return re.sub(pattern, r'_', name) + + @classmethod + def _resolve_download_filename(cls, url, tmpdir): + """ + >>> import pathlib + >>> du = PackageIndex._resolve_download_filename + >>> root = getfixture('tmp_path') + >>> url = 'https://files.pythonhosted.org/packages/a9/5a/0db.../setuptools-78.1.0.tar.gz' + >>> str(pathlib.Path(du(url, root)).relative_to(root)) + 'setuptools-78.1.0.tar.gz' + """ + name, _fragment = egg_info_for_url(url) + name = cls._sanitize( + name + or + # default if URL has no path contents + '__downloaded__' + ) + + # strip any extra .zip before download + name = re.sub(r'\.egg\.zip$', '.egg', name) + + return os.path.join(tmpdir, name) + + def _download_url(self, url, tmpdir): + """ + Determine the download filename. + """ + filename = self._resolve_download_filename(url, tmpdir) + return self._download_vcs(url, filename) or self._download_other(url, filename) + + @staticmethod + def _resolve_vcs(url): + """ + >>> rvcs = PackageIndex._resolve_vcs + >>> rvcs('git+http://foo/bar') + 'git' + >>> rvcs('hg+https://foo/bar') + 'hg' + >>> rvcs('git:myhost') + 'git' + >>> rvcs('hg:myhost') + >>> rvcs('http://foo/bar') + """ + scheme = urllib.parse.urlsplit(url).scheme + pre, sep, _post = scheme.partition('+') + # svn and git have their own protocol; hg does not + allowed = set(['svn', 'git'] + ['hg'] * bool(sep)) + return next(iter({pre} & allowed), None) + + def _download_vcs(self, url, spec_filename): + vcs = self._resolve_vcs(url) + if not vcs: + return None + if vcs == 'svn': + raise DistutilsError( + f"Invalid config, SVN download is not supported: {url}" + ) + + filename, _, _ = spec_filename.partition('#') + url, rev = self._vcs_split_rev_from_url(url) + + self.info(f"Doing {vcs} clone from {url} to {filename}") + subprocess.check_call([vcs, 'clone', '--quiet', url, filename]) + + co_commands = dict( + git=[vcs, '-C', filename, 'checkout', '--quiet', rev], + hg=[vcs, '--cwd', filename, 'up', '-C', '-r', rev, '-q'], + ) + if rev is not None: + self.info(f"Checking out {rev}") + subprocess.check_call(co_commands[vcs]) + + return filename + + def _download_other(self, url, filename): + scheme = urllib.parse.urlsplit(url).scheme + if scheme == 'file': # pragma: no cover + return urllib.request.url2pathname(urllib.parse.urlparse(url).path) + # raise error if not allowed + self.url_ok(url, True) + return self._attempt_download(url, filename) + + def scan_url(self, url) -> None: + self.process_url(url, True) + + def _attempt_download(self, url, filename): + headers = self._download_to(url, filename) + if 'html' in headers.get('content-type', '').lower(): + return self._invalid_download_html(url, headers, filename) + else: + return filename + + def _invalid_download_html(self, url, headers, filename): + os.unlink(filename) + raise DistutilsError(f"Unexpected HTML page found at {url}") + + @staticmethod + def _vcs_split_rev_from_url(url): + """ + Given a possible VCS URL, return a clean URL and resolved revision if any. + + >>> vsrfu = PackageIndex._vcs_split_rev_from_url + >>> vsrfu('git+https://github.com/pypa/setuptools@v69.0.0#egg-info=setuptools') + ('https://github.com/pypa/setuptools', 'v69.0.0') + >>> vsrfu('git+https://github.com/pypa/setuptools#egg-info=setuptools') + ('https://github.com/pypa/setuptools', None) + >>> vsrfu('http://foo/bar') + ('http://foo/bar', None) + """ + parts = urllib.parse.urlsplit(url) + + clean_scheme = parts.scheme.split('+', 1)[-1] + + # Some fragment identification fails + no_fragment_path, _, _ = parts.path.partition('#') + + pre, sep, post = no_fragment_path.rpartition('@') + clean_path, rev = (pre, post) if sep else (post, None) + + resolved = parts._replace( + scheme=clean_scheme, + path=clean_path, + # discard the fragment + fragment='', + ).geturl() + + return resolved, rev + + def debug(self, msg, *args) -> None: + log.debug(msg, *args) + + def info(self, msg, *args) -> None: + log.info(msg, *args) + + def warn(self, msg, *args) -> None: + log.warn(msg, *args) + + +# This pattern matches a character entity reference (a decimal numeric +# references, a hexadecimal numeric reference, or a named reference). +entity_sub = re.compile(r'&(#(\d+|x[\da-fA-F]+)|[\w.:-]+);?').sub + + +def decode_entity(match): + what = match.group(0) + return html.unescape(what) + + +def htmldecode(text): + """ + Decode HTML entities in the given text. + + >>> htmldecode( + ... 'https://../package_name-0.1.2.tar.gz' + ... '?tokena=A&tokenb=B">package_name-0.1.2.tar.gz') + 'https://../package_name-0.1.2.tar.gz?tokena=A&tokenb=B">package_name-0.1.2.tar.gz' + """ + return entity_sub(decode_entity, text) + + +def socket_timeout(timeout=15): + def _socket_timeout(func): + def _socket_timeout(*args, **kwargs): + old_timeout = socket.getdefaulttimeout() + socket.setdefaulttimeout(timeout) + try: + return func(*args, **kwargs) + finally: + socket.setdefaulttimeout(old_timeout) + + return _socket_timeout + + return _socket_timeout + + +def _encode_auth(auth): + """ + Encode auth from a URL suitable for an HTTP header. + >>> str(_encode_auth('username%3Apassword')) + 'dXNlcm5hbWU6cGFzc3dvcmQ=' + + Long auth strings should not cause a newline to be inserted. + >>> long_auth = 'username:' + 'password'*10 + >>> chr(10) in str(_encode_auth(long_auth)) + False + """ + auth_s = urllib.parse.unquote(auth) + # convert to bytes + auth_bytes = auth_s.encode() + encoded_bytes = base64.b64encode(auth_bytes) + # convert back to a string + encoded = encoded_bytes.decode() + # strip the trailing carriage return + return encoded.replace('\n', '') + + +class Credential(NamedTuple): + """ + A username/password pair. + + Displayed separated by `:`. + >>> str(Credential('username', 'password')) + 'username:password' + """ + + username: str + password: str + + def __str__(self) -> str: + return f'{self.username}:{self.password}' + + +class PyPIConfig(configparser.RawConfigParser): + def __init__(self): + """ + Load from ~/.pypirc + """ + defaults = dict.fromkeys(['username', 'password', 'repository'], '') + super().__init__(defaults) + + rc = os.path.join(os.path.expanduser('~'), '.pypirc') + if os.path.exists(rc): + _cfg_read_utf8_with_fallback(self, rc) + + @property + def creds_by_repository(self): + sections_with_repositories = [ + section + for section in self.sections() + if self.get(section, 'repository').strip() + ] + + return dict(map(self._get_repo_cred, sections_with_repositories)) + + def _get_repo_cred(self, section): + repo = self.get(section, 'repository').strip() + return repo, Credential( + self.get(section, 'username').strip(), + self.get(section, 'password').strip(), + ) + + def find_credential(self, url): + """ + If the URL indicated appears to be a repository defined in this + config, return the credential for that repository. + """ + for repository, cred in self.creds_by_repository.items(): + if url.startswith(repository): + return cred + return None + + +def open_with_auth(url, opener=urllib.request.urlopen): + """Open a urllib2 request, handling HTTP authentication""" + + parsed = urllib.parse.urlparse(url) + scheme, netloc, path, params, query, frag = parsed + + # Double scheme does not raise on macOS as revealed by a + # failing test. We would expect "nonnumeric port". Refs #20. + if netloc.endswith(':'): + raise http.client.InvalidURL("nonnumeric port: ''") + + if scheme in ('http', 'https'): + auth, address = _splituser(netloc) + else: + auth, address = (None, None) + + if not auth: + cred = PyPIConfig().find_credential(url) + if cred: + auth = str(cred) + info = cred.username, url + log.info('Authenticating as %s for %s (from .pypirc)', *info) + + if auth: + auth = "Basic " + _encode_auth(auth) + parts = scheme, address, path, params, query, frag + new_url = urllib.parse.urlunparse(parts) + request = urllib.request.Request(new_url) + request.add_header("Authorization", auth) + else: + request = urllib.request.Request(url) + + request.add_header('User-Agent', user_agent) + fp = opener(request) + + if auth: + # Put authentication info back into request URL if same host, + # so that links found on the page will work + s2, h2, path2, param2, query2, frag2 = urllib.parse.urlparse(fp.url) + if s2 == scheme and h2 == address: + parts = s2, netloc, path2, param2, query2, frag2 + fp.url = urllib.parse.urlunparse(parts) + + return fp + + +# copy of urllib.parse._splituser from Python 3.8 +# See https://github.com/python/cpython/issues/80072. +def _splituser(host): + """splituser('user[:passwd]@host[:port]') + --> 'user[:passwd]', 'host[:port]'.""" + user, delim, host = host.rpartition('@') + return (user if delim else None), host + + +# adding a timeout to avoid freezing package_index +open_with_auth = socket_timeout(_SOCKET_TIMEOUT)(open_with_auth) + + +def fix_sf_url(url): + return url # backward compatibility + + +def local_open(url): + """Read a local path, with special support for directories""" + _scheme, _server, path, _param, _query, _frag = urllib.parse.urlparse(url) + filename = urllib.request.url2pathname(path) + if os.path.isfile(filename): + return urllib.request.urlopen(url) + elif path.endswith('/') and os.path.isdir(filename): + files = [] + for f in os.listdir(filename): + filepath = os.path.join(filename, f) + if f == 'index.html': + body = _read_utf8_with_fallback(filepath) + break + elif os.path.isdir(filepath): + f += '/' + files.append(f'{f}') + else: + tmpl = "{url}{files}" + body = tmpl.format(url=url, files='\n'.join(files)) + status, message = 200, "OK" + else: + status, message, body = 404, "Path not found", "Not found" + + headers = {'content-type': 'text/html'} + body_stream = io.StringIO(body) + return urllib.error.HTTPError(url, status, message, headers, body_stream) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/sandbox.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/sandbox.py new file mode 100644 index 0000000000000000000000000000000000000000..2d84242d667c7df6a20aa56eabce6ac34ddc4a7e --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/sandbox.py @@ -0,0 +1,536 @@ +from __future__ import annotations + +import builtins +import contextlib +import functools +import itertools +import operator +import os +import pickle +import re +import sys +import tempfile +import textwrap +from types import TracebackType +from typing import TYPE_CHECKING, Any, ClassVar + +import pkg_resources +from pkg_resources import working_set + +from distutils.errors import DistutilsError + +if TYPE_CHECKING: + import os as _os +elif sys.platform.startswith('java'): + import org.python.modules.posix.PosixModule as _os # pyright: ignore[reportMissingImports] +else: + _os = sys.modules[os.name] +_open = open + + +if TYPE_CHECKING: + from typing_extensions import Self + +__all__ = [ + "AbstractSandbox", + "DirectorySandbox", + "SandboxViolation", + "run_setup", +] + + +def _execfile(filename, globals, locals=None): + """ + Python 3 implementation of execfile. + """ + mode = 'rb' + with open(filename, mode) as stream: + script = stream.read() + if locals is None: + locals = globals + code = compile(script, filename, 'exec') + exec(code, globals, locals) + + +@contextlib.contextmanager +def save_argv(repl=None): + saved = sys.argv[:] + if repl is not None: + sys.argv[:] = repl + try: + yield saved + finally: + sys.argv[:] = saved + + +@contextlib.contextmanager +def save_path(): + saved = sys.path[:] + try: + yield saved + finally: + sys.path[:] = saved + + +@contextlib.contextmanager +def override_temp(replacement): + """ + Monkey-patch tempfile.tempdir with replacement, ensuring it exists + """ + os.makedirs(replacement, exist_ok=True) + + saved = tempfile.tempdir + + tempfile.tempdir = replacement + + try: + yield + finally: + tempfile.tempdir = saved + + +@contextlib.contextmanager +def pushd(target): + saved = os.getcwd() + os.chdir(target) + try: + yield saved + finally: + os.chdir(saved) + + +class UnpickleableException(Exception): + """ + An exception representing another Exception that could not be pickled. + """ + + @staticmethod + def dump(type, exc): + """ + Always return a dumped (pickled) type and exc. If exc can't be pickled, + wrap it in UnpickleableException first. + """ + try: + return pickle.dumps(type), pickle.dumps(exc) + except Exception: + # get UnpickleableException inside the sandbox + from setuptools.sandbox import UnpickleableException as cls + + return cls.dump(cls, cls(repr(exc))) + + +class ExceptionSaver: + """ + A Context Manager that will save an exception, serialize, and restore it + later. + """ + + def __enter__(self) -> Self: + return self + + def __exit__( + self, + type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> bool: + if not exc: + return False + + # dump the exception + self._saved = UnpickleableException.dump(type, exc) + self._tb = tb + + # suppress the exception + return True + + def resume(self): + "restore and re-raise any exception" + + if '_saved' not in vars(self): + return + + _type, exc = map(pickle.loads, self._saved) + raise exc.with_traceback(self._tb) + + +@contextlib.contextmanager +def save_modules(): + """ + Context in which imported modules are saved. + + Translates exceptions internal to the context into the equivalent exception + outside the context. + """ + saved = sys.modules.copy() + with ExceptionSaver() as saved_exc: + yield saved + + sys.modules.update(saved) + # remove any modules imported since + del_modules = ( + mod_name + for mod_name in sys.modules + if mod_name not in saved + # exclude any encodings modules. See #285 + and not mod_name.startswith('encodings.') + ) + _clear_modules(del_modules) + + saved_exc.resume() + + +def _clear_modules(module_names): + for mod_name in list(module_names): + del sys.modules[mod_name] + + +@contextlib.contextmanager +def save_pkg_resources_state(): + saved = pkg_resources.__getstate__() + try: + yield saved + finally: + pkg_resources.__setstate__(saved) + + +@contextlib.contextmanager +def setup_context(setup_dir): + temp_dir = os.path.join(setup_dir, 'temp') + with save_pkg_resources_state(): + with save_modules(): + with save_path(): + hide_setuptools() + with save_argv(): + with override_temp(temp_dir): + with pushd(setup_dir): + # ensure setuptools commands are available + __import__('setuptools') + yield + + +_MODULES_TO_HIDE = { + 'setuptools', + 'distutils', + 'pkg_resources', + 'Cython', + '_distutils_hack', +} + + +def _needs_hiding(mod_name): + """ + >>> _needs_hiding('setuptools') + True + >>> _needs_hiding('pkg_resources') + True + >>> _needs_hiding('setuptools_plugin') + False + >>> _needs_hiding('setuptools.__init__') + True + >>> _needs_hiding('distutils') + True + >>> _needs_hiding('os') + False + >>> _needs_hiding('Cython') + True + """ + base_module = mod_name.split('.', 1)[0] + return base_module in _MODULES_TO_HIDE + + +def hide_setuptools(): + """ + Remove references to setuptools' modules from sys.modules to allow the + invocation to import the most appropriate setuptools. This technique is + necessary to avoid issues such as #315 where setuptools upgrading itself + would fail to find a function declared in the metadata. + """ + _distutils_hack = sys.modules.get('_distutils_hack', None) + if _distutils_hack is not None: + _distutils_hack._remove_shim() + + modules = filter(_needs_hiding, sys.modules) + _clear_modules(modules) + + +def run_setup(setup_script, args): + """Run a distutils setup script, sandboxed in its directory""" + setup_dir = os.path.abspath(os.path.dirname(setup_script)) + with setup_context(setup_dir): + try: + sys.argv[:] = [setup_script] + list(args) + sys.path.insert(0, setup_dir) + # reset to include setup dir, w/clean callback list + working_set.__init__() + working_set.callbacks.append(lambda dist: dist.activate()) + + with DirectorySandbox(setup_dir): + ns = dict(__file__=setup_script, __name__='__main__') + _execfile(setup_script, ns) + except SystemExit as v: + if v.args and v.args[0]: + raise + # Normal exit, just return + + +class AbstractSandbox: + """Wrap 'os' module and 'open()' builtin for virtualizing setup scripts""" + + _active = False + + def __init__(self) -> None: + self._attrs = [ + name + for name in dir(_os) + if not name.startswith('_') and hasattr(self, name) + ] + + def _copy(self, source): + for name in self._attrs: + setattr(os, name, getattr(source, name)) + + def __enter__(self) -> None: + self._copy(self) + builtins.open = self._open + self._active = True + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ): + self._active = False + builtins.open = _open + self._copy(_os) + + def run(self, func): + """Run 'func' under os sandboxing""" + with self: + return func() + + def _mk_dual_path_wrapper(name: str): # type: ignore[misc] # https://github.com/pypa/setuptools/pull/4099 + original = getattr(_os, name) + + def wrap(self, src, dst, *args, **kw): + if self._active: + src, dst = self._remap_pair(name, src, dst, *args, **kw) + return original(src, dst, *args, **kw) + + return wrap + + for __name in ["rename", "link", "symlink"]: + if hasattr(_os, __name): + locals()[__name] = _mk_dual_path_wrapper(__name) + + def _mk_single_path_wrapper(name: str, original=None): # type: ignore[misc] # https://github.com/pypa/setuptools/pull/4099 + original = original or getattr(_os, name) + + def wrap(self, path, *args, **kw): + if self._active: + path = self._remap_input(name, path, *args, **kw) + return original(path, *args, **kw) + + return wrap + + _open = _mk_single_path_wrapper('open', _open) + for __name in [ + "stat", + "listdir", + "chdir", + "open", + "chmod", + "chown", + "mkdir", + "remove", + "unlink", + "rmdir", + "utime", + "lchown", + "chroot", + "lstat", + "startfile", + "mkfifo", + "mknod", + "pathconf", + "access", + ]: + if hasattr(_os, __name): + locals()[__name] = _mk_single_path_wrapper(__name) + + def _mk_single_with_return(name: str): # type: ignore[misc] # https://github.com/pypa/setuptools/pull/4099 + original = getattr(_os, name) + + def wrap(self, path, *args, **kw): + if self._active: + path = self._remap_input(name, path, *args, **kw) + return self._remap_output(name, original(path, *args, **kw)) + return original(path, *args, **kw) + + return wrap + + for __name in ['readlink', 'tempnam']: + if hasattr(_os, __name): + locals()[__name] = _mk_single_with_return(__name) + + def _mk_query(name: str): # type: ignore[misc] # https://github.com/pypa/setuptools/pull/4099 + original = getattr(_os, name) + + def wrap(self, *args, **kw): + retval = original(*args, **kw) + if self._active: + return self._remap_output(name, retval) + return retval + + return wrap + + for __name in ['getcwd', 'tmpnam']: + if hasattr(_os, __name): + locals()[__name] = _mk_query(__name) + + def _validate_path(self, path): + """Called to remap or validate any path, whether input or output""" + return path + + def _remap_input(self, operation, path, *args, **kw): + """Called for path inputs""" + return self._validate_path(path) + + def _remap_output(self, operation, path): + """Called for path outputs""" + return self._validate_path(path) + + def _remap_pair(self, operation, src, dst, *args, **kw): + """Called for path pairs like rename, link, and symlink operations""" + return ( + self._remap_input(operation + '-from', src, *args, **kw), + self._remap_input(operation + '-to', dst, *args, **kw), + ) + + if TYPE_CHECKING: + # This is a catch-all for all the dynamically created attributes. + # This isn't public API anyway + def __getattribute__(self, name: str) -> Any: ... + + +if hasattr(os, 'devnull'): + _EXCEPTIONS = [os.devnull] +else: + _EXCEPTIONS = [] + + +class DirectorySandbox(AbstractSandbox): + """Restrict operations to a single subdirectory - pseudo-chroot""" + + write_ops: ClassVar[dict[str, None]] = dict.fromkeys([ + "open", + "chmod", + "chown", + "mkdir", + "remove", + "unlink", + "rmdir", + "utime", + "lchown", + "chroot", + "mkfifo", + "mknod", + "tempnam", + ]) + + _exception_patterns: list[str | re.Pattern] = [] + "exempt writing to paths that match the pattern" + + def __init__(self, sandbox, exceptions=_EXCEPTIONS) -> None: + self._sandbox = os.path.normcase(os.path.realpath(sandbox)) + self._prefix = os.path.join(self._sandbox, '') + self._exceptions = [ + os.path.normcase(os.path.realpath(path)) for path in exceptions + ] + AbstractSandbox.__init__(self) + + def _violation(self, operation, *args, **kw): + from setuptools.sandbox import SandboxViolation + + raise SandboxViolation(operation, args, kw) + + def _open(self, path, mode='r', *args, **kw): + if mode not in ('r', 'rt', 'rb', 'rU', 'U') and not self._ok(path): + self._violation("open", path, mode, *args, **kw) + return _open(path, mode, *args, **kw) + + def tmpnam(self) -> None: + self._violation("tmpnam") + + def _ok(self, path): + active = self._active + try: + self._active = False + realpath = os.path.normcase(os.path.realpath(path)) + return ( + self._exempted(realpath) + or realpath == self._sandbox + or realpath.startswith(self._prefix) + ) + finally: + self._active = active + + def _exempted(self, filepath): + start_matches = ( + filepath.startswith(exception) for exception in self._exceptions + ) + pattern_matches = ( + re.match(pattern, filepath) for pattern in self._exception_patterns + ) + candidates = itertools.chain(start_matches, pattern_matches) + return any(candidates) + + def _remap_input(self, operation, path, *args, **kw): + """Called for path inputs""" + if operation in self.write_ops and not self._ok(path): + self._violation(operation, os.path.realpath(path), *args, **kw) + return path + + def _remap_pair(self, operation, src, dst, *args, **kw): + """Called for path pairs like rename, link, and symlink operations""" + if not self._ok(src) or not self._ok(dst): + self._violation(operation, src, dst, *args, **kw) + return (src, dst) + + def open(self, file, flags, mode: int = 0o777, *args, **kw) -> int: + """Called for low-level os.open()""" + if flags & WRITE_FLAGS and not self._ok(file): + self._violation("os.open", file, flags, mode, *args, **kw) + return _os.open(file, flags, mode, *args, **kw) + + +WRITE_FLAGS = functools.reduce( + operator.or_, + [ + getattr(_os, a, 0) + for a in "O_WRONLY O_RDWR O_APPEND O_CREAT O_TRUNC O_TEMPORARY".split() + ], +) + + +class SandboxViolation(DistutilsError): + """A setup script attempted to modify the filesystem outside the sandbox""" + + tmpl = textwrap.dedent( + """ + SandboxViolation: {cmd}{args!r} {kwargs} + + The package setup script has attempted to modify files on your system + that are not within the EasyInstall build area, and has been aborted. + + This package cannot be safely installed by EasyInstall, and may not + support alternate installation locations even if you run its setup + script by hand. Please inform the package's author and the EasyInstall + maintainers to find out if a fix or workaround is available. + """ + ).lstrip() + + def __str__(self) -> str: + cmd, args, kwargs = self.args + return self.tmpl.format(**locals()) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/script (dev).tmpl b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/script (dev).tmpl new file mode 100644 index 0000000000000000000000000000000000000000..39a24b04888e79df51e2237577b303a2f901be63 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/script (dev).tmpl @@ -0,0 +1,6 @@ +# EASY-INSTALL-DEV-SCRIPT: %(spec)r,%(script_name)r +__requires__ = %(spec)r +__import__('pkg_resources').require(%(spec)r) +__file__ = %(dev_path)r +with open(__file__) as f: + exec(compile(f.read(), __file__, 'exec')) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/script.tmpl b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/script.tmpl new file mode 100644 index 0000000000000000000000000000000000000000..ff5efbcab3b58063dd84787181c26a95fb663d94 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/script.tmpl @@ -0,0 +1,3 @@ +# EASY-INSTALL-SCRIPT: %(spec)r,%(script_name)r +__requires__ = %(spec)r +__import__('pkg_resources').run_script(%(spec)r, %(script_name)r) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/unicode_utils.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/unicode_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f502f5b089619eafd28e2c7a61967e34e16920e5 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/unicode_utils.py @@ -0,0 +1,102 @@ +import sys +import unicodedata +from configparser import RawConfigParser + +from .compat import py39 +from .warnings import SetuptoolsDeprecationWarning + + +# HFS Plus uses decomposed UTF-8 +def decompose(path): + if isinstance(path, str): + return unicodedata.normalize('NFD', path) + try: + path = path.decode('utf-8') + path = unicodedata.normalize('NFD', path) + path = path.encode('utf-8') + except UnicodeError: + pass # Not UTF-8 + return path + + +def filesys_decode(path): + """ + Ensure that the given path is decoded, + ``None`` when no expected encoding works + """ + + if isinstance(path, str): + return path + + fs_enc = sys.getfilesystemencoding() or 'utf-8' + candidates = fs_enc, 'utf-8' + + for enc in candidates: + try: + return path.decode(enc) + except UnicodeDecodeError: + continue + + return None + + +def try_encode(string, enc): + "turn unicode encoding into a functional routine" + try: + return string.encode(enc) + except UnicodeEncodeError: + return None + + +def _read_utf8_with_fallback(file: str, fallback_encoding=py39.LOCALE_ENCODING) -> str: + """ + First try to read the file with UTF-8, if there is an error fallback to a + different encoding ("locale" by default). Returns the content of the file. + Also useful when reading files that might have been produced by an older version of + setuptools. + """ + try: + with open(file, "r", encoding="utf-8") as f: + return f.read() + except UnicodeDecodeError: # pragma: no cover + _Utf8EncodingNeeded.emit(file=file, fallback_encoding=fallback_encoding) + with open(file, "r", encoding=fallback_encoding) as f: + return f.read() + + +def _cfg_read_utf8_with_fallback( + cfg: RawConfigParser, file: str, fallback_encoding=py39.LOCALE_ENCODING +) -> None: + """Same idea as :func:`_read_utf8_with_fallback`, but for the + :meth:`RawConfigParser.read` method. + + This method may call ``cfg.clear()``. + """ + try: + cfg.read(file, encoding="utf-8") + except UnicodeDecodeError: # pragma: no cover + _Utf8EncodingNeeded.emit(file=file, fallback_encoding=fallback_encoding) + cfg.clear() + cfg.read(file, encoding=fallback_encoding) + + +class _Utf8EncodingNeeded(SetuptoolsDeprecationWarning): + _SUMMARY = """ + `encoding="utf-8"` fails with {file!r}, trying `encoding={fallback_encoding!r}`. + """ + + _DETAILS = """ + Fallback behavior for UTF-8 is considered **deprecated** and future versions of + `setuptools` may not implement it. + + Please encode {file!r} with "utf-8" to ensure future builds will succeed. + + If this file was produced by `setuptools` itself, cleaning up the cached files + and re-building/re-installing the package with a newer version of `setuptools` + (e.g. by updating `build-system.requires` in its `pyproject.toml`) + might solve the problem. + """ + # TODO: Add a deadline? + # Will we be able to remove this? + # The question comes to mind mainly because of sdists that have been produced + # by old versions of setuptools and published to PyPI... diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/version.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/version.py new file mode 100644 index 0000000000000000000000000000000000000000..ec253c414474677d3a5977511cfe901bfb786740 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/version.py @@ -0,0 +1,6 @@ +from ._importlib import metadata + +try: + __version__ = metadata.version('setuptools') or '0.dev0+unknown' +except Exception: + __version__ = '0.dev0+unknown' diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/warnings.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/warnings.py new file mode 100644 index 0000000000000000000000000000000000000000..96467787c237846bfbacf2d44eb833be0a88b633 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/warnings.py @@ -0,0 +1,110 @@ +"""Provide basic warnings used by setuptools modules. + +Using custom classes (other than ``UserWarning``) allow users to set +``PYTHONWARNINGS`` filters to run tests and prepare for upcoming changes in +setuptools. +""" + +from __future__ import annotations + +import os +import warnings +from datetime import date +from inspect import cleandoc +from textwrap import indent +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from typing_extensions import TypeAlias + +_DueDate: TypeAlias = tuple[int, int, int] # time tuple +_INDENT = 8 * " " +_TEMPLATE = f"""{80 * '*'}\n{{details}}\n{80 * '*'}""" + + +class SetuptoolsWarning(UserWarning): + """Base class in ``setuptools`` warning hierarchy.""" + + @classmethod + def emit( + cls, + summary: str | None = None, + details: str | None = None, + due_date: _DueDate | None = None, + see_docs: str | None = None, + see_url: str | None = None, + stacklevel: int = 2, + **kwargs, + ) -> None: + """Private: reserved for ``setuptools`` internal use only""" + # Default values: + summary_ = summary or getattr(cls, "_SUMMARY", None) or "" + details_ = details or getattr(cls, "_DETAILS", None) or "" + due_date = due_date or getattr(cls, "_DUE_DATE", None) + docs_ref = see_docs or getattr(cls, "_SEE_DOCS", None) + docs_url = docs_ref and f"https://setuptools.pypa.io/en/latest/{docs_ref}" + see_url = see_url or getattr(cls, "_SEE_URL", None) + due = date(*due_date) if due_date else None + + text = cls._format(summary_, details_, due, see_url or docs_url, kwargs) + if due and due < date.today() and _should_enforce(): + raise cls(text) + warnings.warn(text, cls, stacklevel=stacklevel + 1) + + @classmethod + def _format( + cls, + summary: str, + details: str, + due_date: date | None = None, + see_url: str | None = None, + format_args: dict | None = None, + ) -> str: + """Private: reserved for ``setuptools`` internal use only""" + today = date.today() + summary = cleandoc(summary).format_map(format_args or {}) + possible_parts = [ + cleandoc(details).format_map(format_args or {}), + ( + f"\nBy {due_date:%Y-%b-%d}, you need to update your project and remove " + "deprecated calls\nor your builds will no longer be supported." + if due_date and due_date > today + else None + ), + ( + "\nThis deprecation is overdue, please update your project and remove " + "deprecated\ncalls to avoid build errors in the future." + if due_date and due_date < today + else None + ), + (f"\nSee {see_url} for details." if see_url else None), + ] + parts = [x for x in possible_parts if x] + if parts: + body = indent(_TEMPLATE.format(details="\n".join(parts)), _INDENT) + return "\n".join([summary, "!!\n", body, "\n!!"]) + return summary + + +class InformationOnly(SetuptoolsWarning): + """Currently there is no clear way of displaying messages to the users + that use the setuptools backend directly via ``pip``. + The only thing that might work is a warning, although it is not the + most appropriate tool for the job... + + See pypa/packaging-problems#558. + """ + + +class SetuptoolsDeprecationWarning(SetuptoolsWarning): + """ + Base class for warning deprecations in ``setuptools`` + + This class is not derived from ``DeprecationWarning``, and as such is + visible by default. + """ + + +def _should_enforce(): + enforce = os.getenv("SETUPTOOLS_ENFORCE_DEPRECATION", "false").lower() + return enforce in ("true", "on", "ok", "1") diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/wheel.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/wheel.py new file mode 100644 index 0000000000000000000000000000000000000000..c7ca43b5cfb2aff8d6983bbba4b7e6fdc9d01f83 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/wheel.py @@ -0,0 +1,236 @@ +"""Wheels support.""" + +import contextlib +import email +import functools +import itertools +import os +import posixpath +import re +import zipfile + +from packaging.tags import sys_tags +from packaging.utils import canonicalize_name +from packaging.version import Version as parse_version + +import setuptools +from setuptools.archive_util import _unpack_zipfile_obj +from setuptools.command.egg_info import _egg_basename, write_requirements + +from .unicode_utils import _read_utf8_with_fallback + +from distutils.util import get_platform + +WHEEL_NAME = re.compile( + r"""^(?P.+?)-(?P\d.*?) + ((-(?P\d.*?))?-(?P.+?)-(?P.+?)-(?P.+?) + )\.whl$""", + re.VERBOSE, +).match + +NAMESPACE_PACKAGE_INIT = "__import__('pkg_resources').declare_namespace(__name__)\n" + + +@functools.cache +def _get_supported_tags(): + # We calculate the supported tags only once, otherwise calling + # this method on thousands of wheels takes seconds instead of + # milliseconds. + return {(t.interpreter, t.abi, t.platform) for t in sys_tags()} + + +def unpack(src_dir, dst_dir) -> None: + """Move everything under `src_dir` to `dst_dir`, and delete the former.""" + for dirpath, dirnames, filenames in os.walk(src_dir): + subdir = os.path.relpath(dirpath, src_dir) + for f in filenames: + src = os.path.join(dirpath, f) + dst = os.path.join(dst_dir, subdir, f) + os.renames(src, dst) + for n, d in reversed(list(enumerate(dirnames))): + src = os.path.join(dirpath, d) + dst = os.path.join(dst_dir, subdir, d) + if not os.path.exists(dst): + # Directory does not exist in destination, + # rename it and prune it from os.walk list. + os.renames(src, dst) + del dirnames[n] + # Cleanup. + for dirpath, dirnames, filenames in os.walk(src_dir, topdown=True): + assert not filenames + os.rmdir(dirpath) + + +@contextlib.contextmanager +def disable_info_traces(): + """ + Temporarily disable info traces. + """ + from distutils import log + + saved = log.set_threshold(log.WARN) + try: + yield + finally: + log.set_threshold(saved) + + +class Wheel: + def __init__(self, filename) -> None: + match = WHEEL_NAME(os.path.basename(filename)) + if match is None: + raise ValueError(f'invalid wheel name: {filename!r}') + self.filename = filename + for k, v in match.groupdict().items(): + setattr(self, k, v) + + def tags(self): + """List tags (py_version, abi, platform) supported by this wheel.""" + return itertools.product( + self.py_version.split('.'), + self.abi.split('.'), + self.platform.split('.'), + ) + + def is_compatible(self): + """Is the wheel compatible with the current platform?""" + return next((True for t in self.tags() if t in _get_supported_tags()), False) + + def egg_name(self): + return ( + _egg_basename( + self.project_name, + self.version, + platform=(None if self.platform == 'any' else get_platform()), + ) + + ".egg" + ) + + def get_dist_info(self, zf): + # find the correct name of the .dist-info dir in the wheel file + for member in zf.namelist(): + dirname = posixpath.dirname(member) + if dirname.endswith('.dist-info') and canonicalize_name(dirname).startswith( + canonicalize_name(self.project_name) + ): + return dirname + raise ValueError("unsupported wheel format. .dist-info not found") + + def install_as_egg(self, destination_eggdir) -> None: + """Install wheel as an egg directory.""" + with zipfile.ZipFile(self.filename) as zf: + self._install_as_egg(destination_eggdir, zf) + + def _install_as_egg(self, destination_eggdir, zf): + dist_basename = f'{self.project_name}-{self.version}' + dist_info = self.get_dist_info(zf) + dist_data = f'{dist_basename}.data' + egg_info = os.path.join(destination_eggdir, 'EGG-INFO') + + self._convert_metadata(zf, destination_eggdir, dist_info, egg_info) + self._move_data_entries(destination_eggdir, dist_data) + self._fix_namespace_packages(egg_info, destination_eggdir) + + @staticmethod + def _convert_metadata(zf, destination_eggdir, dist_info, egg_info): + import pkg_resources + + def get_metadata(name): + with zf.open(posixpath.join(dist_info, name)) as fp: + value = fp.read().decode('utf-8') + return email.parser.Parser().parsestr(value) + + wheel_metadata = get_metadata('WHEEL') + # Check wheel format version is supported. + wheel_version = parse_version(wheel_metadata.get('Wheel-Version')) + wheel_v1 = parse_version('1.0') <= wheel_version < parse_version('2.0dev0') + if not wheel_v1: + raise ValueError(f'unsupported wheel format version: {wheel_version}') + # Extract to target directory. + _unpack_zipfile_obj(zf, destination_eggdir) + # Convert metadata. + dist_info = os.path.join(destination_eggdir, dist_info) + dist = pkg_resources.Distribution.from_location( + destination_eggdir, + dist_info, + metadata=pkg_resources.PathMetadata(destination_eggdir, dist_info), + ) + + # Note: Evaluate and strip markers now, + # as it's difficult to convert back from the syntax: + # foobar; "linux" in sys_platform and extra == 'test' + def raw_req(req): + req.marker = None + return str(req) + + install_requires = list(map(raw_req, dist.requires())) + extras_require = { + extra: [ + req + for req in map(raw_req, dist.requires((extra,))) + if req not in install_requires + ] + for extra in dist.extras + } + os.rename(dist_info, egg_info) + os.rename( + os.path.join(egg_info, 'METADATA'), + os.path.join(egg_info, 'PKG-INFO'), + ) + setup_dist = setuptools.Distribution( + attrs=dict( + install_requires=install_requires, + extras_require=extras_require, + ), + ) + with disable_info_traces(): + write_requirements( + setup_dist.get_command_obj('egg_info'), + None, + os.path.join(egg_info, 'requires.txt'), + ) + + @staticmethod + def _move_data_entries(destination_eggdir, dist_data): + """Move data entries to their correct location.""" + dist_data = os.path.join(destination_eggdir, dist_data) + dist_data_scripts = os.path.join(dist_data, 'scripts') + if os.path.exists(dist_data_scripts): + egg_info_scripts = os.path.join(destination_eggdir, 'EGG-INFO', 'scripts') + os.mkdir(egg_info_scripts) + for entry in os.listdir(dist_data_scripts): + # Remove bytecode, as it's not properly handled + # during easy_install scripts install phase. + if entry.endswith('.pyc'): + os.unlink(os.path.join(dist_data_scripts, entry)) + else: + os.rename( + os.path.join(dist_data_scripts, entry), + os.path.join(egg_info_scripts, entry), + ) + os.rmdir(dist_data_scripts) + for subdir in filter( + os.path.exists, + ( + os.path.join(dist_data, d) + for d in ('data', 'headers', 'purelib', 'platlib') + ), + ): + unpack(subdir, destination_eggdir) + if os.path.exists(dist_data): + os.rmdir(dist_data) + + @staticmethod + def _fix_namespace_packages(egg_info, destination_eggdir): + namespace_packages = os.path.join(egg_info, 'namespace_packages.txt') + if os.path.exists(namespace_packages): + namespace_packages = _read_utf8_with_fallback(namespace_packages).split() + + for mod in namespace_packages: + mod_dir = os.path.join(destination_eggdir, *mod.split('.')) + mod_init = os.path.join(mod_dir, '__init__.py') + if not os.path.exists(mod_dir): + os.mkdir(mod_dir) + if not os.path.exists(mod_init): + with open(mod_init, 'w', encoding="utf-8") as fp: + fp.write(NAMESPACE_PACKAGE_INIT) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/windows_support.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/windows_support.py new file mode 100644 index 0000000000000000000000000000000000000000..7a2b53a291409c66851961a559eb4d69be0f4acc --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/setuptools/windows_support.py @@ -0,0 +1,30 @@ +import platform + + +def windows_only(func): + if platform.system() != 'Windows': + return lambda *args, **kwargs: None + return func + + +@windows_only +def hide_file(path: str) -> None: + """ + Set the hidden attribute on a file or directory. + + From https://stackoverflow.com/questions/19622133/ + + `path` must be text. + """ + import ctypes + import ctypes.wintypes + + SetFileAttributes = ctypes.windll.kernel32.SetFileAttributesW + SetFileAttributes.argtypes = ctypes.wintypes.LPWSTR, ctypes.wintypes.DWORD + SetFileAttributes.restype = ctypes.wintypes.BOOL + + FILE_ATTRIBUTE_HIDDEN = 0x02 + + ret = SetFileAttributes(path, FILE_ATTRIBUTE_HIDDEN) + if not ret: + raise ctypes.WinError() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/smmap-5.0.3.dist-info/INSTALLER b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/smmap-5.0.3.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/smmap-5.0.3.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/smmap-5.0.3.dist-info/METADATA b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/smmap-5.0.3.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..8d4be036e7c2635a4e32b003a7b4966825c6b072 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/smmap-5.0.3.dist-info/METADATA @@ -0,0 +1,125 @@ +Metadata-Version: 2.4 +Name: smmap +Version: 5.0.3 +Summary: A pure Python implementation of a sliding window memory map manager +Home-page: https://github.com/gitpython-developers/smmap +Author: Sebastian Thiel +Author-email: byronimo@gmail.com +License: BSD-3-Clause +Platform: any +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Console +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: Operating System :: OS Independent +Classifier: Operating System :: POSIX +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: MacOS :: MacOS X +Classifier: Programming Language :: Python +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.13 +Classifier: Programming Language :: Python :: 3 :: Only +Requires-Python: >=3.7 +Description-Content-Type: text/markdown +License-File: LICENSE +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: description-content-type +Dynamic: home-page +Dynamic: license +Dynamic: license-file +Dynamic: platform +Dynamic: requires-python +Dynamic: summary + +## Motivation + +When reading from many possibly large files in a fashion similar to random access, it is usually the fastest and most efficient to use memory maps. + +Although memory maps have many advantages, they represent a very limited system resource as every map uses one file descriptor, whose amount is limited per process. On 32 bit systems, the amount of memory you can have mapped at a time is naturally limited to theoretical 4GB of memory, which may not be enough for some applications. + + +## Limitations + +* **System resources (file-handles) are likely to be leaked!** This is due to the library authors reliance on a deterministic `__del__()` destructor. +* The memory access is read-only by design. + + +## Overview + +![Python package](https://github.com/gitpython-developers/smmap/workflows/Python%20package/badge.svg) + +Smmap wraps an interface around mmap and tracks the mapped files as well as the amount of clients who use it. If the system runs out of resources, or if a memory limit is reached, it will automatically unload unused maps to allow continued operation. + +To allow processing large files even on 32 bit systems, it allows only portions of the file to be mapped. Once the user reads beyond the mapped region, smmap will automatically map the next required region, unloading unused regions using a LRU algorithm. + +Although the library can be used most efficiently with its native interface, a Buffer implementation is provided to hide these details behind a simple string-like interface. + +For performance critical 64 bit applications, a simplified version of memory mapping is provided which always maps the whole file, but still provides the benefit of unloading unused mappings on demand. + + + +## Prerequisites + +* Python 3.7+ +* OSX, Windows or Linux + +The package was tested on all of the previously mentioned configurations. + +## Installing smmap + +[![Documentation Status](https://readthedocs.org/projects/smmap/badge/?version=latest)](https://readthedocs.org/projects/smmap/?badge=latest) + +Its easiest to install smmap using the [pip](http://www.pip-installer.org/en/latest) program: + +```bash +$ pip install smmap +``` + +As the command will install smmap in your respective python distribution, you will most likely need root permissions to authorize the required changes. + +If you have downloaded the source archive, the package can be installed by running the `setup.py` script: + +```bash +$ python setup.py install +``` + +It is advised to have a look at the **Usage Guide** for a brief introduction on the different database implementations. + + + +## Homepage and Links + +The project is home on github at https://github.com/gitpython-developers/smmap . + +The latest source can be cloned from github as well: + +* git://github.com/gitpython-developers/smmap.git + + +For support, please use the git-python mailing list: + +* http://groups.google.com/group/git-python + + +Issues can be filed on github: + +* https://github.com/gitpython-developers/smmap/issues + +A link to the pypi page related to this repository: + +* https://pypi.org/project/smmap/ + + +## License Information + +*smmap* is licensed under the New BSD License. + diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/smmap-5.0.3.dist-info/RECORD b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/smmap-5.0.3.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..8375eb105ddb1d920abd135f2fa04b2994adcfb7 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/smmap-5.0.3.dist-info/RECORD @@ -0,0 +1,27 @@ +smmap-5.0.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +smmap-5.0.3.dist-info/METADATA,sha256=dh1i1428o477gPF7laWu9SJNgoiu35gMqZxFPblQR7k,4588 +smmap-5.0.3.dist-info/RECORD,, +smmap-5.0.3.dist-info/WHEEL,sha256=YCfwYGOYMi5Jhw2fU4yNgwErybb2IX5PEwBKV4ZbdBo,91 +smmap-5.0.3.dist-info/licenses/LICENSE,sha256=iOnZP3CNEQsyioNDAt0dXGr72lMOdyHRXYCzUR2G8jU,1519 +smmap-5.0.3.dist-info/top_level.txt,sha256=h0Tp1UdaROCy2bjWNha1MFpwgVghxEUQsaLHbZs96Gw,6 +smmap-5.0.3.dist-info/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1 +smmap/__init__.py,sha256=9xfDzQfkot54EJaz-fU1BAjsTOLOVXpSzszfL6LV4uU,343 +smmap/__pycache__/__init__.cpython-310.pyc,, +smmap/__pycache__/buf.cpython-310.pyc,, +smmap/__pycache__/mman.cpython-310.pyc,, +smmap/__pycache__/util.cpython-310.pyc,, +smmap/buf.py,sha256=wElndUNa4Njhnes6JYmI_Xp4zwaohirLdr7eVR9XYNU,5762 +smmap/mman.py,sha256=HYxohllZqpPY4KgRF_D_lNp4fx0akZ-NQosutLDrQ60,24022 +smmap/test/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +smmap/test/__pycache__/__init__.cpython-310.pyc,, +smmap/test/__pycache__/lib.cpython-310.pyc,, +smmap/test/__pycache__/test_buf.cpython-310.pyc,, +smmap/test/__pycache__/test_mman.cpython-310.pyc,, +smmap/test/__pycache__/test_tutorial.cpython-310.pyc,, +smmap/test/__pycache__/test_util.cpython-310.pyc,, +smmap/test/lib.py,sha256=jYIT4rKckHw2s7-l5lwysft1jqrwDFkjtyNLKNpu_j0,1489 +smmap/test/test_buf.py,sha256=BCg9FbusakiYNs5MUNoJSiyuTP5HcMYl65HzvpY9SNo,5439 +smmap/test/test_mman.py,sha256=o3cPg5idyYJpq32zXgDy1qtD10RA_e88-1zPYBWi4Ms,10822 +smmap/test/test_tutorial.py,sha256=ZwCphCbKAGYt_fn_CiOJ9lWwpWwpqE4-zBUp-v-t9eM,3174 +smmap/test/test_util.py,sha256=3hJyW9Km7k7XSgxxtDOkG8eVagk3lIzP4H2pR0S2ewg,3468 +smmap/util.py,sha256=_Sl3Sd2KWdd-5nmhUegFMfT6L1j5BGchRT4z53Sobug,7476 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/smmap-5.0.3.dist-info/WHEEL b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/smmap-5.0.3.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..1ef5583317a5e59140e3f1c85c2db91aec0961e8 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/smmap-5.0.3.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (82.0.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/smmap-5.0.3.dist-info/top_level.txt b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/smmap-5.0.3.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..2765cefa1c4976ec31a903f3ffb7b2f9f92531f3 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/smmap-5.0.3.dist-info/top_level.txt @@ -0,0 +1 @@ +smmap diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/smmap-5.0.3.dist-info/zip-safe b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/smmap-5.0.3.dist-info/zip-safe new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/smmap-5.0.3.dist-info/zip-safe @@ -0,0 +1 @@ + diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/smmap/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/smmap/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..623181034acb05e7c9168ded256bf549d98c1efa --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/smmap/__init__.py @@ -0,0 +1,11 @@ +"""Initialize the smmap package""" + +__author__ = "Sebastian Thiel" +__contact__ = "byronimo@gmail.com" +__homepage__ = "https://github.com/gitpython-developers/smmap" +version_info = (5, 0, 3) +__version__ = '.'.join(str(i) for i in version_info) + +# make everything available in root package for convenience +from .mman import * +from .buf import * diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/smmap/buf.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/smmap/buf.py new file mode 100644 index 0000000000000000000000000000000000000000..731b0644b5a269b1f941dc7cd49163e6754878a6 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/smmap/buf.py @@ -0,0 +1,143 @@ +"""Module with a simple buffer implementation using the memory manager""" +import sys + +__all__ = ["SlidingWindowMapBuffer"] + + +class SlidingWindowMapBuffer: + + """A buffer like object which allows direct byte-wise object and slicing into + memory of a mapped file. The mapping is controlled by the provided cursor. + + The buffer is relative, that is if you map an offset, index 0 will map to the + first byte at the offset you used during initialization or begin_access + + **Note:** Although this type effectively hides the fact that there are mapped windows + underneath, it can unfortunately not be used in any non-pure python method which + needs a buffer or string""" + __slots__ = ( + '_c', # our cursor + '_size', # our supposed size + ) + + def __init__(self, cursor=None, offset=0, size=sys.maxsize, flags=0): + """Initialize the instance to operate on the given cursor. + :param cursor: if not None, the associated cursor to the file you want to access + If None, you have call begin_access before using the buffer and provide a cursor + :param offset: absolute offset in bytes + :param size: the total size of the mapping. Defaults to the maximum possible size + From that point on, the __len__ of the buffer will be the given size or the file size. + If the size is larger than the mappable area, you can only access the actually available + area, although the length of the buffer is reported to be your given size. + Hence it is in your own interest to provide a proper size ! + :param flags: Additional flags to be passed to os.open + :raise ValueError: if the buffer could not achieve a valid state""" + self._c = cursor + if cursor and not self.begin_access(cursor, offset, size, flags): + raise ValueError("Failed to allocate the buffer - probably the given offset is out of bounds") + # END handle offset + + def __del__(self): + self.end_access() + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + self.end_access() + + def __len__(self): + return self._size + + def __getitem__(self, i): + if isinstance(i, slice): + return self.__getslice__(i.start or 0, i.stop or self._size) + c = self._c + assert c.is_valid() + if i < 0: + i = self._size + i + if not c.includes_ofs(i): + c.use_region(i, 1) + # END handle region usage + return c.buffer()[i - c.ofs_begin()] + + def __getslice__(self, i, j): + c = self._c + # fast path, slice fully included - safes a concatenate operation and + # should be the default + assert c.is_valid() + if i < 0: + i = self._size + i + if j == sys.maxsize: + j = self._size + if j < 0: + j = self._size + j + if (c.ofs_begin() <= i) and (j < c.ofs_end()): + b = c.ofs_begin() + return c.buffer()[i - b:j - b] + else: + l = j - i # total length + ofs = i + # It's fastest to keep tokens and join later, especially in py3, which was 7 times slower + # in the previous iteration of this code + md = list() + while l: + c.use_region(ofs, l) + assert c.is_valid() + d = c.buffer()[:l] + ofs += len(d) + l -= len(d) + # Make sure we don't keep references, as c.use_region() might attempt to free resources, but + # can't unless we use pure bytes + if hasattr(d, 'tobytes'): + d = d.tobytes() + md.append(d) + # END while there are bytes to read + return b''.join(md) + # END fast or slow path + #{ Interface + + def begin_access(self, cursor=None, offset=0, size=sys.maxsize, flags=0): + """Call this before the first use of this instance. The method was already + called by the constructor in case sufficient information was provided. + + For more information no the parameters, see the __init__ method + :param path: if cursor is None the existing one will be used. + :return: True if the buffer can be used""" + if cursor: + self._c = cursor + # END update our cursor + + # reuse existing cursors if possible + if self._c is not None and self._c.is_associated(): + res = self._c.use_region(offset, size, flags).is_valid() + if res: + # if given size is too large or default, we computer a proper size + # If its smaller, we assume the combination between offset and size + # as chosen by the user is correct and use it ! + # If not, the user is in trouble. + if size > self._c.file_size(): + size = self._c.file_size() - offset + # END handle size + self._size = size + # END set size + return res + # END use our cursor + return False + + def end_access(self): + """Call this method once you are done using the instance. It is automatically + called on destruction, and should be called just in time to allow system + resources to be freed. + + Once you called end_access, you must call begin access before reusing this instance!""" + self._size = 0 + if self._c is not None: + self._c.unuse_region() + # END unuse region + + def cursor(self): + """:return: the currently set cursor which provides access to the data""" + return self._c + + #}END interface diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/smmap/mman.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/smmap/mman.py new file mode 100644 index 0000000000000000000000000000000000000000..873f687fdc6f0d78ee24a6d25f7720708d48b6e5 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/smmap/mman.py @@ -0,0 +1,588 @@ +"""Module containing a memory memory manager which provides a sliding window on a number of memory mapped files""" +from .util import ( + MapWindow, + MapRegion, + MapRegionList, + is_64_bit, +) + +import sys +from functools import reduce + +__all__ = ["StaticWindowMapManager", "SlidingWindowMapManager", "WindowCursor"] +#{ Utilities + +#}END utilities + + +class WindowCursor: + + """ + Pointer into the mapped region of the memory manager, keeping the map + alive until it is destroyed and no other client uses it. + + Cursors should not be created manually, but are instead returned by the SlidingWindowMapManager + + **Note:**: The current implementation is suited for static and sliding window managers, but it also means + that it must be suited for the somewhat quite different sliding manager. It could be improved, but + I see no real need to do so.""" + __slots__ = ( + '_manager', # the manager keeping all file regions + '_rlist', # a regions list with regions for our file + '_region', # our current class:`MapRegion` or None + '_ofs', # relative offset from the actually mapped area to our start area + '_size' # maximum size we should provide + ) + + def __init__(self, manager=None, regions=None): + self._manager = manager + self._rlist = regions + self._region = None + self._ofs = 0 + self._size = 0 + + def __del__(self): + self._destroy() + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + self._destroy() + + def _destroy(self): + """Destruction code to decrement counters""" + self.unuse_region() + + if self._rlist is not None: + # Actual client count, which doesn't include the reference kept by the manager, nor ours + # as we are about to be deleted + try: + if len(self._rlist) == 0: + # Free all resources associated with the mapped file + self._manager._fdict.pop(self._rlist.path_or_fd()) + # END remove regions list from manager + except (TypeError, KeyError): + # sometimes, during shutdown, getrefcount is None. Its possible + # to re-import it, however, its probably better to just ignore + # this python problem (for now). + # The next step is to get rid of the error prone getrefcount altogether. + pass + # END exception handling + # END handle regions + + def _copy_from(self, rhs): + """Copy all data from rhs into this instance, handles usage count""" + self._manager = rhs._manager + self._rlist = type(rhs._rlist)(rhs._rlist) + self._region = rhs._region + self._ofs = rhs._ofs + self._size = rhs._size + + for region in self._rlist: + region.increment_client_count() + + if self._region is not None: + self._region.increment_client_count() + # END handle regions + + def __copy__(self): + """copy module interface""" + cpy = type(self)() + cpy._copy_from(self) + return cpy + + #{ Interface + def assign(self, rhs): + """Assign rhs to this instance. This is required in order to get a real copy. + Alternatively, you can copy an existing instance using the copy module""" + self._destroy() + self._copy_from(rhs) + + def use_region(self, offset=0, size=0, flags=0): + """Assure we point to a window which allows access to the given offset into the file + + :param offset: absolute offset in bytes into the file + :param size: amount of bytes to map. If 0, all available bytes will be mapped + :param flags: additional flags to be given to os.open in case a file handle is initially opened + for mapping. Has no effect if a region can actually be reused. + :return: this instance - it should be queried for whether it points to a valid memory region. + This is not the case if the mapping failed because we reached the end of the file + + **Note:**: The size actually mapped may be smaller than the given size. If that is the case, + either the file has reached its end, or the map was created between two existing regions""" + need_region = True + man = self._manager + fsize = self._rlist.file_size() + size = min(size or fsize, man.window_size() or fsize) # clamp size to window size + + if self._region is not None: + if self._region.includes_ofs(offset): + need_region = False + else: + self.unuse_region() + # END handle existing region + # END check existing region + + # offset too large ? + if offset >= fsize: + return self + # END handle offset + + if need_region: + self._region = man._obtain_region(self._rlist, offset, size, flags, False) + self._region.increment_client_count() + # END need region handling + + self._ofs = offset - self._region._b + self._size = min(size, self._region.ofs_end() - offset) + + return self + + def unuse_region(self): + """Unuse the current region. Does nothing if we have no current region + + **Note:** the cursor unuses the region automatically upon destruction. It is recommended + to un-use the region once you are done reading from it in persistent cursors as it + helps to free up resource more quickly""" + if self._region is not None: + self._region.increment_client_count(-1) + self._region = None + # note: should reset ofs and size, but we spare that for performance. Its not + # allowed to query information if we are not valid ! + + def buffer(self): + """Return a buffer object which allows access to our memory region from our offset + to the window size. Please note that it might be smaller than you requested when calling use_region() + + **Note:** You can only obtain a buffer if this instance is_valid() ! + + **Note:** buffers should not be cached passed the duration of your access as it will + prevent resources from being freed even though they might not be accounted for anymore !""" + return memoryview(self._region.buffer())[self._ofs:self._ofs+self._size] + + def map(self): + """ + :return: the underlying raw memory map. Please not that the offset and size is likely to be different + to what you set as offset and size. Use it only if you are sure about the region it maps, which is the whole + file in case of StaticWindowMapManager""" + return self._region.map() + + def is_valid(self): + """:return: True if we have a valid and usable region""" + return self._region is not None + + def is_associated(self): + """:return: True if we are associated with a specific file already""" + return self._rlist is not None + + def ofs_begin(self): + """:return: offset to the first byte pointed to by our cursor + + **Note:** only if is_valid() is True""" + return self._region._b + self._ofs + + def ofs_end(self): + """:return: offset to one past the last available byte""" + # unroll method calls for performance ! + return self._region._b + self._ofs + self._size + + def size(self): + """:return: amount of bytes we point to""" + return self._size + + def region(self): + """:return: our mapped region, or None if nothing is mapped yet + :raise AssertionError: if we have no current region. This is only useful for debugging""" + return self._region + + def includes_ofs(self, ofs): + """:return: True if the given absolute offset is contained in the cursors + current region + + **Note:** cursor must be valid for this to work""" + # unroll methods + return (self._region._b + self._ofs) <= ofs < (self._region._b + self._ofs + self._size) + + def file_size(self): + """:return: size of the underlying file""" + return self._rlist.file_size() + + def path_or_fd(self): + """:return: path or file descriptor of the underlying mapped file""" + return self._rlist.path_or_fd() + + def path(self): + """:return: path of the underlying mapped file + :raise ValueError: if attached path is not a path""" + if isinstance(self._rlist.path_or_fd(), int): + raise ValueError("Path queried although mapping was applied to a file descriptor") + # END handle type + return self._rlist.path_or_fd() + + def fd(self): + """:return: file descriptor used to create the underlying mapping. + + **Note:** it is not required to be valid anymore + :raise ValueError: if the mapping was not created by a file descriptor""" + if isinstance(self._rlist.path_or_fd(), str): + raise ValueError("File descriptor queried although mapping was generated from path") + # END handle type + return self._rlist.path_or_fd() + + #} END interface + + +class StaticWindowMapManager: + + """Provides a manager which will produce single size cursors that are allowed + to always map the whole file. + + Clients must be written to specifically know that they are accessing their data + through a StaticWindowMapManager, as they otherwise have to deal with their window size. + + These clients would have to use a SlidingWindowMapBuffer to hide this fact. + + This type will always use a maximum window size, and optimize certain methods to + accommodate this fact""" + + __slots__ = [ + '_fdict', # mapping of path -> StorageHelper (of some kind + '_window_size', # maximum size of a window + '_max_memory_size', # maximum amount of memory we may allocate + '_max_handle_count', # maximum amount of handles to keep open + '_memory_size', # currently allocated memory size + '_handle_count', # amount of currently allocated file handles + ] + + #{ Configuration + MapRegionListCls = MapRegionList + MapWindowCls = MapWindow + MapRegionCls = MapRegion + WindowCursorCls = WindowCursor + #} END configuration + + _MB_in_bytes = 1024 * 1024 + + def __init__(self, window_size=0, max_memory_size=0, max_open_handles=sys.maxsize): + """initialize the manager with the given parameters. + :param window_size: if -1, a default window size will be chosen depending on + the operating system's architecture. It will internally be quantified to a multiple of the page size + If 0, the window may have any size, which basically results in mapping the whole file at one + :param max_memory_size: maximum amount of memory we may map at once before releasing mapped regions. + If 0, a viable default will be set depending on the system's architecture. + It is a soft limit that is tried to be kept, but nothing bad happens if we have to over-allocate + :param max_open_handles: if not maxint, limit the amount of open file handles to the given number. + Otherwise the amount is only limited by the system itself. If a system or soft limit is hit, + the manager will free as many handles as possible""" + self._fdict = dict() + self._window_size = window_size + self._max_memory_size = max_memory_size + self._max_handle_count = max_open_handles + self._memory_size = 0 + self._handle_count = 0 + + if window_size < 0: + coeff = 64 + if is_64_bit(): + coeff = 1024 + # END handle arch + self._window_size = coeff * self._MB_in_bytes + # END handle max window size + + if max_memory_size == 0: + coeff = 1024 + if is_64_bit(): + coeff = 8192 + # END handle arch + self._max_memory_size = coeff * self._MB_in_bytes + # END handle max memory size + + #{ Internal Methods + + def _collect_lru_region(self, size): + """Unmap the region which was least-recently used and has no client + :param size: size of the region we want to map next (assuming its not already mapped partially or full + if 0, we try to free any available region + :return: Amount of freed regions + + .. Note:: + We don't raise exceptions anymore, in order to keep the system working, allowing temporary overallocation. + If the system runs out of memory, it will tell. + + .. TODO:: + implement a case where all unusued regions are discarded efficiently. + Currently its only brute force + """ + num_found = 0 + while (size == 0) or (self._memory_size + size > self._max_memory_size): + lru_region = None + lru_list = None + for regions in self._fdict.values(): + for region in regions: + # check client count - if it's 1, it's just us + if (region.client_count() == 1 and + (lru_region is None or region._uc < lru_region._uc)): + lru_region = region + lru_list = regions + # END update lru_region + # END for each region + # END for each regions list + + if lru_region is None: + break + # END handle region not found + + num_found += 1 + del(lru_list[lru_list.index(lru_region)]) + lru_region.increment_client_count(-1) + self._memory_size -= lru_region.size() + self._handle_count -= 1 + # END while there is more memory to free + return num_found + + def _obtain_region(self, a, offset, size, flags, is_recursive): + """Utility to create a new region - for more information on the parameters, + see MapCursor.use_region. + :param a: A regions (a)rray + :return: The newly created region""" + if self._memory_size + size > self._max_memory_size: + self._collect_lru_region(size) + # END handle collection + + r = None + if a: + assert len(a) == 1 + r = a[0] + else: + try: + r = self.MapRegionCls(a.path_or_fd(), 0, sys.maxsize, flags) + except Exception: + # apparently we are out of system resources or hit a limit + # As many more operations are likely to fail in that condition ( + # like reading a file from disk, etc) we free up as much as possible + # As this invalidates our insert position, we have to recurse here + if is_recursive: + # we already tried this, and still have no success in obtaining + # a mapping. This is an exception, so we propagate it + raise + # END handle existing recursion + self._collect_lru_region(0) + return self._obtain_region(a, offset, size, flags, True) + # END handle exceptions + + self._handle_count += 1 + self._memory_size += r.size() + a.append(r) + # END handle array + + assert r.includes_ofs(offset) + return r + + #}END internal methods + + #{ Interface + def make_cursor(self, path_or_fd): + """ + :return: a cursor pointing to the given path or file descriptor. + It can be used to map new regions of the file into memory + + **Note:** if a file descriptor is given, it is assumed to be open and valid, + but may be closed afterwards. To refer to the same file, you may reuse + your existing file descriptor, but keep in mind that new windows can only + be mapped as long as it stays valid. This is why the using actual file paths + are preferred unless you plan to keep the file descriptor open. + + **Note:** file descriptors are problematic as they are not necessarily unique, as two + different files opened and closed in succession might have the same file descriptor id. + + **Note:** Using file descriptors directly is faster once new windows are mapped as it + prevents the file to be opened again just for the purpose of mapping it.""" + regions = self._fdict.get(path_or_fd) + if regions is None: + regions = self.MapRegionListCls(path_or_fd) + self._fdict[path_or_fd] = regions + # END obtain region for path + return self.WindowCursorCls(self, regions) + + def collect(self): + """Collect all available free-to-collect mapped regions + :return: Amount of freed handles""" + return self._collect_lru_region(0) + + def num_file_handles(self): + """:return: amount of file handles in use. Each mapped region uses one file handle""" + return self._handle_count + + def num_open_files(self): + """Amount of opened files in the system""" + return reduce(lambda x, y: x + y, (1 for rlist in self._fdict.values() if len(rlist) > 0), 0) + + def window_size(self): + """:return: size of each window when allocating new regions""" + return self._window_size + + def mapped_memory_size(self): + """:return: amount of bytes currently mapped in total""" + return self._memory_size + + def max_file_handles(self): + """:return: maximum amount of handles we may have opened""" + return self._max_handle_count + + def max_mapped_memory_size(self): + """:return: maximum amount of memory we may allocate""" + return self._max_memory_size + + #} END interface + + #{ Special Purpose Interface + + def force_map_handle_removal_win(self, base_path): + """ONLY AVAILABLE ON WINDOWS + On windows removing files is not allowed if anybody still has it opened. + If this process is ourselves, and if the whole process uses this memory + manager (as far as the parent framework is concerned) we can enforce + closing all memory maps whose path matches the given base path to + allow the respective operation after all. + The respective system must NOT access the closed memory regions anymore ! + This really may only be used if you know that the items which keep + the cursors alive will not be using it anymore. They need to be recreated ! + :return: Amount of closed handles + + **Note:** does nothing on non-windows platforms""" + if sys.platform != 'win32': + return + # END early bailout + + num_closed = 0 + for path, rlist in self._fdict.items(): + if path.startswith(base_path): + for region in rlist: + region.release() + num_closed += 1 + # END path matches + # END for each path + return num_closed + #} END special purpose interface + + +class SlidingWindowMapManager(StaticWindowMapManager): + + """Maintains a list of ranges of mapped memory regions in one or more files and allows to easily + obtain additional regions assuring there is no overlap. + Once a certain memory limit is reached globally, or if there cannot be more open file handles + which result from each mmap call, the least recently used, and currently unused mapped regions + are unloaded automatically. + + **Note:** currently not thread-safe ! + + **Note:** in the current implementation, we will automatically unload windows if we either cannot + create more memory maps (as the open file handles limit is hit) or if we have allocated more than + a safe amount of memory already, which would possibly cause memory allocations to fail as our address + space is full.""" + + __slots__ = tuple() + + def __init__(self, window_size=-1, max_memory_size=0, max_open_handles=sys.maxsize): + """Adjusts the default window size to -1""" + super().__init__(window_size, max_memory_size, max_open_handles) + + def _obtain_region(self, a, offset, size, flags, is_recursive): + # bisect to find an existing region. The c++ implementation cannot + # do that as it uses a linked list for regions. + r = None + lo = 0 + hi = len(a) + while lo < hi: + mid = (lo + hi) // 2 + ofs = a[mid]._b + if ofs <= offset: + if a[mid].includes_ofs(offset): + r = a[mid] + break + # END have region + lo = mid + 1 + else: + hi = mid + # END handle position + # END while bisecting + + if r is None: + window_size = self._window_size + left = self.MapWindowCls(0, 0) + mid = self.MapWindowCls(offset, size) + right = self.MapWindowCls(a.file_size(), 0) + + # we want to honor the max memory size, and assure we have anough + # memory available + # Save calls ! + if self._memory_size + window_size > self._max_memory_size: + self._collect_lru_region(window_size) + # END handle collection + + # we assume the list remains sorted by offset + insert_pos = 0 + len_regions = len(a) + if len_regions == 1: + if a[0]._b <= offset: + insert_pos = 1 + # END maintain sort + else: + # find insert position + insert_pos = len_regions + for i, region in enumerate(a): + if region._b > offset: + insert_pos = i + break + # END if insert position is correct + # END for each region + # END obtain insert pos + + # adjust the actual offset and size values to create the largest + # possible mapping + if insert_pos == 0: + if len_regions: + right = self.MapWindowCls.from_region(a[insert_pos]) + # END adjust right side + else: + if insert_pos != len_regions: + right = self.MapWindowCls.from_region(a[insert_pos]) + # END adjust right window + left = self.MapWindowCls.from_region(a[insert_pos - 1]) + # END adjust surrounding windows + + mid.extend_left_to(left, window_size) + mid.extend_right_to(right, window_size) + mid.align() + + # it can happen that we align beyond the end of the file + if mid.ofs_end() > right.ofs: + mid.size = right.ofs - mid.ofs + # END readjust size + + # insert new region at the right offset to keep the order + try: + if self._handle_count >= self._max_handle_count: + raise Exception + # END assert own imposed max file handles + r = self.MapRegionCls(a.path_or_fd(), mid.ofs, mid.size, flags) + except Exception: + # apparently we are out of system resources or hit a limit + # As many more operations are likely to fail in that condition ( + # like reading a file from disk, etc) we free up as much as possible + # As this invalidates our insert position, we have to recurse here + if is_recursive: + # we already tried this, and still have no success in obtaining + # a mapping. This is an exception, so we propagate it + raise + # END handle existing recursion + self._collect_lru_region(0) + return self._obtain_region(a, offset, size, flags, True) + # END handle exceptions + + self._handle_count += 1 + self._memory_size += r.size() + a.insert(insert_pos, r) + # END create new region + return r diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/smmap/util.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/smmap/util.py new file mode 100644 index 0000000000000000000000000000000000000000..fbb3872118e644ee0a920914fa5835cf2bfab44d --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/smmap/util.py @@ -0,0 +1,222 @@ +"""Module containing a memory memory manager which provides a sliding window on a number of memory mapped files""" +import os +import sys + +from mmap import mmap, ACCESS_READ +from mmap import ALLOCATIONGRANULARITY + +__all__ = ["align_to_mmap", "is_64_bit", + "MapWindow", "MapRegion", "MapRegionList", "ALLOCATIONGRANULARITY"] + +#{ Utilities + + +def align_to_mmap(num, round_up): + """ + Align the given integer number to the closest page offset, which usually is 4096 bytes. + + :param round_up: if True, the next higher multiple of page size is used, otherwise + the lower page_size will be used (i.e. if True, 1 becomes 4096, otherwise it becomes 0) + :return: num rounded to closest page""" + res = (num // ALLOCATIONGRANULARITY) * ALLOCATIONGRANULARITY + if round_up and (res != num): + res += ALLOCATIONGRANULARITY + # END handle size + return res + + +def is_64_bit(): + """:return: True if the system is 64 bit. Otherwise it can be assumed to be 32 bit""" + return sys.maxsize > (1 << 32) - 1 + +#}END utilities + + +#{ Utility Classes + +class MapWindow: + + """Utility type which is used to snap windows towards each other, and to adjust their size""" + __slots__ = ( + 'ofs', # offset into the file in bytes + 'size' # size of the window in bytes + ) + + def __init__(self, offset, size): + self.ofs = offset + self.size = size + + def __repr__(self): + return "MapWindow(%i, %i)" % (self.ofs, self.size) + + @classmethod + def from_region(cls, region): + """:return: new window from a region""" + return cls(region._b, region.size()) + + def ofs_end(self): + return self.ofs + self.size + + def align(self): + """Assures the previous window area is contained in the new one""" + nofs = align_to_mmap(self.ofs, 0) + self.size += self.ofs - nofs # keep size constant + self.ofs = nofs + self.size = align_to_mmap(self.size, 1) + + def extend_left_to(self, window, max_size): + """Adjust the offset to start where the given window on our left ends if possible, + but don't make yourself larger than max_size. + The resize will assure that the new window still contains the old window area""" + rofs = self.ofs - window.ofs_end() + nsize = rofs + self.size + rofs -= nsize - min(nsize, max_size) + self.ofs -= rofs + self.size += rofs + + def extend_right_to(self, window, max_size): + """Adjust the size to make our window end where the right window begins, but don't + get larger than max_size""" + self.size = min(self.size + (window.ofs - self.ofs_end()), max_size) + + +class MapRegion: + + """Defines a mapped region of memory, aligned to pagesizes + + **Note:** deallocates used region automatically on destruction""" + __slots__ = [ + '_b', # beginning of mapping + '_mf', # mapped memory chunk (as returned by mmap) + '_uc', # total amount of usages + '_size', # cached size of our memory map + '__weakref__' + ] + + #{ Configuration + #} END configuration + + def __init__(self, path_or_fd, ofs, size, flags=0): + """Initialize a region, allocate the memory map + :param path_or_fd: path to the file to map, or the opened file descriptor + :param ofs: **aligned** offset into the file to be mapped + :param size: if size is larger then the file on disk, the whole file will be + allocated the the size automatically adjusted + :param flags: additional flags to be given when opening the file. + :raise Exception: if no memory can be allocated""" + self._b = ofs + self._size = 0 + self._uc = 0 + + if isinstance(path_or_fd, int): + fd = path_or_fd + else: + fd = os.open(path_or_fd, os.O_RDONLY | getattr(os, 'O_BINARY', 0) | flags) + # END handle fd + + try: + kwargs = dict(access=ACCESS_READ, offset=ofs) + corrected_size = size + sizeofs = ofs + + # have to correct size, otherwise (instead of the c version) it will + # bark that the size is too large ... many extra file accesses because + # if this ... argh ! + actual_size = min(os.fstat(fd).st_size - sizeofs, corrected_size) + self._mf = mmap(fd, actual_size, **kwargs) + # END handle memory mode + + self._size = len(self._mf) + finally: + if isinstance(path_or_fd, str): + os.close(fd) + # END only close it if we opened it + # END close file handle + # We assume the first one to use us keeps us around + self.increment_client_count() + + def __repr__(self): + return "MapRegion<%i, %i>" % (self._b, self.size()) + + #{ Interface + + def buffer(self): + """:return: a buffer containing the memory""" + return self._mf + + def map(self): + """:return: a memory map containing the memory""" + return self._mf + + def ofs_begin(self): + """:return: absolute byte offset to the first byte of the mapping""" + return self._b + + def size(self): + """:return: total size of the mapped region in bytes""" + return self._size + + def ofs_end(self): + """:return: Absolute offset to one byte beyond the mapping into the file""" + return self._b + self._size + + def includes_ofs(self, ofs): + """:return: True if the given offset can be read in our mapped region""" + return self._b <= ofs < self._b + self._size + + def client_count(self): + """:return: number of clients currently using this region""" + return self._uc + + def increment_client_count(self, ofs = 1): + """Adjust the usage count by the given positive or negative offset. + If usage count equals 0, we will auto-release our resources + :return: True if we released resources, False otherwise. In the latter case, we can still be used""" + self._uc += ofs + assert self._uc > -1, "Increments must match decrements, usage counter negative: %i" % self._uc + + if self.client_count() == 0: + self.release() + return True + else: + return False + # end handle release + + def release(self): + """Release all resources this instance might hold. Must only be called if there usage_count() is zero""" + self._mf.close() + + #} END interface + + +class MapRegionList(list): + + """List of MapRegion instances associating a path with a list of regions.""" + __slots__ = ( + '_path_or_fd', # path or file descriptor which is mapped by all our regions + '_file_size' # total size of the file we map + ) + + def __new__(cls, path): + return super().__new__(cls) + + def __init__(self, path_or_fd): + self._path_or_fd = path_or_fd + self._file_size = None + + def path_or_fd(self): + """:return: path or file descriptor we are attached to""" + return self._path_or_fd + + def file_size(self): + """:return: size of file we manager""" + if self._file_size is None: + if isinstance(self._path_or_fd, str): + self._file_size = os.stat(self._path_or_fd).st_size + else: + self._file_size = os.fstat(self._path_or_fd).st_size + # END handle path type + # END update file size + return self._file_size + +#} END utility classes diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/INSTALLER b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/LICENSE b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..51f3442917839f8e0f0cccb52b3c10968ad0779e --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/LICENSE @@ -0,0 +1,3 @@ +This software is made available under the terms of *either* of the +licenses found in LICENSE.APACHE2 or LICENSE.MIT. Contributions to are +made under the terms of *both* these licenses. diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/LICENSE.APACHE2 b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/LICENSE.APACHE2 new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/LICENSE.APACHE2 @@ -0,0 +1,202 @@ + + 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/LICENSE.MIT b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/LICENSE.MIT new file mode 100644 index 0000000000000000000000000000000000000000..b8bb97185926d7daed314609753173945ed4ff1a --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/LICENSE.MIT @@ -0,0 +1,20 @@ +The MIT License (MIT) + +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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/METADATA b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..75e0057bbad50ca4c117b9130b92f1bed2720669 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/METADATA @@ -0,0 +1,104 @@ +Metadata-Version: 2.1 +Name: sniffio +Version: 1.3.1 +Summary: Sniff out which async library your code is running under +Author-email: "Nathaniel J. Smith" +License: MIT OR Apache-2.0 +Project-URL: Homepage, https://github.com/python-trio/sniffio +Project-URL: Documentation, https://sniffio.readthedocs.io/ +Project-URL: Changelog, https://sniffio.readthedocs.io/en/latest/history.html +Keywords: async,trio,asyncio +Classifier: License :: OSI Approved :: MIT License +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Framework :: Trio +Classifier: Framework :: AsyncIO +Classifier: Operating System :: POSIX :: Linux +Classifier: Operating System :: MacOS :: MacOS X +Classifier: Operating System :: Microsoft :: Windows +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Intended Audience :: Developers +Classifier: Development Status :: 5 - Production/Stable +Requires-Python: >=3.7 +Description-Content-Type: text/x-rst +License-File: LICENSE +License-File: LICENSE.APACHE2 +License-File: LICENSE.MIT + +.. image:: https://img.shields.io/badge/chat-join%20now-blue.svg + :target: https://gitter.im/python-trio/general + :alt: Join chatroom + +.. image:: https://img.shields.io/badge/docs-read%20now-blue.svg + :target: https://sniffio.readthedocs.io/en/latest/?badge=latest + :alt: Documentation Status + +.. image:: https://img.shields.io/pypi/v/sniffio.svg + :target: https://pypi.org/project/sniffio + :alt: Latest PyPi version + +.. image:: https://img.shields.io/conda/vn/conda-forge/sniffio.svg + :target: https://anaconda.org/conda-forge/sniffio + :alt: Latest conda-forge version + +.. image:: https://travis-ci.org/python-trio/sniffio.svg?branch=master + :target: https://travis-ci.org/python-trio/sniffio + :alt: Automated test status + +.. image:: https://codecov.io/gh/python-trio/sniffio/branch/master/graph/badge.svg + :target: https://codecov.io/gh/python-trio/sniffio + :alt: Test coverage + +================================================================= +sniffio: Sniff out which async library your code is running under +================================================================= + +You're writing a library. You've decided to be ambitious, and support +multiple async I/O packages, like `Trio +`__, and `asyncio +`__, and ... You've +written a bunch of clever code to handle all the differences. But... +how do you know *which* piece of clever code to run? + +This is a tiny package whose only purpose is to let you detect which +async library your code is running under. + +* Documentation: https://sniffio.readthedocs.io + +* Bug tracker and source code: https://github.com/python-trio/sniffio + +* License: MIT or Apache License 2.0, your choice + +* Contributor guide: https://trio.readthedocs.io/en/latest/contributing.html + +* Code of conduct: Contributors are requested to follow our `code of + conduct + `_ + in all project spaces. + +This library is maintained by the Trio project, as a service to the +async Python community as a whole. + + +Quickstart +---------- + +.. code-block:: python3 + + from sniffio import current_async_library + import trio + import asyncio + + async def print_library(): + library = current_async_library() + print("This is:", library) + + # Prints "This is trio" + trio.run(print_library) + + # Prints "This is asyncio" + asyncio.run(print_library()) + +For more details, including how to add support to new async libraries, +`please peruse our fine manual `__. diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/RECORD b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..68d8d987668df5b887295da207750819779e43b4 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/RECORD @@ -0,0 +1,19 @@ +sniffio-1.3.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +sniffio-1.3.1.dist-info/LICENSE,sha256=ZSyHhIjRRWNh4Iw_hgf9e6WYkqFBA9Fczk_5PIW1zIs,185 +sniffio-1.3.1.dist-info/LICENSE.APACHE2,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358 +sniffio-1.3.1.dist-info/LICENSE.MIT,sha256=Pm2uVV65J4f8gtHUg1Vnf0VMf2Wus40_nnK_mj2vA0s,1046 +sniffio-1.3.1.dist-info/METADATA,sha256=CzGLVwmO3sz1heYKiJprantcQIbzqapi7_dqHTzuEtk,3875 +sniffio-1.3.1.dist-info/RECORD,, +sniffio-1.3.1.dist-info/WHEEL,sha256=oiQVh_5PnQM0E3gPdiz09WCNmwiHDMaGer_elqB3coM,92 +sniffio-1.3.1.dist-info/top_level.txt,sha256=v9UJXGs5CyddCVeAqXkQiWOrpp6Wtx6GeRrPt9-jjHg,8 +sniffio/__init__.py,sha256=9WJEJlXu7yluP0YtI5SQ9M9OTQfbNHkadarK1vXGDPM,335 +sniffio/__pycache__/__init__.cpython-310.pyc,, +sniffio/__pycache__/_impl.cpython-310.pyc,, +sniffio/__pycache__/_version.cpython-310.pyc,, +sniffio/_impl.py,sha256=UmUFMZpiuOrcjnuHhuYiYMxeCNWfqu9kBlaPf0xk6X8,2843 +sniffio/_tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sniffio/_tests/__pycache__/__init__.cpython-310.pyc,, +sniffio/_tests/__pycache__/test_sniffio.cpython-310.pyc,, +sniffio/_tests/test_sniffio.py,sha256=MMJZZJjQrUi95RANNM-a_55BZquA_gv4rHU1pevcTCM,2058 +sniffio/_version.py,sha256=iVes5xwsHeRzQDexBaAhyx_taNt2ucfA7CWAo4QDt6Q,89 +sniffio/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/WHEEL b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..98c0d20b7a64f4f998d7913e1d38a05dba20916c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.42.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/top_level.txt b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..01c650244d0ccb6043c603b736fcf8d9e622bc71 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/top_level.txt @@ -0,0 +1 @@ +sniffio diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..63f2f19e409c7f4b3c6c064022e8f104227873aa --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/__init__.py @@ -0,0 +1,17 @@ +"""Top-level package for sniffio.""" + +__all__ = [ + "current_async_library", + "AsyncLibraryNotFoundError", + "current_async_library_cvar", + "thread_local", +] + +from ._version import __version__ + +from ._impl import ( + current_async_library, + AsyncLibraryNotFoundError, + current_async_library_cvar, + thread_local, +) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/_impl.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..c1a7bbf218ba985b87cd1d9b23da69222894c1dd --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/_impl.py @@ -0,0 +1,95 @@ +from contextvars import ContextVar +from typing import Optional +import sys +import threading + +current_async_library_cvar = ContextVar( + "current_async_library_cvar", default=None +) # type: ContextVar[Optional[str]] + + +class _ThreadLocal(threading.local): + # Since threading.local provides no explicit mechanism is for setting + # a default for a value, a custom class with a class attribute is used + # instead. + name = None # type: Optional[str] + + +thread_local = _ThreadLocal() + + +class AsyncLibraryNotFoundError(RuntimeError): + pass + + +def current_async_library() -> str: + """Detect which async library is currently running. + + The following libraries are currently supported: + + ================ =========== ============================ + Library Requires Magic string + ================ =========== ============================ + **Trio** Trio v0.6+ ``"trio"`` + **Curio** - ``"curio"`` + **asyncio** ``"asyncio"`` + **Trio-asyncio** v0.8.2+ ``"trio"`` or ``"asyncio"``, + depending on current mode + ================ =========== ============================ + + Returns: + A string like ``"trio"``. + + Raises: + AsyncLibraryNotFoundError: if called from synchronous context, + or if the current async library was not recognized. + + Examples: + + .. code-block:: python3 + + from sniffio import current_async_library + + async def generic_sleep(seconds): + library = current_async_library() + if library == "trio": + import trio + await trio.sleep(seconds) + elif library == "asyncio": + import asyncio + await asyncio.sleep(seconds) + # ... and so on ... + else: + raise RuntimeError(f"Unsupported library {library!r}") + + """ + value = thread_local.name + if value is not None: + return value + + value = current_async_library_cvar.get() + if value is not None: + return value + + # Need to sniff for asyncio + if "asyncio" in sys.modules: + import asyncio + try: + current_task = asyncio.current_task # type: ignore[attr-defined] + except AttributeError: + current_task = asyncio.Task.current_task # type: ignore[attr-defined] + try: + if current_task() is not None: + return "asyncio" + except RuntimeError: + pass + + # Sniff for curio (for now) + if 'curio' in sys.modules: + from curio.meta import curio_running + if curio_running(): + return 'curio' + + raise AsyncLibraryNotFoundError( + "unknown async library, or not in async context" + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/_version.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..0495d10545c9fd515ed51e890309d2b66e2c30bb --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/_version.py @@ -0,0 +1,3 @@ +# This file is imported from __init__.py and exec'd from setup.py + +__version__ = "1.3.1" diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/py.typed b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/spacy_loggers-1.0.5.dist-info/INSTALLER b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/spacy_loggers-1.0.5.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/spacy_loggers-1.0.5.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/spacy_loggers-1.0.5.dist-info/LICENSE b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/spacy_loggers-1.0.5.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..4350174cf9f66ebf628b484903b6fe34d73ff69b --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/spacy_loggers-1.0.5.dist-info/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 ExplosionAI GmbH + +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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/spacy_loggers-1.0.5.dist-info/METADATA b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/spacy_loggers-1.0.5.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..5e76645a576174411a1c5ec54f10fd40b27fff79 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/spacy_loggers-1.0.5.dist-info/METADATA @@ -0,0 +1,379 @@ +Metadata-Version: 2.1 +Name: spacy-loggers +Version: 1.0.5 +Summary: Logging utilities for SpaCy +Home-page: https://github.com/explosion/spacy-loggers +Author: Explosion +Author-email: contact@explosion.ai +License: MIT +Requires-Python: >=3.6 +Description-Content-Type: text/markdown +License-File: LICENSE + + + +# spacy-loggers: Logging utilities for spaCy + +[![PyPi Version](https://img.shields.io/pypi/v/spacy-loggers.svg?style=flat-square&logo=pypi&logoColor=white)](https://pypi.python.org/pypi/spacy-loggers) + +Starting with spaCy v3.2, alternate loggers are moved into a separate package +so that they can be added and updated independently from the core spaCy +library. + +`spacy-loggers` currently provides loggers for: + +- [Weights & Biases](https://www.wandb.com) +- [MLflow](https://www.mlflow.org/) +- [ClearML](https://www.clear.ml/) +- [PyTorch](https://pytorch.org/) +- [CuPy](https://github.com/cupy/cupy) + +`spacy-loggers` also provides additional utility loggers to facilitate interoperation +between individual loggers. + +If you'd like to add a new logger or logging option, please submit a PR to this +repo! + +## Setup and installation + +`spacy-loggers` should be installed automatically with spaCy v3.2+, so you +usually don't need to install it separately. You can install it with `pip` or +from the conda channel `conda-forge`: + +```bash +pip install spacy-loggers +``` + +```bash +conda install -c conda-forge spacy-loggers +``` + +# Loggers + +## WandbLogger + +### Installation + +This logger requires `wandb` to be installed and configured: + +```bash +pip install wandb +wandb login +``` + +### Usage + +`spacy.WandbLogger.v5` is a logger that sends the results of each training step +to the dashboard of the [Weights & Biases](https://www.wandb.com/) tool. To use +this logger, Weights & Biases should be installed, and you should be logged in. +The logger will send the full config file to W&B, as well as various system +information such as memory utilization, network traffic, disk IO, GPU +statistics, etc. This will also include information such as your hostname and +operating system, as well as the location of your Python executable. + +`spacy.WandbLogger.v4` and below automatically call the [default console logger](https://spacy.io/api/top-level#ConsoleLogger). +However, starting with `spacy.WandbLogger.v5`, console logging must be activated +through the use of the [ChainLogger](#chainlogger). This allows the user to configure +the console logger's parameters according to their preferences. + +**Note** that by default, the full (interpolated) +[training config](https://spacy.io/usage/training#config) is sent over to the +W&B dashboard. If you prefer to **exclude certain information** such as path +names, you can list those fields in "dot notation" in the +`remove_config_values` parameter. These fields will then be removed from the +config before uploading, but will otherwise remain in the config file stored +on your local system. + +### Example config + +```ini +[training.logger] +@loggers = "spacy.WandbLogger.v5" +project_name = "monitor_spacy_training" +remove_config_values = ["paths.train", "paths.dev", "corpora.train.path", "corpora.dev.path"] +log_dataset_dir = "corpus" +model_log_interval = 1000 +``` + +| Name | Type | Description | +| ---------------------- | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `project_name` | `str` | The name of the project in the Weights & Biases interface. The project will be created automatically if it doesn't exist yet. | +| `remove_config_values` | `List[str]` | A list of values to exclude from the config before it is uploaded to W&B (default: `[]`). | +| `model_log_interval` | `Optional[int]` | Steps to wait between logging model checkpoints to the W&B dasboard (default: `None`). Added in `spacy.WandbLogger.v2`. | +| `log_dataset_dir` | `Optional[str]` | Directory containing the dataset to be logged and versioned as a W&B artifact (default: `None`). Added in `spacy.WandbLogger.v2`. | +| `entity` | `Optional[str]` | An entity is a username or team name where you're sending runs. If you don't specify an entity, the run will be sent to your default entity, which is usually your username (default: `None`). Added in `spacy.WandbLogger.v3`. | +| `run_name` | `Optional[str]` | The name of the run. If you don't specify a run name, the name will be created by the `wandb` library (default: `None`). Added in `spacy.WandbLogger.v3`. | +| `log_best_dir` | `Optional[str]` | Directory containing the best trained model as saved by spaCy (by default in `training/model-best`), to be logged and versioned as a W&B artifact (default: `None`). Added in `spacy.WandbLogger.v4`. | +| `log_latest_dir` | `Optional[str]` | Directory containing the latest trained model as saved by spaCy (by default in `training/model-latest`), to be logged and versioned as a W&B artifact (default: `None`). Added in `spacy.WandbLogger.v4`. | +| `log_custom_stats` | `Optional[List[str]]` | A list of regular expressions that will be applied to the info dictionary passed to the logger (default: `None`). Statistics and metrics that match these regexps will be automatically logged. Added in `spacy.WandbLogger.v5`. | + +## MLflowLogger + +### Installation + +This logger requires `mlflow` to be installed and configured: + +```bash +pip install mlflow +``` + +### Usage + +`spacy.MLflowLogger.v2` is a logger that tracks the results of each training step +using the [MLflow](https://www.mlflow.org/) tool. To use +this logger, MLflow should be installed. At the beginning of each model training +operation, the logger will initialize a new MLflow run and set it as the active +run under which metrics and parameters wil be logged. The logger will then log +the entire config file as parameters of the active run. After each training step, +the following actions are performed: + +- The final score is logged under the metric `score`. +- Individual component scores are logged under their default names. +- Loss values of different components are logged with the `loss_` prefix. +- If the final score is higher than the previous best score (for the current run), + the model artifact is additionally uploaded to MLflow. This action is only performed + if the `output_path` argument is provided during the training pipeline initialization phase. + +By default, the tracking API writes data into files in a local `./mlruns` directory. + +`spacy.MLflowLogger.v1` and below automatically call the [default console logger](https://spacy.io/api/top-level#ConsoleLogger). +However, starting with `spacy.MLflowLogger.v2`, console logging must be activated +through the use of the [ChainLogger](#chainlogger). This allows the user to configure +the console logger's parameters according to their preferences. + +**Note** that by default, the full (interpolated) +[training config](https://spacy.io/usage/training#config) is sent over to +MLflow. If you prefer to **exclude certain information** such as path +names, you can list those fields in "dot notation" in the +`remove_config_values` parameter. These fields will then be removed from the +config before uploading, but will otherwise remain in the config file stored +on your local system. + +### Example config + +```ini +[training.logger] +@loggers = "spacy.MLflowLogger.v2" +experiment_id = "1" +run_name = "with_fast_alignments" +nested = False +remove_config_values = ["paths.train", "paths.dev", "corpora.train.path", "corpora.dev.path"] +``` + +| Name | Type | Description | +| ---------------------- | -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `run_id` | `Optional[str]` | Unique ID of an existing MLflow run to which parameters and metrics are logged. Can be omitted if `experiment_id` and `run_id` are provided (default: `None`). | +| `experiment_id` | `Optional[str]` | ID of an existing experiment under which to create the current run. Only applicable when `run_id` is `None` (default: `None`). | +| `run_name` | `Optional[str]` | Name of new run. Only applicable when `run_id` is `None` (default: `None`). | +| `nested` | `bool` | Controls whether run is nested in parent run. `True` creates a nested run (default: `False`). | +| `tags` | `Optional[Dict[str, Any]]` | A dictionary of string keys and values to set as tags on the run. If a run is being resumed, these tags are set on the resumed run. If a new run is being created, these tags are set on the new run (default: `None`). | +| `remove_config_values` | `List[str]` | A list of values to exclude from the config before it is uploaded to MLflow (default: `[]`). | +| `log_custom_stats` | `Optional[List[str]]` | A list of regular expressions that will be applied to the info dictionary passed to the logger (default: `None`). Statistics and metrics that match these regexps will be automatically logged. Added in `spacy.MLflowLogger.v2`. | + +## ClearMLLogger + +### Installation + +This logger requires `clearml` to be installed and configured: + +```bash +pip install clearml +clearml-init +``` + +### Usage + +`spacy.ClearMLLogger.v2` is a logger that tracks the results of each training step +using the [ClearML](https://www.clear.ml/) tool. To use +this logger, ClearML should be installed and you should have initialized (using the command above). +The logger will send all the gathered information to your ClearML server, either [the hosted free tier](https://app.clear.ml) +or the open source [self-hosted server](https://github.com/allegroai/clearml-server). This logger captures the following information, all of which is visible in the ClearML web UI: + +- The full spaCy config file contents. +- Code information such as git repository, commit ID and uncommitted changes. +- Full console output. +- Miscellaneous info such as time, python version and hardware information. +- Output scalars: + - The final score is logged under the scalar `score`. + - Individual component scores are grouped together on one scalar plot (filterable using the web UI). + - Loss values of different components are logged with the `loss_` prefix. + +In addition to the above, the following artifacts can also be optionally captured: + +- Best model directory (zipped). +- Latest model directory (zipped). +- Dataset used to train. + - Versioned using ClearML Data and linked to under Configuration -> User Properties on the web UI. + +`spacy.ClearMLLogger.v1` and below automatically call the [default console logger](https://spacy.io/api/top-level#ConsoleLogger). +However, starting with `spacy.ClearMLLogger.v2`, console logging must be activated +through the use of the [ChainLogger](#chainlogger). This allows the user to configure +the console logger's parameters according to their preferences. + +**Note** that by default, the full (interpolated) +[training config](https://spacy.io/usage/training#config) is sent over to +ClearML. If you prefer to **exclude certain information** such as path +names, you can list those fields in "dot notation" in the +`remove_config_values` parameter. These fields will then be removed from the +config before uploading, but will otherwise remain in the config file stored +on your local system. + +### Example config + +```ini +[training.logger] +@loggers = "spacy.ClearMLLogger.v2" +project_name = "Hello ClearML!" +task_name = "My spaCy Task" +model_log_interval = 1000 +log_best_dir = training/model-best +log_latest_dir = training/model-last +log_dataset_dir = corpus +remove_config_values = ["paths.train", "paths.dev", "corpora.train.path", "corpora.dev.path"] +``` + +| Name | Type | Description | +| ---------------------- | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `project_name` | `str` | The name of the project in the ClearML interface. The project will be created automatically if it doesn't exist yet. | +| `task_name` | `str` | The name of the ClearML task. A task is an experiment that lives inside a project. Can be non-unique. | +| `remove_config_values` | `List[str]` | A list of values to exclude from the config before it is uploaded to ClearML (default: `[]`). | +| `model_log_interval` | `Optional[int]` | Steps to wait between logging model checkpoints to the ClearML dasboard (default: `None`). Will have no effect without also setting `log_best_dir` or `log_latest_dir`. | +| `log_dataset_dir` | `Optional[str]` | Directory containing the dataset to be logged and versioned as a [ClearML Dataset](https://clear.ml/docs/latest/docs/clearml_data/clearml_data/) (default: `None`). | +| `log_best_dir` | `Optional[str]` | Directory containing the best trained model as saved by spaCy (by default in `training/model-best`), to be logged and versioned as a ClearML artifact (default: `None`) | +| `log_latest_dir` | `Optional[str]` | Directory containing the latest trained model as saved by spaCy (by default in `training/model-last`), to be logged and versioned as a ClearML artifact (default: `None`) | +| `log_custom_stats` | `Optional[List[str]]` | A list of regular expressions that will be applied to the info dictionary passed to the logger (default: `None`). Statistics and metrics that match these regexps will be automatically logged. Added in `spacy.ClearMLLogger.v2`. | + +## PyTorchLogger + +### Installation + +This logger requires `torch` to be installed: + +```bash +pip install torch +``` + +### Usage + +`spacy.PyTorchLogger.v1` is different from the other loggers above in that it does not act as a bridge between spaCy and +an external framework. Instead, it is used to query PyTorch-specific metrics and make them available to other loggers. +Therefore, it's primarily intended to be used with [ChainLogger](#chainlogger). + +Whenever a logging checkpoint is reached, it queries statistics from the PyTorch backend and stores them in +the dictionary passed to it. Downstream loggers can thereafter lookup the statistics and log them to their +preferred framework. + +The following PyTorch statistics are currently supported: + +- [CUDA memory statistics](https://pytorch.org/docs/stable/generated/torch.cuda.memory_stats.html#torch.cuda.memory_stats) + +### Example config + +```ini +[training.logger] +@loggers = "spacy.ChainLogger.v1" +logger1 = {"@loggers": "spacy.PyTorchLogger.v1", "prefix": "pytorch", "device": "0", "cuda_mem_metric": "current"} +# Alternatively, you can use any other logger that provides the `log_custom_stats` parameter. +logger2 = {"@loggers": "spacy.LookupLogger.v1", "patterns": ["pytorch"]} +``` + +| Name | Type | Description | +| ----------------- | ----- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `prefix` | `str` | All metric names are prefixed with this string using dot notation, e.g: `.` (default: `pytorch`). | +| `device` | `int` | The identifier of the CUDA device (default: `0`). | +| `cuda_mem_pool` | `str` | One of the memory pool values specified in the PyTorch docs: `all`, `large_pool`, `small_pool` (default: `all`). | +| `cuda_mem_metric` | `str` | One of the memory metric values specified in the PyTorch docs: `current`, `peak`, `allocated`, `freed`. To log all metrics, use `all` instead (default: `all`). | + +## CupyLogger + +### Installation + +This logger requires `cupy` to be installed: + +```bash +pip install cupy +``` + +### Usage + +Similar to `PyTorchLogger`, `spacy.CupyLogger.v1` does not act as a bridge between spaCy and an external framework +but rather is used with the [ChainLogger](#chainlogger) to facilitate the flow of metrics to other loggers. +The `CupyLogger` queries statistics from the CuPy backend and stores them in the info dictionary passed to it. Downstream +loggers can thereafter lookup the statistics and log them to their preferred framework. + +The following CuPy statistics are currently supported: + +- [CUDA memory pool statistics](https://docs.cupy.dev/en/stable/user_guide/memory.html) + +### Example config + +```ini +[training.logger] +@loggers = "spacy.ChainLogger.v1" +logger1 = {"@loggers": "spacy.CupyLogger.v1", "prefix": "cupy"} +# Alternatively, you can use any other logger that provides the `log_custom_stats` parameter. +logger2 = {"@loggers": "spacy.LookupLogger.v1", "patterns": ["cupy"]} +``` + +| Name | Type | Description | +| -------- | ----- | ---------------------------------------------------------------------------------------------------------------- | +| `prefix` | `str` | All metric names are prefixed with this string using dot notation, e.g: `.` (default: `"cupy"`). | + +# Utility Loggers + +## ChainLogger + +### Usage + +This logger can be used to daisy-chain multiple loggers and execute them in-order. Loggers that are executed earlier in the chain +can pass information to those that come later by adding it to the dictionary that is passed to them. + +Currently, up to 10 loggers can be chained together. + +### Example config + +```ini +[training.logger] +@loggers = "spacy.ChainLogger.v1" +logger1 = {"@loggers": "spacy.PyTorchLogger.v1"} +logger2 = {"@loggers": "spacy.ConsoleLogger.v1", "progress_bar": "true"} +``` + +| Name | Type | Description | +| ---------- | -------------------- | -------------------------------------------------- | +| `logger1` | `Optional[Callable]` | The first logger in the chain (default: `None`). | +| `logger2` | `Optional[Callable]` | The second logger in the chain (default: `None`). | +| `logger3` | `Optional[Callable]` | The third logger in the chain (default: `None`). | +| `logger4` | `Optional[Callable]` | The fourth logger in the chain (default: `None`). | +| `logger5` | `Optional[Callable]` | The fifth logger in the chain (default: `None`). | +| `logger6` | `Optional[Callable]` | The sixth logger in the chain (default: `None`). | +| `logger7` | `Optional[Callable]` | The seventh logger in the chain (default: `None`). | +| `logger8` | `Optional[Callable]` | The eighth logger in the chain (default: `None`). | +| `logger9` | `Optional[Callable]` | The ninth logger in the chain (default: `None`). | +| `logger10` | `Optional[Callable]` | The tenth logger in the chain (default: `None`). | + +## LookupLogger + +### Usage + +This logger can be used to lookup statistics in the info dictionary and print them to `stdout`. It is primarily +intended to be used as a tool when developing new loggers. + +### Example config + +```ini +[training.logger] +@loggers = "spacy.ChainLogger.v1" +logger1 = {"@loggers": "spacy.PyTorchLogger.v1", "prefix": "pytorch"} +logger2 = {"@loggers": "spacy.LookupLogger.v1", "patterns": ["^[pP]ytorch"]} +``` + +| Name | Type | Description | +| ---------- | ----------- | ---------------------------------------------------------------------------------------------------- | +| `patterns` | `List[str]` | A list of regular expressions. If a statistic's name matches one of these, it's printed to `stdout`. | + +## Bug reports and other issues + +Please use [spaCy's issue tracker](https://github.com/explosion/spaCy/issues) to report a bug, or open a new thread on the +[discussion board](https://github.com/explosion/spaCy/discussions) +for any other issue. diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/spacy_loggers-1.0.5.dist-info/RECORD b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/spacy_loggers-1.0.5.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..9c3628726dce93e46162e5e62d546b1dd05d6635 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/spacy_loggers-1.0.5.dist-info/RECORD @@ -0,0 +1,38 @@ +spacy_loggers-1.0.5.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +spacy_loggers-1.0.5.dist-info/LICENSE,sha256=lUN_KcVXfUPlCgxqW250tVmE5BZh0eQ-Msuvo8pVcJk,1073 +spacy_loggers-1.0.5.dist-info/METADATA,sha256=GKCRyRhqBLyQMoWf0q0_hTEB6-Wqv_BmOR8OWE5pK3M,23074 +spacy_loggers-1.0.5.dist-info/RECORD,, +spacy_loggers-1.0.5.dist-info/WHEEL,sha256=yQN5g4mg4AybRjkgi-9yy4iQEFibGQmlz78Pik5Or-A,92 +spacy_loggers-1.0.5.dist-info/entry_points.txt,sha256=w-yZoxYqVnO7gVVm_md_lf5vq0M2YNWRrbHwiWzAlH0,807 +spacy_loggers-1.0.5.dist-info/top_level.txt,sha256=PpevRlpPD_JIAOOwxodbgv8OmKh68L8kOwjTRC2Yfp0,14 +spacy_loggers-1.0.5.dist-info/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1 +spacy_loggers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +spacy_loggers/__pycache__/__init__.cpython-310.pyc,, +spacy_loggers/__pycache__/chain.cpython-310.pyc,, +spacy_loggers/__pycache__/clearml.cpython-310.pyc,, +spacy_loggers/__pycache__/cupy.cpython-310.pyc,, +spacy_loggers/__pycache__/lookup.cpython-310.pyc,, +spacy_loggers/__pycache__/mlflow.cpython-310.pyc,, +spacy_loggers/__pycache__/pytorch.cpython-310.pyc,, +spacy_loggers/__pycache__/util.cpython-310.pyc,, +spacy_loggers/__pycache__/wandb.cpython-310.pyc,, +spacy_loggers/chain.py,sha256=WDDhPK0dcD6J1oDlMymPbSTXqLX-G6dZzPMZAI-e9tA,1499 +spacy_loggers/clearml.py,sha256=oO6nKQgaoX3pBhVXfRcAVESy7MfbHd-7gFlk2EtnTnU,11524 +spacy_loggers/cupy.py,sha256=t67Xo916h6a5wSFQj_beT6Fjahp8MrqTFkF8Re49gCc,2482 +spacy_loggers/lookup.py,sha256=Zqh7xc6s6p6eGL3JVWqD6n4Y_oCSw5KjSnfz3eKfKaM,950 +spacy_loggers/mlflow.py,sha256=KZrguHKE_UmgUssO2FlZ19vCFAGLCq1nkZI_fwdD9e8,7914 +spacy_loggers/pytorch.py,sha256=XGiDVGKLoBvT0GqB67A9-FcIiNEk226KlS1HaPemZC8,2961 +spacy_loggers/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +spacy_loggers/tests/__pycache__/__init__.cpython-310.pyc,, +spacy_loggers/tests/__pycache__/test_chain.cpython-310.pyc,, +spacy_loggers/tests/__pycache__/test_cupy.cpython-310.pyc,, +spacy_loggers/tests/__pycache__/test_lookup.cpython-310.pyc,, +spacy_loggers/tests/__pycache__/test_registry.cpython-310.pyc,, +spacy_loggers/tests/__pycache__/util.cpython-310.pyc,, +spacy_loggers/tests/test_chain.py,sha256=dhGTHzGbGqXwD20VwRImLqDOyw-DLc9PodSw5tMe3pI,873 +spacy_loggers/tests/test_cupy.py,sha256=yMtJ0QIv2egNC4MGP0ob4HozoT4cywIlqzL86anKduE,1235 +spacy_loggers/tests/test_lookup.py,sha256=CiwqsziqHlfUFxHIxMEgiUuEPABrKuEQPMplFIV3WSA,1808 +spacy_loggers/tests/test_registry.py,sha256=kL_gc2i2vy3qxTfVJotIng3NlGSAH73Y8ZfEBkc8Zmk,789 +spacy_loggers/tests/util.py,sha256=s3t25fO1YzJCSH8ZnlrRa10CMHs9e-qtmpsuws0SqlY,548 +spacy_loggers/util.py,sha256=oi1Ub8-TTo9ofv6hpwWNm7KtQxpsgB_1anILbLSkOgA,2714 +spacy_loggers/wandb.py,sha256=Qp8Xc2sunCsy3pIXYycNl2VpF5lLYkpbcNEoh_JLRR8,15879 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/spacy_loggers-1.0.5.dist-info/WHEEL b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/spacy_loggers-1.0.5.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..7e688737d490be3643d705bc16b5a77f7bd567b7 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/spacy_loggers-1.0.5.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.41.2) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/spacy_loggers-1.0.5.dist-info/entry_points.txt b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/spacy_loggers-1.0.5.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..e3f78fdc84103c8ee5c6d911b80488057ee99731 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/spacy_loggers-1.0.5.dist-info/entry_points.txt @@ -0,0 +1,14 @@ +[spacy_loggers] +spacy.ChainLogger.v1 = spacy_loggers.chain:chain_logger_v1 +spacy.ClearMLLogger.v1 = spacy_loggers.clearml:clearml_logger_v1 +spacy.ClearMLLogger.v2 = spacy_loggers.clearml:clearml_logger_v2 +spacy.CupyLogger.v1 = spacy_loggers.cupy:cupy_logger_v1 +spacy.LookupLogger.v1 = spacy_loggers.lookup:lookup_logger_v1 +spacy.MLflowLogger.v1 = spacy_loggers.mlflow:mlflow_logger_v1 +spacy.MLflowLogger.v2 = spacy_loggers.mlflow:mlflow_logger_v2 +spacy.PyTorchLogger.v1 = spacy_loggers.pytorch:pytorch_logger_v1 +spacy.WandbLogger.v1 = spacy_loggers.wandb:wandb_logger_v1 +spacy.WandbLogger.v2 = spacy_loggers.wandb:wandb_logger_v2 +spacy.WandbLogger.v3 = spacy_loggers.wandb:wandb_logger_v3 +spacy.WandbLogger.v4 = spacy_loggers.wandb:wandb_logger_v4 +spacy.WandbLogger.v5 = spacy_loggers.wandb:wandb_logger_v5 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/spacy_loggers-1.0.5.dist-info/top_level.txt b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/spacy_loggers-1.0.5.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..f1f3035302caa329d68d4749dd7a6e3821fe697d --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/spacy_loggers-1.0.5.dist-info/top_level.txt @@ -0,0 +1 @@ +spacy_loggers diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/spacy_loggers-1.0.5.dist-info/zip-safe b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/spacy_loggers-1.0.5.dist-info/zip-safe new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/spacy_loggers-1.0.5.dist-info/zip-safe @@ -0,0 +1 @@ + diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/srsly-2.5.3.dist-info/INSTALLER b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/srsly-2.5.3.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/srsly-2.5.3.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/srsly-2.5.3.dist-info/METADATA b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/srsly-2.5.3.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..ae5827ff161c63af55c5402206e343aa7dc502bf --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/srsly-2.5.3.dist-info/METADATA @@ -0,0 +1,473 @@ +Metadata-Version: 2.4 +Name: srsly +Version: 2.5.3 +Summary: Modern high-performance serialization utilities for Python +Home-page: https://github.com/explosion/srsly +Author: Explosion +Author-email: contact@explosion.ai +License: MIT +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Console +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Science/Research +Classifier: License :: OSI Approved :: MIT License +Classifier: Operating System :: POSIX :: Linux +Classifier: Operating System :: MacOS :: MacOS X +Classifier: Operating System :: Microsoft :: Windows +Classifier: Programming Language :: Cython +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 :: Scientific/Engineering +Requires-Python: <3.15,>=3.9 +Description-Content-Type: text/markdown +License-File: LICENSE +Requires-Dist: catalogue<2.1.0,>=2.0.3 +Dynamic: license-file + + + +# srsly: Modern high-performance serialization utilities for Python + +This package bundles some of the best Python serialization libraries into one +standalone package, with a high-level API that makes it easy to write code +that's correct across platforms and Pythons. This allows us to provide all the +serialization utilities we need in a single binary wheel. Currently supports +**JSON**, **JSONL**, **MessagePack**, **Pickle** and **YAML**. + +[![tests](https://github.com/explosion/srsly/actions/workflows/tests.yml/badge.svg)](https://github.com/explosion/srsly/actions/workflows/tests.yml) +[![PyPi](https://img.shields.io/pypi/v/srsly.svg?style=flat-square&logo=pypi&logoColor=white)](https://pypi.python.org/pypi/srsly) +[![conda](https://img.shields.io/conda/vn/conda-forge/srsly.svg?style=flat-square&logo=conda-forge&logoColor=white)](https://anaconda.org/conda-forge/srsly) +[![GitHub](https://img.shields.io/github/release/explosion/srsly/all.svg?style=flat-square&logo=github)](https://github.com/explosion/srsly) +[![Python wheels](https://img.shields.io/badge/wheels-%E2%9C%93-4c1.svg?longCache=true&style=flat-square&logo=python&logoColor=white)](https://github.com/explosion/wheelwright/releases) + +## Motivation + +Serialization is hard, especially across Python versions and multiple platforms. +After dealing with many subtle bugs over the years (encodings, locales, large +files) our libraries like [spaCy](https://github.com/explosion/spaCy) and +[Prodigy](https://prodi.gy) had steadily grown a number of utility functions to +wrap the multiple serialization formats we need to support (especially `json`, +`msgpack` and `pickle`). These wrapping functions ended up duplicated across our +codebases, so we wanted to put them in one place. + +At the same time, we noticed that having a lot of small dependencies was making +maintenance harder, and making installation slower. To solve this, we've made +`srsly` standalone, by including the component packages directly within it. This +way we can provide all the serialization utilities we need in a single binary +wheel. + +`srsly` currently includes forks of the following packages: + +- [`ujson`](https://github.com/esnme/ultrajson) +- [`msgpack`](https://github.com/msgpack/msgpack-python) +- [`msgpack-numpy`](https://github.com/lebedov/msgpack-numpy) +- [`cloudpickle`](https://github.com/cloudpipe/cloudpickle) +- [`ruamel.yaml`](https://github.com/pycontribs/ruamel-yaml) (without unsafe + implementations!) + +## Installation + +> ⚠️ Note that `v2.x` is only compatible with **Python 3.6+**. For 2.7+ +> compatibility, use `v1.x`. + +`srsly` can be installed from pip. Before installing, make sure that your `pip`, +`setuptools` and `wheel` are up to date. + +```bash +python -m pip install -U pip setuptools wheel +python -m pip install srsly +``` + +Or from conda via conda-forge: + +```bash +conda install -c conda-forge srsly +``` + +Alternatively, you can also compile the library from source. You'll need to make +sure that you have a development environment with a Python distribution +including header files, a compiler (XCode command-line tools on macOS / OS X or +Visual C++ build tools on Windows), pip and git installed. + +Install from source: + +```bash +# clone the repo +git clone https://github.com/explosion/srsly +cd srsly + +# create a virtual environment +python -m venv .env +source .env/bin/activate + +# update pip +python -m pip install -U pip setuptools wheel + +# compile and install from source +python -m pip install . +``` + +For developers, install requirements separately and then install in editable +mode without build isolation: + +```bash +# install in editable mode +python -m pip install -r requirements.txt +python -m pip install --no-build-isolation --editable . + +# run test suite +python -m pytest --pyargs srsly +``` + +## API + +### JSON + +> 📦 The underlying module is exposed via `srsly.ujson`. However, we normally +> interact with it via the utility functions only. + +#### function `srsly.json_dumps` + +Serialize an object to a JSON string. Falls back to `json` if `sort_keys=True` +is used (until it's fixed in `ujson`). + +```python +data = {"foo": "bar", "baz": 123} +json_string = srsly.json_dumps(data) +``` + +| Argument | Type | Description | +| ----------- | ---- | ------------------------------------------------------ | +| `data` | - | The JSON-serializable data to output. | +| `indent` | int | Number of spaces used to indent JSON. Defaults to `0`. | +| `sort_keys` | bool | Sort dictionary keys. Defaults to `False`. | +| **RETURNS** | str | The serialized string. | + +#### function `srsly.json_loads` + +Deserialize unicode or bytes to a Python object. + +```python +data = '{"foo": "bar", "baz": 123}' +obj = srsly.json_loads(data) +``` + +| Argument | Type | Description | +| ----------- | ----------- | ------------------------------- | +| `data` | str / bytes | The data to deserialize. | +| **RETURNS** | - | The deserialized Python object. | + +#### function `srsly.write_json` + +Create a JSON file and dump contents or write to standard output. + +```python +data = {"foo": "bar", "baz": 123} +srsly.write_json("/path/to/file.json", data) +``` + +| Argument | Type | Description | +| -------- | ------------ | ------------------------------------------------------ | +| `path` | str / `Path` | The file path or `"-"` to write to stdout. | +| `data` | - | The JSON-serializable data to output. | +| `indent` | int | Number of spaces used to indent JSON. Defaults to `2`. | + +#### function `srsly.read_json` + +Load JSON from a file or standard input. + +```python +data = srsly.read_json("/path/to/file.json") +``` + +| Argument | Type | Description | +| ----------- | ------------ | ------------------------------------------ | +| `path` | str / `Path` | The file path or `"-"` to read from stdin. | +| **RETURNS** | dict / list | The loaded JSON content. | + +#### function `srsly.write_gzip_json` + +Create a gzipped JSON file and dump contents. + +```python +data = {"foo": "bar", "baz": 123} +srsly.write_gzip_json("/path/to/file.json.gz", data) +``` + +| Argument | Type | Description | +| -------- | ------------ | ------------------------------------------------------ | +| `path` | str / `Path` | The file path. | +| `data` | - | The JSON-serializable data to output. | +| `indent` | int | Number of spaces used to indent JSON. Defaults to `2`. | + +#### function `srsly.write_gzip_jsonl` + +Create a gzipped JSONL file and dump contents. + +```python +data = [{"foo": "bar"}, {"baz": 123}] +srsly.write_gzip_json("/path/to/file.jsonl.gz", data) +``` + +| Argument | Type | Description | +| ----------------- | ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `path` | str / `Path` | The file path. | +| `lines` | - | The JSON-serializable contents of each line. | +| `append` | bool | Whether or not to append to the location. Appending to .gz files is generally not recommended, as it doesn't allow the algorithm to take advantage of all data when compressing - files may hence be poorly compressed. | +| `append_new_line` | bool | Whether or not to write a new line before appending to the file. | + +#### function `srsly.read_gzip_json` + +Load gzipped JSON from a file. + +```python +data = srsly.read_gzip_json("/path/to/file.json.gz") +``` + +| Argument | Type | Description | +| ----------- | ------------ | ------------------------ | +| `path` | str / `Path` | The file path. | +| **RETURNS** | dict / list | The loaded JSON content. | + +#### function `srsly.read_gzip_jsonl` + +Load gzipped JSONL from a file. + +```python +data = srsly.read_gzip_jsonl("/path/to/file.jsonl.gz") +``` + +| Argument | Type | Description | +| ----------- | ------------ | ------------------------- | +| `path` | str / `Path` | The file path. | +| **RETURNS** | dict / list | The loaded JSONL content. | + +#### function `srsly.write_jsonl` + +Create a JSONL file (newline-delimited JSON) and dump contents line by line, or +write to standard output. + +```python +data = [{"foo": "bar"}, {"baz": 123}] +srsly.write_jsonl("/path/to/file.jsonl", data) +``` + +| Argument | Type | Description | +| ----------------- | ------------ | ---------------------------------------------------------------------------------------------------------------------- | +| `path` | str / `Path` | The file path or `"-"` to write to stdout. | +| `lines` | iterable | The JSON-serializable lines. | +| `append` | bool | Append to an existing file. Will open it in `"a"` mode and insert a newline before writing lines. Defaults to `False`. | +| `append_new_line` | bool | Defines whether a new line should first be written when appending to an existing file. Defaults to `True`. | + +#### function `srsly.read_jsonl` + +Read a JSONL file (newline-delimited JSON) or from JSONL data from standard +input and yield contents line by line. Blank lines will always be skipped. + +```python +data = srsly.read_jsonl("/path/to/file.jsonl") +``` + +| Argument | Type | Description | +| ---------- | ---------- | -------------------------------------------------------------------- | +| `path` | str / Path | The file path or `"-"` to read from stdin. | +| `skip` | bool | Skip broken lines and don't raise `ValueError`. Defaults to `False`. | +| **YIELDS** | - | The loaded JSON contents of each line. | + +#### function `srsly.is_json_serializable` + +Check if a Python object is JSON-serializable. + +```python +assert srsly.is_json_serializable({"hello": "world"}) is True +assert srsly.is_json_serializable(lambda x: x) is False +``` + +| Argument | Type | Description | +| ----------- | ---- | ---------------------------------------- | +| `obj` | - | The object to check. | +| **RETURNS** | bool | Whether the object is JSON-serializable. | + +### msgpack + +> 📦 The underlying module is exposed via `srsly.msgpack`. However, we normally +> interact with it via the utility functions only. + +#### function `srsly.msgpack_dumps` + +Serialize an object to a msgpack byte string. + +```python +data = {"foo": "bar", "baz": 123} +msg = srsly.msgpack_dumps(data) +``` + +| Argument | Type | Description | +| ----------- | ----- | ---------------------- | +| `data` | - | The data to serialize. | +| **RETURNS** | bytes | The serialized bytes. | + +#### function `srsly.msgpack_loads` + +Deserialize msgpack bytes to a Python object. + +```python +msg = b"\x82\xa3foo\xa3bar\xa3baz{" +data = srsly.msgpack_loads(msg) +``` + +| Argument | Type | Description | +| ----------- | ----- | --------------------------------------------------------------------------------------- | +| `data` | bytes | The data to deserialize. | +| `use_list` | bool | Don't use tuples instead of lists. Can make deserialization slower. Defaults to `True`. | +| **RETURNS** | - | The deserialized Python object. | + +#### function `srsly.write_msgpack` + +Create a msgpack file and dump contents. + +```python +data = {"foo": "bar", "baz": 123} +srsly.write_msgpack("/path/to/file.msg", data) +``` + +| Argument | Type | Description | +| -------- | ------------ | ---------------------- | +| `path` | str / `Path` | The file path. | +| `data` | - | The data to serialize. | + +#### function `srsly.read_msgpack` + +Load a msgpack file. + +```python +data = srsly.read_msgpack("/path/to/file.msg") +``` + +| Argument | Type | Description | +| ----------- | ------------ | --------------------------------------------------------------------------------------- | +| `path` | str / `Path` | The file path. | +| `use_list` | bool | Don't use tuples instead of lists. Can make deserialization slower. Defaults to `True`. | +| **RETURNS** | - | The loaded and deserialized content. | + +### pickle + +> 📦 The underlying module is exposed via `srsly.cloudpickle`. However, we +> normally interact with it via the utility functions only. + +#### function `srsly.pickle_dumps` + +Serialize a Python object with pickle. + +```python +data = {"foo": "bar", "baz": 123} +pickled_data = srsly.pickle_dumps(data) +``` + +| Argument | Type | Description | +| ----------- | ----- | ------------------------------------------------------ | +| `data` | - | The object to serialize. | +| `protocol` | int | Protocol to use. `-1` for highest. Defaults to `None`. | +| **RETURNS** | bytes | The serialized object. | + +#### function `srsly.pickle_loads` + +Deserialize bytes with pickle. + +```python +pickled_data = b"\x80\x04\x95\x19\x00\x00\x00\x00\x00\x00\x00}\x94(\x8c\x03foo\x94\x8c\x03bar\x94\x8c\x03baz\x94K{u." +data = srsly.pickle_loads(pickled_data) +``` + +| Argument | Type | Description | +| ----------- | ----- | ------------------------------- | +| `data` | bytes | The data to deserialize. | +| **RETURNS** | - | The deserialized Python object. | + +### YAML + +> 📦 The underlying module is exposed via `srsly.ruamel_yaml`. However, we +> normally interact with it via the utility functions only. + +#### function `srsly.yaml_dumps` + +Serialize an object to a YAML string. See the +[`ruamel.yaml` docs](https://yaml.readthedocs.io/en/latest/detail.html?highlight=indentation#indentation-of-block-sequences) +for details on the indentation format. + +```python +data = {"foo": "bar", "baz": 123} +yaml_string = srsly.yaml_dumps(data) +``` + +| Argument | Type | Description | +| ----------------- | ---- | ------------------------------------------ | +| `data` | - | The JSON-serializable data to output. | +| `indent_mapping` | int | Mapping indentation. Defaults to `2`. | +| `indent_sequence` | int | Sequence indentation. Defaults to `4`. | +| `indent_offset` | int | Indentation offset. Defaults to `2`. | +| `sort_keys` | bool | Sort dictionary keys. Defaults to `False`. | +| **RETURNS** | str | The serialized string. | + +#### function `srsly.yaml_loads` + +Deserialize unicode or a file object to a Python object. + +```python +data = 'foo: bar\nbaz: 123' +obj = srsly.yaml_loads(data) +``` + +| Argument | Type | Description | +| ----------- | ---------- | ------------------------------- | +| `data` | str / file | The data to deserialize. | +| **RETURNS** | - | The deserialized Python object. | + +#### function `srsly.write_yaml` + +Create a YAML file and dump contents or write to standard output. + +```python +data = {"foo": "bar", "baz": 123} +srsly.write_yaml("/path/to/file.yml", data) +``` + +| Argument | Type | Description | +| ----------------- | ------------ | ------------------------------------------ | +| `path` | str / `Path` | The file path or `"-"` to write to stdout. | +| `data` | - | The JSON-serializable data to output. | +| `indent_mapping` | int | Mapping indentation. Defaults to `2`. | +| `indent_sequence` | int | Sequence indentation. Defaults to `4`. | +| `indent_offset` | int | Indentation offset. Defaults to `2`. | +| `sort_keys` | bool | Sort dictionary keys. Defaults to `False`. | + +#### function `srsly.read_yaml` + +Load YAML from a file or standard input. + +```python +data = srsly.read_yaml("/path/to/file.yml") +``` + +| Argument | Type | Description | +| ----------- | ------------ | ------------------------------------------ | +| `path` | str / `Path` | The file path or `"-"` to read from stdin. | +| **RETURNS** | dict / list | The loaded YAML content. | + +#### function `srsly.is_yaml_serializable` + +Check if a Python object is YAML-serializable. + +```python +assert srsly.is_yaml_serializable({"hello": "world"}) is True +assert srsly.is_yaml_serializable(lambda x: x) is False +``` + +| Argument | Type | Description | +| ----------- | ---- | ---------------------------------------- | +| `obj` | - | The object to check. | +| **RETURNS** | bool | Whether the object is YAML-serializable. | diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/srsly-2.5.3.dist-info/RECORD b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/srsly-2.5.3.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..cb5b84289c91e415ff7dc580b18f5b20700d95b7 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/srsly-2.5.3.dist-info/RECORD @@ -0,0 +1,258 @@ +srsly-2.5.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +srsly-2.5.3.dist-info/METADATA,sha256=mCDZrv8TlHJCEc5c_0WxIhYKE_SIjN8j8RrPKKh7lNM,19980 +srsly-2.5.3.dist-info/RECORD,, +srsly-2.5.3.dist-info/WHEEL,sha256=z48LxuTeK5nbqpjIHt5Mb8KFWfjfuywypx8NoDND-HE,151 +srsly-2.5.3.dist-info/entry_points.txt,sha256=egiO6704NBZxNhIz96v_ihXL0C3wRZztCqfc3MN4Vyc,172 +srsly-2.5.3.dist-info/licenses/LICENSE,sha256=bJ6SkctoVXngWj92x3bMXe4evYnWgjuT1fh1uW5OXxE,1103 +srsly-2.5.3.dist-info/top_level.txt,sha256=TXhaztKWFjuGKlTFNJcSwDQkYN0ELHqohBa9ArpK0uI,6 +srsly-2.5.3.dist-info/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1 +srsly/__init__.py,sha256=A60Csk04xjHruVgW4eUNxMwfFdE68a6hauTQkxRhnxU,591 +srsly/__pycache__/__init__.cpython-310.pyc,, +srsly/__pycache__/_json_api.cpython-310.pyc,, +srsly/__pycache__/_msgpack_api.cpython-310.pyc,, +srsly/__pycache__/_pickle_api.cpython-310.pyc,, +srsly/__pycache__/_yaml_api.cpython-310.pyc,, +srsly/__pycache__/about.cpython-310.pyc,, +srsly/__pycache__/util.cpython-310.pyc,, +srsly/_json_api.py,sha256=iCcvHnrTZz83LSgRUUldZsPjtWw4TBja3e8_pQhEdHs,7068 +srsly/_msgpack_api.py,sha256=sSl0rw5C6Y45WPP1a9waHofPTid9dauK3BI_oce5-ls,1855 +srsly/_pickle_api.py,sha256=EVWsikoVdG75WO9VWPwpKeUehjdLeOZ9PXgOywhkOWQ,631 +srsly/_yaml_api.py,sha256=Gc3EEi--S39HP7DSPah-gRXsBDcsC4KFZUtsye10f4o,3773 +srsly/about.py,sha256=9As6EseYF3Vi8VWUZnZuuTi-kW5fYIv8u6cHK0RidGo,22 +srsly/cloudpickle/__init__.py,sha256=ErKyvqqAErOkbCowrizhGpN9DN-TaD22QtqI9CQ9sDw,308 +srsly/cloudpickle/__pycache__/__init__.cpython-310.pyc,, +srsly/cloudpickle/__pycache__/cloudpickle.cpython-310.pyc,, +srsly/cloudpickle/__pycache__/cloudpickle_fast.cpython-310.pyc,, +srsly/cloudpickle/cloudpickle.py,sha256=KcLA_uAxp2KuMJb9vaTVve7FLFUQu7mYkD3dCscxeRc,58874 +srsly/cloudpickle/cloudpickle_fast.py,sha256=AI5ZKf2AbLNxD8lXyLDpKZyzeZ2ofFtdK1ZWFq_ec1c,323 +srsly/msgpack/__init__.py,sha256=aVX2zoRR2sNNkYa6wqGtJYJh6_s-JDaAemyp-6g72uY,2772 +srsly/msgpack/__pycache__/__init__.cpython-310.pyc,, +srsly/msgpack/__pycache__/_msgpack_numpy.cpython-310.pyc,, +srsly/msgpack/__pycache__/_version.cpython-310.pyc,, +srsly/msgpack/__pycache__/exceptions.cpython-310.pyc,, +srsly/msgpack/__pycache__/ext.cpython-310.pyc,, +srsly/msgpack/__pycache__/fallback.cpython-310.pyc,, +srsly/msgpack/__pycache__/util.cpython-310.pyc,, +srsly/msgpack/_epoch.cpp,sha256=BVkoFaOCiUCEhQe0rwlkghdZCSe5xirFJB6QehZN6ys,278400 +srsly/msgpack/_epoch.cpython-310-x86_64-linux-gnu.so,sha256=QJO-40xCPT0yedYJMG_Y8RjebuWwg0H9msPFCIS_Z48,110032 +srsly/msgpack/_epoch.pyx,sha256=quvB_NUUtLdV8w-mX7PKzSgmI-5fvWwNOi6Qq4bCiA0,177 +srsly/msgpack/_msgpack_numpy.py,sha256=X3Q2V-Yzo-DsW6fKwWC7YGR_lqilrAixoLE_t7NCxbM,2717 +srsly/msgpack/_packer.cpp,sha256=VUhIrs3Nr-AWVj1CXZzVa-Sf2k4CdpbfSjad4HcD5ZA,770945 +srsly/msgpack/_packer.cpython-310-x86_64-linux-gnu.so,sha256=81hvCKCd2_-tLFPCqk03hxaXJyEuHHrjWvQZf5aO6-U,791568 +srsly/msgpack/_packer.pyx,sha256=RXc02LfKi4J4Z60E7gzwJE-U1WWctgwKtXOjui0dKHk,14069 +srsly/msgpack/_unpacker.cpp,sha256=qIO0trdZJtp4XLm5epMGpeInmlqGvE5GOidmqwx98jM,668057 +srsly/msgpack/_unpacker.cpython-310-x86_64-linux-gnu.so,sha256=SAPILoDXLqbIDOEGBFUZ8P7hv7O7MUfkmPFXpRTL5rs,697832 +srsly/msgpack/_unpacker.pyx,sha256=yzGuU9A6vWg0_mKDWlohwGjEf96hJwuRiIbBhlpz7Vw,19314 +srsly/msgpack/_version.py,sha256=9om2f77xxKuOFtAaSR8nFqLRyPvPKOO2kFxGnQmhixg,20 +srsly/msgpack/exceptions.py,sha256=dCTWei8dpkrMsQDcjQk74ATl9HsIBH0ybt8zOPNqMYc,1081 +srsly/msgpack/ext.py,sha256=kteJv03n9tYzd5oo3xYopVTo4vRaAxonBQQJhXohZZo,5726 +srsly/msgpack/fallback.py,sha256=0g1Pzp0vtmBEmJ5w9F3s_-JMVURP8RS4G1cc5TRaAsI,32390 +srsly/msgpack/pack.h,sha256=O3DpdfO4bYbrSfIbwE2lP4spXjmYLryFsFEEnM1EP0c,1653 +srsly/msgpack/pack_template.h,sha256=lfcznrkgf5ItCVq6qbmKOkXrZs_7ucTnwVPUW34vnK0,16762 +srsly/msgpack/sysdep.h,sha256=g0Be20rldEx2yZHY-s7eFtzx7dZlnognCutLNL2Cys8,6452 +srsly/msgpack/unpack.h,sha256=bUoDSrA2AHByUVBdYMqGFUChJXw27AMVGnPoR4qkkkM,11105 +srsly/msgpack/unpack_container_header.h,sha256=AuN5sWGsolVflhIuHFcSl6iVIvI9gZkpLHFjCezCHQo,1379 +srsly/msgpack/unpack_define.h,sha256=ebuKljj6t2eb7UVM-cl6cr2l0oK0PcMx3l7Zhqq6wEQ,2366 +srsly/msgpack/unpack_template.h,sha256=NRNSJE9ikdsHaSPeCpo1QgvA1FAQmfpCpbNpfgr6_wM,13722 +srsly/msgpack/util.py,sha256=aKP4WukOwuUY1wxPHtZf7Dyr7Wj0I3H-3Zh721pwQkI,301 +srsly/ruamel_yaml/__init__.py,sha256=CryTaULKl5uwAP0ZB5i8h3BTbBavmzBheVICTM2S2u0,104 +srsly/ruamel_yaml/__pycache__/__init__.cpython-310.pyc,, +srsly/ruamel_yaml/__pycache__/anchor.cpython-310.pyc,, +srsly/ruamel_yaml/__pycache__/comments.cpython-310.pyc,, +srsly/ruamel_yaml/__pycache__/compat.cpython-310.pyc,, +srsly/ruamel_yaml/__pycache__/composer.cpython-310.pyc,, +srsly/ruamel_yaml/__pycache__/configobjwalker.cpython-310.pyc,, +srsly/ruamel_yaml/__pycache__/constructor.cpython-310.pyc,, +srsly/ruamel_yaml/__pycache__/cyaml.cpython-310.pyc,, +srsly/ruamel_yaml/__pycache__/dumper.cpython-310.pyc,, +srsly/ruamel_yaml/__pycache__/emitter.cpython-310.pyc,, +srsly/ruamel_yaml/__pycache__/error.cpython-310.pyc,, +srsly/ruamel_yaml/__pycache__/events.cpython-310.pyc,, +srsly/ruamel_yaml/__pycache__/loader.cpython-310.pyc,, +srsly/ruamel_yaml/__pycache__/main.cpython-310.pyc,, +srsly/ruamel_yaml/__pycache__/nodes.cpython-310.pyc,, +srsly/ruamel_yaml/__pycache__/parser.cpython-310.pyc,, +srsly/ruamel_yaml/__pycache__/reader.cpython-310.pyc,, +srsly/ruamel_yaml/__pycache__/representer.cpython-310.pyc,, +srsly/ruamel_yaml/__pycache__/resolver.cpython-310.pyc,, +srsly/ruamel_yaml/__pycache__/scalarbool.cpython-310.pyc,, +srsly/ruamel_yaml/__pycache__/scalarfloat.cpython-310.pyc,, +srsly/ruamel_yaml/__pycache__/scalarint.cpython-310.pyc,, +srsly/ruamel_yaml/__pycache__/scalarstring.cpython-310.pyc,, +srsly/ruamel_yaml/__pycache__/scanner.cpython-310.pyc,, +srsly/ruamel_yaml/__pycache__/serializer.cpython-310.pyc,, +srsly/ruamel_yaml/__pycache__/timestamp.cpython-310.pyc,, +srsly/ruamel_yaml/__pycache__/tokens.cpython-310.pyc,, +srsly/ruamel_yaml/__pycache__/util.cpython-310.pyc,, +srsly/ruamel_yaml/anchor.py,sha256=d0FhKTzeeUdNM0legCHMtDr7edkZi-e2JjK0Jy6rAhY,501 +srsly/ruamel_yaml/comments.py,sha256=Edl6m8LIDlY58F3i-Eo5s40MZmPz9NOZRTErIyLgXzE,35006 +srsly/ruamel_yaml/compat.py,sha256=QuzIRFsDXAHNKfoZj3_4utlPxs_skF08_RgKX8Nfu6g,8594 +srsly/ruamel_yaml/composer.py,sha256=MnKbBgb9HL9cnFscysjFcs5rhNiaGO7tMuKa7E4-2ek,8355 +srsly/ruamel_yaml/configobjwalker.py,sha256=K3mRlfJHvshPjLytvJ507FcO7MH7ZoVbMzBdg_ziyBw,351 +srsly/ruamel_yaml/constructor.py,sha256=oS5cGHfSGZpBKocr-tdOM6tyFATXIHNMdI0Gr2FJbvA,64802 +srsly/ruamel_yaml/cyaml.py,sha256=PlmS1MIsZRbEtmJS74iNb0V514FlecVW5SPx5O45IGM,6567 +srsly/ruamel_yaml/dumper.py,sha256=MFGRVwjDwuItg9OBC3-XWbG6hoWCvOfZkVQgFZcl8CA,6570 +srsly/ruamel_yaml/emitter.py,sha256=x0zGkmxxxwVe01DeSD5V8DNqj-OHUf6Z4E7_wJecZOc,64676 +srsly/ruamel_yaml/error.py,sha256=Q7c3n6iz_yKjzY9pyHuV_MMaonT5HvBI_cYmU045RfY,9104 +srsly/ruamel_yaml/events.py,sha256=0WBCPgpFzv4MKDN7ijApePTP58bxzTNM7Me1Hi0HA8g,3902 +srsly/ruamel_yaml/loader.py,sha256=vJJwRauFV_a38o7umWnsqZpjNdZJp5B0qjHFtbb5vsU,2597 +srsly/ruamel_yaml/main.py,sha256=c55zVN1wvGfEQseKecOetvzT7zfxYogHJ358-ji1br8,53946 +srsly/ruamel_yaml/nodes.py,sha256=KglOPI3ex9RvVCOm7CPtkPkdeYQXKLYbd2Ji_siaDJ0,3716 +srsly/ruamel_yaml/parser.py,sha256=CYk_IUD2UnLPZbWzZ4-9rl5rqLCJiw492OiwRZTOLv0,33818 +srsly/ruamel_yaml/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +srsly/ruamel_yaml/reader.py,sha256=uKca3z6ozdeoIDjy1KWE-023P5MJ5H-stkp_eZ9Ak5M,11177 +srsly/ruamel_yaml/representer.py,sha256=NKZMh-oi8FsJjPFlSuirwb0AOsO8xSY9WiJ-8R7Uft8,49193 +srsly/ruamel_yaml/resolver.py,sha256=yLFaHJHNkTIPrOgCOUZWA8WbzMgaXP8DlmrD4ujc1wI,15456 +srsly/ruamel_yaml/scalarbool.py,sha256=83Vj1BDlYY6KK2woM6lmGkA0PxTPvQLwxg2Xxmml-qY,1520 +srsly/ruamel_yaml/scalarfloat.py,sha256=7b2chxBOSWJqBCSoD8ZFxOQEP5NpK_kDKqWf8rE7H_c,4515 +srsly/ruamel_yaml/scalarint.py,sha256=cAWxr0NXOgU4asNX3IB99_Ot68YZIDFdGtiPAHjS1lY,4681 +srsly/ruamel_yaml/scalarstring.py,sha256=TvNrpBQied0Y5TKHfFp301JhjnKYfPoDn2eMGCOIAJo,4463 +srsly/ruamel_yaml/scanner.py,sha256=VpyLuUi_U19eTe3j85YdDdlk-1jZkrCVKIE8HfBjJJo,72758 +srsly/ruamel_yaml/serializer.py,sha256=CEQl3CjJoUqAoz0DCEOPe7gdhUSYJ42Ppw-lY9M-8L4,8531 +srsly/ruamel_yaml/timestamp.py,sha256=wT7PvcUQ3XU3MlbM3vTd1pMnHn6EnkJvV-WDzr5kat8,939 +srsly/ruamel_yaml/tokens.py,sha256=z1gPCgyz7dhdBdKKK3UPTw_EAwELaPRRExMa9KIV6q8,7471 +srsly/ruamel_yaml/util.py,sha256=XOPF6x5cblVNCGpkj_dC1z1kiBd9o3JMd8boj4R8DrQ,6098 +srsly/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +srsly/tests/__pycache__/__init__.cpython-310.pyc,, +srsly/tests/__pycache__/test_json_api.cpython-310.pyc,, +srsly/tests/__pycache__/test_msgpack_api.cpython-310.pyc,, +srsly/tests/__pycache__/test_pickle_api.cpython-310.pyc,, +srsly/tests/__pycache__/test_yaml_api.cpython-310.pyc,, +srsly/tests/__pycache__/util.cpython-310.pyc,, +srsly/tests/cloudpickle/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +srsly/tests/cloudpickle/__pycache__/__init__.cpython-310.pyc,, +srsly/tests/cloudpickle/__pycache__/cloudpickle_file_test.cpython-310.pyc,, +srsly/tests/cloudpickle/__pycache__/cloudpickle_test.cpython-310.pyc,, +srsly/tests/cloudpickle/__pycache__/testutils.cpython-310.pyc,, +srsly/tests/cloudpickle/cloudpickle_file_test.py,sha256=R2iL8YPAjvOJwi9fKZM1_fEPGtNa6fz9cd4Ivjszgc0,3244 +srsly/tests/cloudpickle/cloudpickle_test.py,sha256=rTkoFwBIAJVW4BElyYsAK4MvIGpazFXHfPtgz87Jd_0,106299 +srsly/tests/cloudpickle/testutils.py,sha256=Gd-LX8hyLLkzSoguZ0LASUMB0FYRdWMFPBuf7qGqX44,7466 +srsly/tests/msgpack/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +srsly/tests/msgpack/__pycache__/__init__.cpython-310.pyc,, +srsly/tests/msgpack/__pycache__/test_buffer.cpython-310.pyc,, +srsly/tests/msgpack/__pycache__/test_case.cpython-310.pyc,, +srsly/tests/msgpack/__pycache__/test_except.cpython-310.pyc,, +srsly/tests/msgpack/__pycache__/test_extension.cpython-310.pyc,, +srsly/tests/msgpack/__pycache__/test_format.cpython-310.pyc,, +srsly/tests/msgpack/__pycache__/test_limits.cpython-310.pyc,, +srsly/tests/msgpack/__pycache__/test_memoryview.cpython-310.pyc,, +srsly/tests/msgpack/__pycache__/test_newspec.cpython-310.pyc,, +srsly/tests/msgpack/__pycache__/test_numpy.cpython-310.pyc,, +srsly/tests/msgpack/__pycache__/test_pack.cpython-310.pyc,, +srsly/tests/msgpack/__pycache__/test_read_size.cpython-310.pyc,, +srsly/tests/msgpack/__pycache__/test_seq.cpython-310.pyc,, +srsly/tests/msgpack/__pycache__/test_sequnpack.cpython-310.pyc,, +srsly/tests/msgpack/__pycache__/test_stricttype.cpython-310.pyc,, +srsly/tests/msgpack/__pycache__/test_subtype.cpython-310.pyc,, +srsly/tests/msgpack/__pycache__/test_unpack.cpython-310.pyc,, +srsly/tests/msgpack/test_buffer.py,sha256=lqXDTcMcGOI1IdKrucw5KqPf_hQR3Mx9DCTShhAyASY,709 +srsly/tests/msgpack/test_case.py,sha256=l7CwcbSVNQ3jt7wZ9nwX00RGsS8Ye2lb9ui4zx_szbM,2846 +srsly/tests/msgpack/test_except.py,sha256=WiQ3diwh374f4RCPtGdSI8nkSmVroKdJNcgViP2S5HM,1682 +srsly/tests/msgpack/test_extension.py,sha256=MX6QyMO9hKlGVvSh79LtPdL9WOKq0vFVoaxhomzCnpY,2569 +srsly/tests/msgpack/test_format.py,sha256=rQOAnl0oAp6KvoKinIeIKnYhdFnuxBqwk-3xgxamB9s,2052 +srsly/tests/msgpack/test_limits.py,sha256=vkDwwoxqtw2alibIgvuW6lNeGiPkdGwBdnQILMoPsiE,3123 +srsly/tests/msgpack/test_memoryview.py,sha256=gj2vwbzEPpzMyUTa8rm5wYXmH-i-zAoPjx6ydv2nh1s,2581 +srsly/tests/msgpack/test_newspec.py,sha256=EE_8RcagOtkfe4Nc5Z3M5UsSawgb993YMAksUDi9oWA,2604 +srsly/tests/msgpack/test_numpy.py,sha256=rdiXlUjMojUn0Q69BeqVKGBHH0ShCVuVw6k05KnV7S8,8609 +srsly/tests/msgpack/test_pack.py,sha256=SjYBJmiSkb3qnQyI6tHJub1AXV7X_JIVoT5bNvHRqNI,5071 +srsly/tests/msgpack/test_read_size.py,sha256=5WjorRXpimFpBkPrKHrDLTjlGgHU7r-oMsty2z-DyAs,1800 +srsly/tests/msgpack/test_seq.py,sha256=6omeg4J5dMbbPj09bqOBo-qoDdwoCFsRhD99_ZY7ITo,1125 +srsly/tests/msgpack/test_sequnpack.py,sha256=cDtl-Iy7jTLmLbMleJ9ZV6W0Z3j8bOnyNWOTGSdjUHc,3632 +srsly/tests/msgpack/test_stricttype.py,sha256=UszJmIhmTovF2TzOkckbcWWQSOg3rKGPyKlHPj2ypmM,1781 +srsly/tests/msgpack/test_subtype.py,sha256=1h66XotqtP_KBRNFS4Xc02JdN87bXsIRWVx1gkGrFXU,375 +srsly/tests/msgpack/test_unpack.py,sha256=hML12x8kIS-3lZUKXJvhrY165jPHfmgWNsfhH1PZga0,1820 +srsly/tests/ruamel_yaml/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +srsly/tests/ruamel_yaml/__pycache__/__init__.cpython-310.pyc,, +srsly/tests/ruamel_yaml/__pycache__/roundtrip.cpython-310.pyc,, +srsly/tests/ruamel_yaml/__pycache__/test_a_dedent.cpython-310.pyc,, +srsly/tests/ruamel_yaml/__pycache__/test_add_xxx.cpython-310.pyc,, +srsly/tests/ruamel_yaml/__pycache__/test_anchor.cpython-310.pyc,, +srsly/tests/ruamel_yaml/__pycache__/test_api_change.cpython-310.pyc,, +srsly/tests/ruamel_yaml/__pycache__/test_appliance.cpython-310.pyc,, +srsly/tests/ruamel_yaml/__pycache__/test_class_register.cpython-310.pyc,, +srsly/tests/ruamel_yaml/__pycache__/test_collections.cpython-310.pyc,, +srsly/tests/ruamel_yaml/__pycache__/test_comment_manipulation.cpython-310.pyc,, +srsly/tests/ruamel_yaml/__pycache__/test_comments.cpython-310.pyc,, +srsly/tests/ruamel_yaml/__pycache__/test_contextmanager.cpython-310.pyc,, +srsly/tests/ruamel_yaml/__pycache__/test_copy.cpython-310.pyc,, +srsly/tests/ruamel_yaml/__pycache__/test_datetime.cpython-310.pyc,, +srsly/tests/ruamel_yaml/__pycache__/test_deprecation.cpython-310.pyc,, +srsly/tests/ruamel_yaml/__pycache__/test_documents.cpython-310.pyc,, +srsly/tests/ruamel_yaml/__pycache__/test_fail.cpython-310.pyc,, +srsly/tests/ruamel_yaml/__pycache__/test_float.cpython-310.pyc,, +srsly/tests/ruamel_yaml/__pycache__/test_flowsequencekey.cpython-310.pyc,, +srsly/tests/ruamel_yaml/__pycache__/test_indentation.cpython-310.pyc,, +srsly/tests/ruamel_yaml/__pycache__/test_int.cpython-310.pyc,, +srsly/tests/ruamel_yaml/__pycache__/test_issues.cpython-310.pyc,, +srsly/tests/ruamel_yaml/__pycache__/test_json_numbers.cpython-310.pyc,, +srsly/tests/ruamel_yaml/__pycache__/test_line_col.cpython-310.pyc,, +srsly/tests/ruamel_yaml/__pycache__/test_literal.cpython-310.pyc,, +srsly/tests/ruamel_yaml/__pycache__/test_none.cpython-310.pyc,, +srsly/tests/ruamel_yaml/__pycache__/test_numpy.cpython-310.pyc,, +srsly/tests/ruamel_yaml/__pycache__/test_program_config.cpython-310.pyc,, +srsly/tests/ruamel_yaml/__pycache__/test_spec_examples.cpython-310.pyc,, +srsly/tests/ruamel_yaml/__pycache__/test_string.cpython-310.pyc,, +srsly/tests/ruamel_yaml/__pycache__/test_tag.cpython-310.pyc,, +srsly/tests/ruamel_yaml/__pycache__/test_version.cpython-310.pyc,, +srsly/tests/ruamel_yaml/__pycache__/test_yamlfile.cpython-310.pyc,, +srsly/tests/ruamel_yaml/__pycache__/test_yamlobject.cpython-310.pyc,, +srsly/tests/ruamel_yaml/__pycache__/test_z_check_debug_leftovers.cpython-310.pyc,, +srsly/tests/ruamel_yaml/__pycache__/test_z_data.cpython-310.pyc,, +srsly/tests/ruamel_yaml/roundtrip.py,sha256=lVo93FYrEqtWEvnb5LfzC7WzLdy8m0V83lVtXUT670A,9490 +srsly/tests/ruamel_yaml/test_a_dedent.py,sha256=jXK3jgkoY9rLIcZ-zCkVf1FQcX3IheVA7sshPOzW-hc,1125 +srsly/tests/ruamel_yaml/test_add_xxx.py,sha256=LD_4RPWIxE2cKLMMyydhRqQmrxiVM7FpRk6LYQkgkB8,5347 +srsly/tests/ruamel_yaml/test_anchor.py,sha256=EQMllNBxDtm9evK9KgUa1GB1vp1F7HR_4IdwNY65Xys,14428 +srsly/tests/ruamel_yaml/test_api_change.py,sha256=Rt636GxMmw3k9fkR5bXSpgDXYjNMZa5yk4U_ka_EaHc,7078 +srsly/tests/ruamel_yaml/test_appliance.py,sha256=3uqi-TjuglUKFwGMA5cNLbarzzRwYPcFs-wsvmn93GU,7680 +srsly/tests/ruamel_yaml/test_class_register.py,sha256=XqlZAcu5dFIPRF547TYcFDF4YdxHwa6O8Q-pDlpHfCk,3340 +srsly/tests/ruamel_yaml/test_collections.py,sha256=J81XgAigeIbQNnmEE80kNweeGfsVmhJ2fH9ERM5pzVw,508 +srsly/tests/ruamel_yaml/test_comment_manipulation.py,sha256=jDLJPdsfzmZCaroJOekATpy1NzA7cYEcO7m1eXDwfCY,14843 +srsly/tests/ruamel_yaml/test_comments.py,sha256=Z4DvoaBB9grqZA48L-t-vHmdFe0RSRV3PuR9uWd_TCg,20553 +srsly/tests/ruamel_yaml/test_contextmanager.py,sha256=9T0T9smirmyBB6-v06fIy7dahopdKgxOlToVxXNoCD0,2804 +srsly/tests/ruamel_yaml/test_copy.py,sha256=dmNw2UG8D1ABjco_1AEXQYbdhE1Q39OmF9wwTAkTmA8,3651 +srsly/tests/ruamel_yaml/test_datetime.py,sha256=lGEX0dj1aR0N---zYr8-LassvFHQHRgxW1_6B2IF0IU,3787 +srsly/tests/ruamel_yaml/test_deprecation.py,sha256=Vffm1sMsSs_ttd4QrCwtpZohtKfVwy44LiGKgWuMC28,353 +srsly/tests/ruamel_yaml/test_documents.py,sha256=jyPg5X2FnH3pjxnp78Zrsfum4MGekOjN-5RLQ7W1EFA,1827 +srsly/tests/ruamel_yaml/test_fail.py,sha256=qt3G2_0RoWcVzq-BOnu2JnHEPku5e-Yi-p5smRDvymo,6290 +srsly/tests/ruamel_yaml/test_float.py,sha256=vjgR7hB9-0wOFLY-V5IbbVCuDLXjScCO5L8alprxxQU,2130 +srsly/tests/ruamel_yaml/test_flowsequencekey.py,sha256=bNHrGCQAv0S7F9QSyhi7OcLij3C3t-g4tLN3zRVfcLo,487 +srsly/tests/ruamel_yaml/test_indentation.py,sha256=bx0PqPw0V2GDhy9s0Z7OONTDHtNBS6VVcHKxheaSVCM,8512 +srsly/tests/ruamel_yaml/test_int.py,sha256=Vzz1WSj3KffPbdc9s1pcM-Bo5BBWVXQxWhLGpH1HYcY,907 +srsly/tests/ruamel_yaml/test_issues.py,sha256=7PA9I_FrYsakVeNmMHBRKlUVKVkh3mK5mgJWx-pPqdo,23713 +srsly/tests/ruamel_yaml/test_json_numbers.py,sha256=kpMkzRoNZ0AAHgJKRcXA0vAsem08qOtCtRssr-CZtwg,1452 +srsly/tests/ruamel_yaml/test_line_col.py,sha256=R-2iT9e9ec6vvdhundgRdy-suVDPe9pqN16rU20Hv2M,2106 +srsly/tests/ruamel_yaml/test_literal.py,sha256=OO6Nq_OCo_Cs3HQFfbGwfxiReK7uPCU2NKD0aSzbNfY,7787 +srsly/tests/ruamel_yaml/test_none.py,sha256=ClKUX2o3ihMmfYBjF-26O7LRAA9omcnO8Os_XLlHVlA,1428 +srsly/tests/ruamel_yaml/test_numpy.py,sha256=RMVi8aV6csU0ta0mHWlHIhwsVCLNjMDitVqrc0rS-PQ,488 +srsly/tests/ruamel_yaml/test_program_config.py,sha256=DO3AZJ_CKUmHgByAdk68voMH6qENYV_-V-Col3fqCWo,1869 +srsly/tests/ruamel_yaml/test_spec_examples.py,sha256=w1aGUnKrMWEP_lZpSLqWXexdTH_K5gErkTG3adkCFqM,5880 +srsly/tests/ruamel_yaml/test_string.py,sha256=rmqika05PwjZ8xWdSNjHpvyKvbdfyA3ZRwaM81oLUiQ,5603 +srsly/tests/ruamel_yaml/test_tag.py,sha256=unM1E7lZOxsBaxPlGOyzajbRtGchbri_66bI7lEYVAA,3619 +srsly/tests/ruamel_yaml/test_version.py,sha256=K-ccl8lAtBa-VjkczEPyA-fIgt8EpHJLNhDaD6nMdY4,4343 +srsly/tests/ruamel_yaml/test_yamlfile.py,sha256=ZcfKZAtrrNrxYHtVeHDPIqbt81Jw-cxt0OJgsu-elBg,5897 +srsly/tests/ruamel_yaml/test_yamlobject.py,sha256=taNz3phS5ilFSYiWpF55U4_N3kzYjMVguCvjygRsSAg,2513 +srsly/tests/ruamel_yaml/test_z_check_debug_leftovers.py,sha256=dEC_k-17XQPV0PlOQArppC1UyaezxUFwYcmwvmYd_m4,891 +srsly/tests/ruamel_yaml/test_z_data.py,sha256=LFsHo62kxPrde_oHpJ8YxNKAO2exYFyaHC0DDV9V6cM,7319 +srsly/tests/test_json_api.py,sha256=VKstntKumY-SsIFw7P5hX10fLg1G00Ckx5vS4TGSC9w,8291 +srsly/tests/test_msgpack_api.py,sha256=LEAJullzmOwVMC534PO0-IzZaaITUukHIPpEhQ5yc_s,3568 +srsly/tests/test_pickle_api.py,sha256=r5UcU2Okn-E0667hSlgd-Q62a9Glgs2BR6l4amCdbMM,870 +srsly/tests/test_yaml_api.py,sha256=ju3c04jz5kbtWZaAZV1d_4biaAKKl9AT9rU2VLjkk6I,3162 +srsly/tests/ujson/334-reproducer.json,sha256=Guo9u9OQM96fuP2LwzEFsyNFmSElvMI3fWFDhAarAnA,29345 +srsly/tests/ujson/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +srsly/tests/ujson/__pycache__/__init__.cpython-310.pyc,, +srsly/tests/ujson/__pycache__/test_ujson.cpython-310.pyc,, +srsly/tests/ujson/test_ujson.py,sha256=DcuP7D-TXJ49uTo8g655iAedxKCBMvc5NB9tv-LkAfw,33468 +srsly/tests/util.py,sha256=ayY3VLP8lZguVw5CMceej11lqbqtkgd2kqIyie73GQY,415 +srsly/ujson/JSONtoObj.c,sha256=eOiP3eeJH1cJd7HVP_Xu7wwwpvACbyJ2L7p7gjRX92M,6361 +srsly/ujson/__init__.py,sha256=HPqaiYSvbbCuYz5KMEQOzxel2GTFF-CDPtzFojkFq90,74 +srsly/ujson/__pycache__/__init__.cpython-310.pyc,, +srsly/ujson/lib/dconv_wrapper.cc,sha256=C3QSOHza_Tme7oyMgcgzvdBr7Nx-STwhQO-NvEkA2UY,2038 +srsly/ujson/lib/ultrajson.h,sha256=tF-PEN4er6SXBTUysD1TUF8lNu4iR4O26CRvJy_tAf0,9792 +srsly/ujson/lib/ultrajsondec.c,sha256=wkpNzKt84e8NyzYjB_db_ES-jDbHOmHklNFntgL-iCE,21708 +srsly/ujson/lib/ultrajsonenc.c,sha256=qXEZxjjZ2sj1XwCi0WIZsUeQsOD62dZOJFIuId7l5t4,26333 +srsly/ujson/objToJSON.c,sha256=XjD4fKf75Qdajex3pw9ORrztJ-8Vc6zpDsTQl2HzwtI,22961 +srsly/ujson/py_defines.h,sha256=aScKErKSk48wdIZYUycFKimFgYsQxzYm3qzKjIzEGoM,2365 +srsly/ujson/ujson.c,sha256=K6P2Nv-hQyRB2MKYQ2CZl3GiIUFlcswU4YqFH0oOmCE,4748 +srsly/ujson/ujson.cpython-310-x86_64-linux-gnu.so,sha256=5Uq1y7f96ckPm3AkK1K2joxb6lQ8KeMdV1p7bSHypik,195712 +srsly/ujson/version.h,sha256=ltVzrB_Kuk2c45Dl-T3xk20rpK219xwx28lbVWqaVuI,1999 +srsly/util.py,sha256=NzAQxdE76AV4NCwbuRvdq77vFaIjf9CRDyBoWxA5xpA,1108 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/srsly-2.5.3.dist-info/WHEEL b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/srsly-2.5.3.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..d15c16833bfa933b4cddb8de281e29ec5f86f021 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/srsly-2.5.3.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: setuptools (82.0.1) +Root-Is-Purelib: false +Tag: cp310-cp310-manylinux_2_17_x86_64 +Tag: cp310-cp310-manylinux2014_x86_64 + diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/srsly-2.5.3.dist-info/entry_points.txt b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/srsly-2.5.3.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..5ddbaa2b8de7dfee21cc72fedcc37adc5ea00d78 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/srsly-2.5.3.dist-info/entry_points.txt @@ -0,0 +1,5 @@ +[spacy_readers] +srsly.read_json.v1 = srsly:read_json +srsly.read_jsonl.v1 = srsly:read_jsonl +srsly.read_msgpack.v1 = srsly:read_msgpack +srsly.read_yaml.v1 = srsly:read_yaml diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/srsly-2.5.3.dist-info/top_level.txt b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/srsly-2.5.3.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..f2bd860d17ddbfaa456ee2d6a78b62c61f572375 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/srsly-2.5.3.dist-info/top_level.txt @@ -0,0 +1 @@ +srsly diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/srsly-2.5.3.dist-info/zip-safe b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/srsly-2.5.3.dist-info/zip-safe new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/srsly-2.5.3.dist-info/zip-safe @@ -0,0 +1 @@ + diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/srsly/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/srsly/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0c94d82bbd75a2607d9851850eb4457133cf640d --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/srsly/__init__.py @@ -0,0 +1,10 @@ +from ._json_api import read_json, read_gzip_json, write_json, write_gzip_json +from ._json_api import read_gzip_jsonl, write_gzip_jsonl +from ._json_api import read_jsonl, write_jsonl +from ._json_api import json_dumps, json_loads, is_json_serializable +from ._msgpack_api import read_msgpack, write_msgpack, msgpack_dumps, msgpack_loads +from ._msgpack_api import msgpack_encoders, msgpack_decoders +from ._pickle_api import pickle_dumps, pickle_loads +from ._yaml_api import read_yaml, write_yaml, yaml_dumps, yaml_loads +from ._yaml_api import is_yaml_serializable +from .about import __version__ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/srsly/_json_api.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/srsly/_json_api.py new file mode 100644 index 0000000000000000000000000000000000000000..24d25fdc81663fbdec8a5ca7cf9bdf7c57633f80 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/srsly/_json_api.py @@ -0,0 +1,209 @@ +from typing import Union, Iterable, Sequence, Any, Optional, Iterator +import sys +import json as _builtin_json +import gzip + +from . import ujson +from .util import force_path, force_string, FilePath, JSONInput, JSONOutput + + +def json_dumps( + data: JSONInput, indent: Optional[int] = 0, sort_keys: bool = False +) -> str: + """Serialize an object to a JSON string. + + data: The JSON-serializable data. + indent (int): Number of spaces used to indent JSON. + sort_keys (bool): Sort dictionary keys. Falls back to json module for now. + RETURNS (str): The serialized string. + """ + if sort_keys: + indent = None if indent == 0 else indent + result = _builtin_json.dumps( + data, indent=indent, separators=(",", ":"), sort_keys=sort_keys + ) + else: + result = ujson.dumps(data, indent=indent, escape_forward_slashes=False) + return result + + +def json_loads(data: Union[str, bytes]) -> JSONOutput: + """Deserialize unicode or bytes to a Python object. + + data (str / bytes): The data to deserialize. + RETURNS: The deserialized Python object. + """ + # Avoid transforming the string '-' into the int '0' + if data == "-": + raise ValueError("Expected object or value") + return ujson.loads(data) + + +def read_json(path: FilePath) -> JSONOutput: + """Load JSON from file or standard input. + + path (FilePath): The file path. "-" for reading from stdin. + RETURNS (JSONOutput): The loaded JSON content. + """ + if path == "-": # reading from sys.stdin + data = sys.stdin.read() + return ujson.loads(data) + file_path = force_path(path) + with file_path.open("r", encoding="utf8") as f: + return ujson.load(f) + + +def read_gzip_json(path: FilePath) -> JSONOutput: + """Load JSON from a gzipped file. + + location (FilePath): The file path. + RETURNS (JSONOutput): The loaded JSON content. + """ + file_path = force_string(path) + with gzip.open(file_path, "r") as f: + return ujson.load(f) + + +def read_gzip_jsonl(path: FilePath, skip: bool = False) -> Iterator[JSONOutput]: + """Read a gzipped .jsonl file and yield contents line by line. + Blank lines will always be skipped. + + path (FilePath): The file path. + skip (bool): Skip broken lines and don't raise ValueError. + YIELDS (JSONOutput): The unpacked, deserialized Python objects. + """ + with gzip.open(force_path(path), "r") as f: + for line in _yield_json_lines(f, skip=skip): + yield line + + +def write_json(path: FilePath, data: JSONInput, indent: int = 2) -> None: + """Create a .json file and dump contents or write to standard + output. + + location (FilePath): The file path. "-" for writing to stdout. + data (JSONInput): The JSON-serializable data to output. + indent (int): Number of spaces used to indent JSON. + """ + json_data = json_dumps(data, indent=indent) + if path == "-": # writing to stdout + print(json_data) + else: + file_path = force_path(path, require_exists=False) + with file_path.open("w", encoding="utf8") as f: + f.write(json_data) + + +def write_gzip_json(path: FilePath, data: JSONInput, indent: int = 2) -> None: + """Create a .json.gz file and dump contents. + + path (FilePath): The file path. + data (JSONInput): The JSON-serializable data to output. + indent (int): Number of spaces used to indent JSON. + """ + json_data = json_dumps(data, indent=indent) + file_path = force_string(path) + with gzip.open(file_path, "w") as f: + f.write(json_data.encode("utf-8")) + + +def write_gzip_jsonl( + path: FilePath, + lines: Iterable[JSONInput], + append: bool = False, + append_new_line: bool = True, +) -> None: + """Create a .jsonl.gz file and dump contents. + + location (FilePath): The file path. + lines (Sequence[JSONInput]): The JSON-serializable contents of each line. + append (bool): Whether or not to append to the location. Appending to .gz files is generally not recommended, as it + doesn't allow the algorithm to take advantage of all data when compressing - files may hence be poorly + compressed. + append_new_line (bool): Whether or not to write a new line before appending + to the file. + """ + mode = "a" if append else "w" + file_path = force_path(path, require_exists=False) + with gzip.open(file_path, mode=mode) as f: + if append and append_new_line: + f.write("\n".encode("utf-8")) + f.writelines([(json_dumps(line) + "\n").encode("utf-8") for line in lines]) + + +def read_jsonl(path: FilePath, skip: bool = False) -> Iterable[JSONOutput]: + """Read a .jsonl file or standard input and yield contents line by line. + Blank lines will always be skipped. + + path (FilePath): The file path. "-" for reading from stdin. + skip (bool): Skip broken lines and don't raise ValueError. + YIELDS (JSONOutput): The loaded JSON contents of each line. + """ + if path == "-": # reading from sys.stdin + for line in _yield_json_lines(sys.stdin, skip=skip): + yield line + else: + file_path = force_path(path) + with file_path.open("r", encoding="utf8") as f: + for line in _yield_json_lines(f, skip=skip): + yield line + + +def write_jsonl( + path: FilePath, + lines: Iterable[JSONInput], + append: bool = False, + append_new_line: bool = True, +) -> None: + """Create a .jsonl file and dump contents or write to standard output. + + location (FilePath): The file path. "-" for writing to stdout. + lines (Sequence[JSONInput]): The JSON-serializable contents of each line. + append (bool): Whether or not to append to the location. + append_new_line (bool): Whether or not to write a new line before appending + to the file. + """ + if path == "-": # writing to stdout + for line in lines: + print(json_dumps(line)) + else: + mode = "a" if append else "w" + file_path = force_path(path, require_exists=False) + with file_path.open(mode, encoding="utf-8") as f: + if append and append_new_line: + f.write("\n") + for line in lines: + f.write(json_dumps(line) + "\n") + + +def is_json_serializable(obj: Any) -> bool: + """Check if a Python object is JSON-serializable. + + obj: The object to check. + RETURNS (bool): Whether the object is JSON-serializable. + """ + if hasattr(obj, "__call__"): + # Check this separately here to prevent infinite recursions + return False + try: + ujson.dumps(obj) + return True + except (TypeError, OverflowError): + return False + + +def _yield_json_lines( + stream: Iterable[str], skip: bool = False +) -> Iterable[JSONOutput]: + line_no = 1 + for line in stream: + line = line.strip() + if line == "": + continue + try: + yield ujson.loads(line) + except ValueError: + if skip: + continue + raise ValueError(f"Invalid JSON on line {line_no}: {line}") + line_no += 1 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/srsly/_msgpack_api.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/srsly/_msgpack_api.py new file mode 100644 index 0000000000000000000000000000000000000000..3da0fe6150d52a0080e46ad167e9e61eaa46c69f --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/srsly/_msgpack_api.py @@ -0,0 +1,57 @@ +import gc + +from . import msgpack +from .msgpack import msgpack_encoders, msgpack_decoders # noqa: F401 +from .util import force_path, FilePath, JSONInputBin, JSONOutputBin + + +def msgpack_dumps(data: JSONInputBin) -> bytes: + """Serialize an object to a msgpack byte string. + + data: The data to serialize. + RETURNS (bytes): The serialized bytes. + """ + return msgpack.dumps(data, use_bin_type=True) + + +def msgpack_loads(data: bytes, use_list: bool = True) -> JSONOutputBin: + """Deserialize msgpack bytes to a Python object. + + data (bytes): The data to deserialize. + use_list (bool): Don't use tuples instead of lists. Can make + deserialization slower. + RETURNS: The deserialized Python object. + """ + # msgpack-python docs suggest disabling gc before unpacking large messages + gc.disable() + msg = msgpack.loads(data, raw=False, use_list=use_list) + gc.enable() + return msg + + +def write_msgpack(path: FilePath, data: JSONInputBin) -> None: + """Create a msgpack file and dump contents. + + location (FilePath): The file path. + data (JSONInputBin): The data to serialize. + """ + file_path = force_path(path, require_exists=False) + with file_path.open("wb") as f: + msgpack.dump(data, f, use_bin_type=True) + + +def read_msgpack(path: FilePath, use_list: bool = True) -> JSONOutputBin: + """Load a msgpack file. + + location (FilePath): The file path. + use_list (bool): Don't use tuples instead of lists. Can make + deserialization slower. + RETURNS (JSONOutputBin): The loaded and deserialized content. + """ + file_path = force_path(path) + with file_path.open("rb") as f: + # msgpack-python docs suggest disabling gc before unpacking large messages + gc.disable() + msg = msgpack.load(f, raw=False, use_list=use_list) + gc.enable() + return msg diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/srsly/_pickle_api.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/srsly/_pickle_api.py new file mode 100644 index 0000000000000000000000000000000000000000..0e894d9de814fb103d7992b9807e15b920463d0c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/srsly/_pickle_api.py @@ -0,0 +1,23 @@ +from typing import Optional + +from . import cloudpickle +from .util import JSONInput, JSONOutput + + +def pickle_dumps(data: JSONInput, protocol: Optional[int] = None) -> bytes: + """Serialize a Python object with pickle. + + data: The object to serialize. + protocol (int): Protocol to use. -1 for highest. + RETURNS (bytes): The serialized object. + """ + return cloudpickle.dumps(data, protocol=protocol) + + +def pickle_loads(data: bytes) -> JSONOutput: + """Deserialize bytes with pickle. + + data (bytes): The data to deserialize. + RETURNS: The deserialized Python object. + """ + return cloudpickle.loads(data) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/srsly/_yaml_api.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/srsly/_yaml_api.py new file mode 100644 index 0000000000000000000000000000000000000000..36f24aa1083310d03b10c2064d348e2913d5161d --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/srsly/_yaml_api.py @@ -0,0 +1,122 @@ +from typing import Union, IO, Any +from io import StringIO +import sys + +from .ruamel_yaml import YAML +from .ruamel_yaml.representer import RepresenterError +from .util import force_path, FilePath, YAMLInput, YAMLOutput + + +class CustomYaml(YAML): + def __init__(self, typ="safe", pure=True): + YAML.__init__(self, typ=typ, pure=pure) + self.default_flow_style = False + self.allow_unicode = True + self.encoding = "utf-8" + + # https://yaml.readthedocs.io/en/latest/example.html#output-of-dump-as-a-string + def dump(self, data, stream=None, **kw): + inefficient = False + if stream is None: + inefficient = True + stream = StringIO() + YAML.dump(self, data, stream, **kw) + if inefficient: + return stream.getvalue() + + +def yaml_dumps( + data: YAMLInput, + indent_mapping: int = 2, + indent_sequence: int = 4, + indent_offset: int = 2, + sort_keys: bool = False, +) -> str: + """Serialize an object to a YAML string. See the ruamel.yaml docs on + indentation for more details on the expected format. + https://yaml.readthedocs.io/en/latest/detail.html?highlight=indentation#indentation-of-block-sequences + + data: The YAML-serializable data. + indent_mapping (int): Mapping indentation. + indent_sequence (int): Sequence indentation. + indent_offset (int): Indentation offset. + sort_keys (bool): Sort dictionary keys. + RETURNS (str): The serialized string. + """ + yaml = CustomYaml() + yaml.sort_base_mapping_type_on_output = sort_keys + yaml.indent(mapping=indent_mapping, sequence=indent_sequence, offset=indent_offset) + return yaml.dump(data) + + +def yaml_loads(data: Union[str, IO]) -> YAMLOutput: + """Deserialize unicode or a file object a Python object. + + data (str / file): The data to deserialize. + RETURNS: The deserialized Python object. + """ + yaml = CustomYaml() + try: + return yaml.load(data) + except Exception as e: + raise ValueError(f"Invalid YAML: {e}") + + +def read_yaml(path: FilePath) -> YAMLOutput: + """Load YAML from file or standard input. + + location (FilePath): The file path. "-" for reading from stdin. + RETURNS (YAMLOutput): The loaded content. + """ + if path == "-": # reading from sys.stdin + data = sys.stdin.read() + return yaml_loads(data) + file_path = force_path(path) + with file_path.open("r", encoding="utf8") as f: + return yaml_loads(f) + + +def write_yaml( + path: FilePath, + data: YAMLInput, + indent_mapping: int = 2, + indent_sequence: int = 4, + indent_offset: int = 2, + sort_keys: bool = False, +) -> None: + """Create a .json file and dump contents or write to standard + output. + + location (FilePath): The file path. "-" for writing to stdout. + data (YAMLInput): The JSON-serializable data to output. + indent_mapping (int): Mapping indentation. + indent_sequence (int): Sequence indentation. + indent_offset (int): Indentation offset. + sort_keys (bool): Sort dictionary keys. + """ + yaml_data = yaml_dumps( + data, + indent_mapping=indent_mapping, + indent_sequence=indent_sequence, + indent_offset=indent_offset, + sort_keys=sort_keys, + ) + if path == "-": # writing to stdout + print(yaml_data) + else: + file_path = force_path(path, require_exists=False) + with file_path.open("w", encoding="utf8") as f: + f.write(yaml_data) + + +def is_yaml_serializable(obj: Any) -> bool: + """Check if a Python object is YAML-serializable (strict). + + obj: The object to check. + RETURNS (bool): Whether the object is YAML-serializable. + """ + try: + yaml_dumps(obj) + return True + except RepresenterError: + return False diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/srsly/about.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/srsly/about.py new file mode 100644 index 0000000000000000000000000000000000000000..43b48b6fda2891edad88e18424029419e6628978 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/srsly/about.py @@ -0,0 +1 @@ +__version__ = "2.5.3" diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/srsly/util.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/srsly/util.py new file mode 100644 index 0000000000000000000000000000000000000000..c43120c96182895496403bbaac1caae3d4f12eb5 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/srsly/util.py @@ -0,0 +1,31 @@ +from pathlib import Path +from typing import Union, Dict, Any, List, Tuple +from collections import OrderedDict + + +# fmt: off +FilePath = Union[str, Path] +# Superficial JSON input/output types +# https://github.com/python/typing/issues/182#issuecomment-186684288 +JSONOutput = Union[str, int, float, bool, None, Dict[str, Any], List[Any]] +JSONOutputBin = Union[bytes, str, int, float, bool, None, Dict[str, Any], List[Any]] +# For input, we also accept tuples, ordered dicts etc. +JSONInput = Union[str, int, float, bool, None, Dict[str, Any], List[Any], Tuple[Any, ...], OrderedDict] +JSONInputBin = Union[bytes, str, int, float, bool, None, Dict[str, Any], List[Any], Tuple[Any, ...], OrderedDict] +YAMLInput = JSONInput +YAMLOutput = JSONOutput +# fmt: on + + +def force_path(location, require_exists=True): + if not isinstance(location, Path): + location = Path(location) + if require_exists and not location.exists(): + raise ValueError(f"Can't read file: {location}") + return location + + +def force_string(location): + if isinstance(location, str): + return location + return str(location) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/LICENSE.txt b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..47cd54eec489af242da0e1a9fe00f1ed15cf2e69 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/LICENSE.txt @@ -0,0 +1,34 @@ +Copyright (C) 2006, Jonathan E. Taylor +All rights reserved. + +Copyright (c) 2006-2008 Scipy Developers. +All rights reserved. + +Copyright (c) 2009-2018 statsmodels Developers. +All rights reserved. + + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + a. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + b. 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. + c. Neither the name of statsmodels 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 STATSMODELS 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. diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..419ab809630518adb821e72571de62f47d4c3ee3 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/__init__.py @@ -0,0 +1,42 @@ +from statsmodels.compat.patsy import monkey_patch_cat_dtype + +from statsmodels._version import __version__, __version_tuple__ + +__version_info__ = __version_tuple__ + +monkey_patch_cat_dtype() + +debug_warnings = False + +if debug_warnings: + import warnings + + warnings.simplefilter("default") + # use the following to raise an exception for debugging specific warnings + # warnings.filterwarnings("error", message=".*integer.*") + + +def test(extra_args=None, exit=False): + """ + Run the test suite + + Parameters + ---------- + extra_args : list[str] + List of argument to pass to pytest when running the test suite. The + default is ['--tb=short', '--disable-pytest-warnings']. + exit : bool + Flag indicating whether the test runner should exit when finished. + + Returns + ------- + int + The status code from the test run if exit is False. + """ + from .tools._test_runner import PytestTester + + tst = PytestTester(package_path=__file__) + return tst(extra_args=extra_args, exit=exit) + + +__all__ = ["__version__", "__version_info__", "__version_tuple__", "test"] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/_version.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..f3efca6d719282a64c7016fdff3eef50ac25abeb --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/_version.py @@ -0,0 +1,21 @@ +# file generated by setuptools-scm +# don't change, don't track in version control + +__all__ = ["__version__", "__version_tuple__", "version", "version_tuple"] + +TYPE_CHECKING = False +if TYPE_CHECKING: + from typing import Tuple + from typing import Union + + VERSION_TUPLE = Tuple[Union[int, str], ...] +else: + VERSION_TUPLE = object + +version: str +__version__: str +__version_tuple__: VERSION_TUPLE +version_tuple: VERSION_TUPLE + +__version__ = version = '0.14.6' +__version_tuple__ = version_tuple = (0, 14, 6) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/api.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/api.py new file mode 100644 index 0000000000000000000000000000000000000000..ca51f15b3f91b8a3f16e556698756ea40befd434 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/api.py @@ -0,0 +1,144 @@ +__all__ = [ + "BayesGaussMI", + "BinomialBayesMixedGLM", + "ConditionalLogit", + "ConditionalMNLogit", + "ConditionalPoisson", + "Factor", + "GEE", + "GLM", + "GLMGam", + "GLS", + "GLSAR", + "GeneralizedPoisson", + "HurdleCountModel", + "Logit", + "MANOVA", + "MI", + "MICE", + "MICEData", + "MNLogit", + "MixedLM", + "NegativeBinomial", + "NegativeBinomialP", + "NominalGEE", + "OLS", + "OrdinalGEE", + "PCA", + "PHReg", + "Poisson", + "PoissonBayesMixedGLM", + "ProbPlot", + "Probit", + "QuantReg", + "RLM", + "RecursiveLS", + "SurvfuncRight", + "TruncatedLFPoisson", + "TruncatedLFNegativeBinomialP", + "WLS", + "ZeroInflatedGeneralizedPoisson", + "ZeroInflatedNegativeBinomialP", + "ZeroInflatedPoisson", + "__version__", + "add_constant", + "categorical", + "cov_struct", + "datasets", + "distributions", + "duration", + "emplike", + "families", + "formula", + "gam", + "genmod", + "graphics", + "iolib", + "load", + "load_pickle", + "multivariate", + "nonparametric", + "qqline", + "qqplot", + "qqplot_2samples", + "regression", + "robust", + "show_versions", + "stats", + "test", + "tools", + "tsa", + "webdoc", + "__version_info__" +] + + +from . import datasets, distributions, iolib, regression, robust, tools +from .__init__ import test +from statsmodels._version import ( + version as __version__, version_tuple as __version_info__ +) +from .discrete.conditional_models import ( + ConditionalLogit, + ConditionalMNLogit, + ConditionalPoisson, +) +from .discrete.count_model import ( + ZeroInflatedGeneralizedPoisson, + ZeroInflatedNegativeBinomialP, + ZeroInflatedPoisson, +) +from .discrete.discrete_model import ( + GeneralizedPoisson, + Logit, + MNLogit, + NegativeBinomial, + NegativeBinomialP, + Poisson, + Probit, +) +from .discrete.truncated_model import ( + TruncatedLFPoisson, + TruncatedLFNegativeBinomialP, + HurdleCountModel, + ) +from .duration import api as duration +from .duration.hazard_regression import PHReg +from .duration.survfunc import SurvfuncRight +from .emplike import api as emplike +from .formula import api as formula +from .gam import api as gam +from .gam.generalized_additive_model import GLMGam +from .genmod import api as genmod +from .genmod.api import ( + GEE, + GLM, + BinomialBayesMixedGLM, + NominalGEE, + OrdinalGEE, + PoissonBayesMixedGLM, + cov_struct, + families, +) +from .graphics import api as graphics +from .graphics.gofplots import ProbPlot, qqline, qqplot, qqplot_2samples +from .imputation.bayes_mi import MI, BayesGaussMI +from .imputation.mice import MICE, MICEData +from .iolib.smpickle import load_pickle +from .multivariate import api as multivariate +from .multivariate.factor import Factor +from .multivariate.manova import MANOVA +from .multivariate.pca import PCA +from .nonparametric import api as nonparametric +from .regression.linear_model import GLS, GLSAR, OLS, WLS +from .regression.mixed_linear_model import MixedLM +from .regression.quantile_regression import QuantReg +from .regression.recursive_ls import RecursiveLS +from .robust.robust_linear_model import RLM +from .stats import api as stats +from .tools.print_version import show_versions +from .tools.tools import add_constant, categorical +from .tools.web import webdoc +from .tsa import api as tsa + +load = load_pickle diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/conftest.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..33ccf901a075c9cce94c97f3d29f81bdcfbc5b1f --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/conftest.py @@ -0,0 +1,167 @@ +import logging +import os + +import numpy as np +import pandas as pd +import pytest +from statsmodels.compat.python import PYTHON_IMPL_WASM + +try: + import matplotlib + + matplotlib.use('agg') + HAVE_MATPLOTLIB = True +except ImportError: + HAVE_MATPLOTLIB = False + + +logger = logging.getLogger(__name__) + +cow = False +try: + cow = bool(os.environ.get("SM_TEST_COPY_ON_WRITE", False)) + pd.options.mode.copy_on_write = cow +except AttributeError: + pass + +if cow: + logger.critical("Copy on Write Enabled!") +else: + logger.critical("Copy on Write disabled") + + +def pytest_addoption(parser): + parser.addoption("--skip-slow", action="store_true", + help="skip slow tests") + parser.addoption("--only-slow", action="store_true", + help="run only slow tests") + parser.addoption("--skip-examples", action="store_true", + help="skip tests of examples") + parser.addoption("--skip-matplotlib", action="store_true", + help="skip tests that depend on matplotlib") + parser.addoption("--skip-smoke", action="store_true", + help="skip smoke tests") + parser.addoption("--only-smoke", action="store_true", + help="run only smoke tests") + + +def pytest_runtest_setup(item): + if 'slow' in item.keywords and item.config.getoption("--skip-slow"): + pytest.skip("skipping due to --skip-slow") + + if 'slow' not in item.keywords and item.config.getoption("--only-slow"): + pytest.skip("skipping due to --only-slow") + + if 'example' in item.keywords and item.config.getoption("--skip-examples"): + pytest.skip("skipping due to --skip-examples") + + if 'matplotlib' in item.keywords and \ + item.config.getoption("--skip-matplotlib"): + pytest.skip("skipping due to --skip-matplotlib") + + if 'matplotlib' in item.keywords and not HAVE_MATPLOTLIB: + pytest.skip("skipping since matplotlib is not intalled") + + if 'smoke' in item.keywords and item.config.getoption("--skip-smoke"): + pytest.skip("skipping due to --skip-smoke") + + if 'smoke' not in item.keywords and item.config.getoption('--only-smoke'): + pytest.skip("skipping due to --only-smoke") + + +def pytest_configure(config): + try: + import matplotlib + matplotlib.use('agg') + try: + from pandas.plotting import register_matplotlib_converters + register_matplotlib_converters() + except ImportError: + pass + except ImportError: + pass + + +@pytest.fixture() +def close_figures(): + """ + Fixture that closes all figures after a test function has completed + + Returns + ------- + closer : callable + Function that will close all figures when called. + + Notes + ----- + Used by passing as an argument to the function that produces a plot, + for example + + def test_some_plot(close_figures): + + + If a function creates many figures, then these can be destroyed within a + test function by calling close_figures to ensure that the number of + figures does not become too large. + + def test_many_plots(close_figures): + for i in range(100000): + plt.plot(x,y) + close_figures() + """ + try: + import matplotlib.pyplot + + def close(): + matplotlib.pyplot.close('all') + + except ImportError: + def close(): + pass + + yield close + close() + + +@pytest.fixture() +def reset_randomstate(): + """ + Fixture that set the global RandomState to the fixed seed 1 + + Notes + ----- + Used by passing as an argument to the function that uses the global + RandomState + + def test_some_plot(reset_randomstate): + + + Returns the state after the test function exits + """ + state = np.random.get_state() + np.random.seed(1) + yield + np.random.set_state(state) + + +# This is a special hook that converts all xfail marks to have strict=False +# instead of strict=True. This is useful to have for Pyodide tests, where +# some tests will consistently xfail due to missing functionality (such as +# NotImplementedErrors) or floating point imprecisions, but we don't want +# to mark them as strict xfails because they are more prominently expected +# to fail in a Pyodide environment. +def pytest_collection_modifyitems(config, items): + if PYTHON_IMPL_WASM: + for item in items: + if 'xfail' in item.keywords: + mark = item.get_closest_marker('xfail') + if mark: + # Modify the existing xfail mark if it exists + # to set strict=False + new_kwargs = dict(mark.kwargs) + new_kwargs['strict'] = False + new_mark = pytest.mark.xfail(**new_kwargs) + item.add_marker(new_mark) + item.keywords['xfail'] = new_mark + else: + pass diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/setup.cfg b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/setup.cfg new file mode 100644 index 0000000000000000000000000000000000000000..f8c35d66b99fe5f4723e4efb26edf95854e1845d --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/setup.cfg @@ -0,0 +1,324 @@ +[metadata] +license_files = + LICENSE.txt + +[tool:pytest] +minversion = 6 +testpaths = statsmodels +xfail_strict = true +addopts = --strict +# Filter warnings generated by dependencies +filterwarnings = + ignore:pandas.core.common.is_categorical_dtype:DeprecationWarning:patsy + ignore:Using or importing the ABCs:DeprecationWarning:patsy + ignore:Using a non-tuple sequence:FutureWarning:mkl_fft + ignore:Using a non-tuple:FutureWarning:scipy.signal + ignore:Using a non-tuple:FutureWarning:scipy.stats.stats + ignore:the matrix subclass is not the recommended:PendingDeprecationWarning: + ignore:Method .ptp is deprecated:FutureWarning:numpy.core.fromnumeric + ignore::DeprecationWarning:nbconvert.exporters.exporter_locator + ignore:Using or importing the ABCs:DeprecationWarning:jinja2.utils + ignore:Converting `np.integer`:DeprecationWarning:scipy.stats.morestats + ignore:\nstatsmodels.tsa.arima_model.ARMA:FutureWarning + ignore:The --strict option is deprecated:pytest.PytestDeprecationWarning: + error:genfromdta:FutureWarning + error:StataReader:FutureWarning + error:Care should be used:UserWarning + error::statsmodels.tools.sm_exceptions.HypothesisTestWarning + error::statsmodels.tools.sm_exceptions.SpecificationWarning + error:load will return datasets:FutureWarning + error:the 'lags' keyword is deprecated:FutureWarning + error:nobs is deprecated in favor of lags:DeprecationWarning + error:The default pvalmethod will change:FutureWarning + error:Using an implicitly registered:FutureWarning + error:An unsupported index:statsmodels.tools.sm_exceptions.ValueWarning + error:No supported index is:statsmodels.tools.sm_exceptions.ValueWarning + error:Anscombe residuals:FutureWarning + error:Calling Family:DeprecationWarning + error:SIR.fit_regularized did not:UserWarning + error:the 'sigma' keyword:FutureWarning + error:tight_layout:UserWarning + error:statsmodels.tsa.AR has been deprecated:FutureWarning + error:Using deprecated variance components:UserWarning + error:recarray support has been deprecated:FutureWarning + error:The value returned will change to a:FutureWarning + error:The default value of lags:FutureWarning + error:non-integer arg n is deprecated:DeprecationWarning + error:The default number of lags:FutureWarning: + error:fft=True will become the default:FutureWarning + error:The parameter names will change:FutureWarning + error:Only PeriodIndexes, DatetimeIndexes:UserWarning + error:the 'unbiased'' keyword is deprecated:FutureWarning + error:unbiased is deprecated in factor of adjusted:FutureWarning + error:categorical is deprecated:FutureWarning + error:After 0.13 initialization:FutureWarning + error:The bic value:FutureWarning + error:Setting initial values:FutureWarning + error:Setting use_boxcox:FutureWarning + error:``Describe`` has been deprecated:DeprecationWarning + error:Promotion of numbers and bools to strings:FutureWarning + error:old_names will be removed after the 0.14 release:FutureWarning + error:Dropping of nuisance columns in:: + error:The `inplace` parameter in pandas:: + error:The default method:FutureWarning: + error:trend 'nc' has been renamed to 'n':FutureWarning: + error:Keyword arguments have been passed:FutureWarning: + error:The behavior of wald_test:FutureWarning + error:cols is deprecated and will be removed after:FutureWarning + error:Passing None to catch any warning has been deprecated:: + error:pandas.Int64Index is deprecated:: + error:divide by zero encountered in _binom_pdf:RuntimeWarning + error:verbose is deprecated:FutureWarning + error:linear keyword is deprecated:DeprecationWarning: + error:The identity link alias is deprecated:FutureWarning: + error:The log link alias is deprecated:FutureWarning: + error:The probit link alias is deprecated:FutureWarning: + error:Parsing dates in:UserWarning + error:A value is trying to be set on a copy:: + error:Conversion of an array with ndim:DeprecationWarning: + error:Series.__getitem__ treating keys:FutureWarning: + error:'Y' is deprecated, please use 'YE' instead:FutureWarning + error:'A' is deprecated, please use 'YE' instead:FutureWarning + error:'H' is deprecated and will:FutureWarning + error:'M' is deprecated, please use:FutureWarning + error:'Q' is deprecated, please use 'QE' instead:FutureWarning + error:'Q-DEC' is deprecated, please use 'QE-DEC' instead:FutureWarning + error:'Q-JAN' is deprecated, please use 'QE-JAN' instead:FutureWarning + error:'BQ-MAR' is deprecated, please use 'BQE-MAR' instead:FutureWarning + error:'AS-MAR' is deprecated and will be removed in a future version:FutureWarning + error:Downcasting object dtype arrays on:FutureWarning + error:The previous implementation of stack is deprecated:FutureWarning + error:Series.__setitem__ treating keys as positions is deprecated:FutureWarning + error:The provided callable:FutureWarning + error:divide by zero encountered in log1p:RuntimeWarning + error:Starting with pandas version 3.0 all:FutureWarning + +markers = + example: mark a test that runs example code + matplotlib: mark a test that requires matplotlib + slow: mark a test as slow + smoke: mark a test as a smoketest + low_precision: mark a test as low precision + todo: mark a test as incomplete +junit_family = xunit2 + +[flake8] +exclude = .git,build,docs,archive +max-line-length = 88 +ignore= + W503, + # W503: line break before binary operator + W504, + # W504: line break after binary operator + E741, + # E741: ambiguous variable name 'l' + E203 + # E203: Whitespace before ':' +select= + E101, + # E101: indentation contains mixed spaces and tabs + E124, + # E124: closing bracket does not match visual indentation + F811, + # F811: redefinition of unused 'pytest' from line 10 + F812, + # F812: list comprehension redefines 'x' from line 199 + F822, + # F822: undefined name name in __all__ + F823, + # F823: local variable name ... referenced before assignment + E129, + # E129: visually indented line with same indent as next logical line + E131, + # E131: continuation line unaligned for hanging indent + E125, + # E125: continuation line with same indent as next logical line + E111, + # E111: Indentation is not a multiple of four + E114, + # E114: Indentation is not a multiple of four (comment) + E117, + # E117: over-indented + E227, + # E227: missing whitespace around bitwise or shift operator + E228, + # E228: missing whitespace around modulo operator + E211, + # E211: whitespace before '[' + E112, + # E112: expected an indented block + E113, + # E113: unexpected indentation + E223, + # E223: tab before operator + E224, + # E224: tab after operator + E242, + # E242: tab after ',' + E304, + # E304: blank lines found after function decorator + F831, + # F831: duplicate argument name in function definition + E306, + # E306: expected 1 blank line before a nested definition, found 0 + + W, + # W191: indentation contains tabs + # W291: trailing whitespace + # W292: no newline at end of file + # W293: blank line contains whitespace + # W391: blank line at end of file + # W601: .has_key() is deprecated, use 'in' + # W602: deprecated form of raising exception + # W603: '<>' is deprecated, use '!=' + # W604: backticks are deprecated, use 'repr()' + # W605: invalid escape sequence 'x' + # W606: 'async' and 'await' are reserved keywords starting with Python 3.7 + + E70, + # E701: multiple statements on one line (colon) + # E702: multiple statements on one line (semicolon) + # E703: statement ends with a semicolon + # E704: multiple statements on one line (def) + + E71, + # E711: comparison to None should be 'if cond is None:' + # E712: comparison to True should be 'if cond is True:' or 'if cond:' + # E713: test for membership should be 'not in' + + E721, + # E721: do not compare types, use 'isinstance()' + + E74, + # E741 ambiguous variable name 'l', 'O', or 'I' + # E742: do not define classes named 'l', 'O', or 'I' + # E743: do not define functions named 'l', 'O', or 'I' + + F4, + # F401: 'foo.bar' imported but unused + # F402: import 'assert_equal' from line 7 shadowed by loop variable + # F403: 'from .data import *' used; unable to detect undefined names + # F404: future import(s) name after other statements + # F405: name may be undefined, or defined from star imports: module + # F406: 'from module import *' only allowed at module level + # F407: an undefined __future__ feature name was imported + + F6, + # F601: dictionary key name repeated with different values + # F602: dictionary key variable name repeated with different values + # F621: too many expressions in an assignment with star-unpacking + # F622: two or more starred expressions in an assignment (a, *b, *c = d) + # F631: assertion test is a tuple, which are always True + # F632: use ==/!= to compare str, bytes, and int literals + + F7, + # F701: a break statement outside of a while or for loop + # F702: a continue statement outside of a while or for loop + # F703: a continue statement in a finally block in a loop + # F704: a yield or yield from statement outside of a function + # F705: a return statement with arguments inside a generator + # F706: a return statement outside of a function/method + # F707: an except: block as not the last exception handler + # F721: doctest syntax error + # F722: syntax error in forward type annotation + + F81, + # F811: redefinition of unused 'pytest' from line 10 + # F812: list comprehension redefines 'x' from line 199 + + F82, + # F821: undefined name 'foo' + # F822: undefined name name in __all__ + # F823: local variable name ... referenced before assignment + + F9, + # F901: raise NotImplemented should be raise NotImplementedError + + E27, + # E271: multiple spaces after keyword + # E272: multiple spaces before keyword + # E273: tab after keyword + # E274: tab before keyword + # E275: missing whitespace after keyword + + E4, + # E401: multiple imports on one line + # E402: module level import not at top of file + + E9, + # E901: SyntaxError or IndentationError + # E902: IOError + # E999: Syntax Error + + +[coverage:run] +source = statsmodels +branch = True +plugins = Cython.Coverage +omit = + # print_version is untestable + */print_version.py + # skip compatibility code + */compat/* + # Unused file + */results/gee_generate_tests.py + # Results for tests + */tests/results/* + # Simulation checks + */tests/*_simulation_check.py + # Misc non-test files in test directories + */tests/_* + */tests/e* + */tests/c* + */tests/d* + */tests/g* + */tests/m* + */tests/p* + */tests/r* + */tests/s* + */_version.py + +[coverage:report] +show_missing = True +ignore_errors = False +# Regexes for lines to exclude from consideration +exclude_lines = + # Have to re-enable the standard pragma + pragma: no cover + + # Do not complain about missing debug-only code: + def __repr__ + if self\.debug + if pdf_output: + + # Do not complain if tests do not hit defensive assertion code: + raise AssertionError + raise NotImplementedError + except NotImplementedError + except ImportError + except (HTTPError, URLError, SSLError, timeout) + except IGNORED_EXCEPTIONS + + # Ignore pass + pass + + # Do not complain if non-runnable code is not run: + if 0: + if __name__ == .__main__.: + +[coverage:html] +directory = coverage_html_report + +[isort] +sections=FUTURE,COMPAT,STDLIB,THIRDPARTY,FIRSTPARTY,LOCALFOLDER +known_first_party=statsmodels +known_third_party=Cython,numpy,matplotlib,pandas,patsy,pytest,cvxopt,cython +multi_line_output=3 +include_trailing_comma=True +use_parentheses=True +line_length=79 +known_compat=statsmodels.compat.*,setuptools,setuptools.* +force_grid_wrap=0 +combine_as_imports=True +force_sort_within_sections=True +force_to_top=True diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tabledata-1.3.5.dist-info/INSTALLER b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tabledata-1.3.5.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tabledata-1.3.5.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tabledata-1.3.5.dist-info/METADATA b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tabledata-1.3.5.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..1bd38b9bcb99f6d4b09ee887d19f0c391a901856 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tabledata-1.3.5.dist-info/METADATA @@ -0,0 +1,117 @@ +Metadata-Version: 2.4 +Name: tabledata +Version: 1.3.5 +Summary: tabledata is a Python library to represent tabular data. Used for pytablewriter/pytablereader/SimpleSQLite/etc. +Home-page: https://github.com/thombashi/tabledata +Author: Tsuyoshi Hombashi +Author-email: tsuyoshi.hombashi@gmail.com +License: MIT License +Project-URL: Changelog, https://github.com/thombashi/tabledata/releases +Project-URL: Documentation, https://tabledata.rtfd.io/ +Project-URL: Source, https://github.com/thombashi/tabledata +Project-URL: Tracker, https://github.com/thombashi/tabledata/issues +Keywords: table +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Information Technology +Classifier: License :: OSI Approved :: MIT License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +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 :: Only +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Software Development :: Libraries +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Typing :: Typed +Requires-Python: >=3.10 +Description-Content-Type: text/x-rst +License-File: LICENSE +Requires-Dist: DataProperty<2,>=1.0.2 +Requires-Dist: typepy<3,>=1.2.0 +Provides-Extra: logging +Requires-Dist: loguru<1,>=0.4.1; extra == "logging" +Provides-Extra: test +Requires-Dist: pytablewriter>=0.46; extra == "test" +Requires-Dist: pytest; extra == "test" +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: description-content-type +Dynamic: home-page +Dynamic: keywords +Dynamic: license +Dynamic: license-file +Dynamic: project-url +Dynamic: provides-extra +Dynamic: requires-dist +Dynamic: requires-python +Dynamic: summary + +.. contents:: **tabledata** + :backlinks: top + :depth: 2 + +Summary +--------- +`tabledata `__ is a Python library to represent tabular data. Used for pytablewriter/pytablereader/SimpleSQLite/etc. + +.. image:: https://badge.fury.io/py/tabledata.svg + :target: https://badge.fury.io/py/tabledata + :alt: PyPI package version + +.. image:: https://img.shields.io/pypi/pyversions/tabledata.svg + :target: https://pypi.org/project/tabledata + :alt: Supported Python versions + +.. image:: https://img.shields.io/pypi/implementation/tabledata.svg + :target: https://pypi.org/project/tabledata + :alt: Supported Python implementations + +.. image:: https://github.com/thombashi/tabledata/actions/workflows/ci.yml/badge.svg + :target: https://github.com/thombashi/tabledata/actions/workflows/ci.yml + :alt: Linux/macOS/Windows CI status + +.. image:: https://coveralls.io/repos/github/thombashi/tabledata/badge.svg?branch=master + :target: https://coveralls.io/github/thombashi/tabledata?branch=master + :alt: Test coverage + +Installation +============ + +Install from PyPI +------------------------------ +:: + + pip install tabledata + +Install from PPA (for Ubuntu) +------------------------------ +:: + + sudo add-apt-repository ppa:thombashi/ppa + sudo apt update + sudo apt install python3-tabledata + + +Dependencies +============ +- Python 3.10+ +- `Mandatory Python package dependencies (automatically installed) `__ + +Optional Python packages +------------------------------------------------ +- `loguru `__ + - Used for logging if the package installed +- `pandas `__ + - required to get table data as a pandas data frame + +Documentation +=============== +https://tabledata.rtfd.io/ + diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tabledata-1.3.5.dist-info/RECORD b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tabledata-1.3.5.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..6665db0e925f7701d25599eb5778a60d100734d7 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tabledata-1.3.5.dist-info/RECORD @@ -0,0 +1,29 @@ +tabledata-1.3.5.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +tabledata-1.3.5.dist-info/METADATA,sha256=mAzggqWck35z1YQ_k2ih7GUUQS3OuxsMgBFoOxnrROU,3983 +tabledata-1.3.5.dist-info/RECORD,, +tabledata-1.3.5.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91 +tabledata-1.3.5.dist-info/licenses/LICENSE,sha256=31KMV79GBvx6xAIrOmXe2KSRXgQIXtdcP4EN9WKzcBs,1079 +tabledata-1.3.5.dist-info/top_level.txt,sha256=wPYCjph2PxB5odPJWPADX_65iL1gAIjMQFlAyZi80iI,10 +tabledata/__init__.py,sha256=eudQG2H25UnOXi6v_OmSJOZ58y0vS9_xxGxAeNnN-Xg,762 +tabledata/__pycache__/__init__.cpython-310.pyc,, +tabledata/__pycache__/__version__.cpython-310.pyc,, +tabledata/__pycache__/_common.cpython-310.pyc,, +tabledata/__pycache__/_constant.cpython-310.pyc,, +tabledata/__pycache__/_converter.cpython-310.pyc,, +tabledata/__pycache__/_core.cpython-310.pyc,, +tabledata/__pycache__/error.cpython-310.pyc,, +tabledata/__pycache__/normalizer.cpython-310.pyc,, +tabledata/__version__.py,sha256=wly3F2A-kYk6h-JqatVFwr6pA9iDErY_A7OqvZcOSBM,268 +tabledata/_common.py,sha256=eB3xHflvbF5p5hz1f5D9xNHQCujy6Uk91NLPTy5fFHY,274 +tabledata/_constant.py,sha256=I763_Fx-9IT_ZQTTncxi04WsXd6tK78z2VBYZ3up5Aw,154 +tabledata/_converter.py,sha256=ud75_BoQAzhuzkHCZJK8QvkZoo26kCroUXCoUyCxdwA,909 +tabledata/_core.py,sha256=fBlpOotJ2ldtkdIlAf0RLpXbRnY5e7DRcx6Z9sedJEA,14473 +tabledata/_logger/__init__.py,sha256=Bvpnv_2rgv0Pj4CIiKiLRC-tPhQjGEckjfX408iTXvk,93 +tabledata/_logger/__pycache__/__init__.cpython-310.pyc,, +tabledata/_logger/__pycache__/_logger.cpython-310.pyc,, +tabledata/_logger/__pycache__/_null_logger.cpython-310.pyc,, +tabledata/_logger/_logger.py,sha256=2OlnpGVK0jGOs-at8Xgpue1zKm9Hmd62KG1D9Y5BUwA,815 +tabledata/_logger/_null_logger.py,sha256=QJuaErUIV_x6NjQ9qNX9eNSi_GB_9CrO7lKeXYZnuaw,1088 +tabledata/error.py,sha256=UGGJm3_9oLQi9GBWZz4cqp1dnzc5Kbu37c6CsiWozME,526 +tabledata/normalizer.py,sha256=MumDxG0LievF1r-D-YMoW8sc5-jV4RmT8qwCkPwSn70,6484 +tabledata/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tabledata-1.3.5.dist-info/WHEEL b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tabledata-1.3.5.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..14a883f292bc96b20c2b76a3081991f2676523a9 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tabledata-1.3.5.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (82.0.1) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tabledata-1.3.5.dist-info/top_level.txt b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tabledata-1.3.5.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..43aaf2f47a3d66da5f27d0be87b84007bd70669a --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tabledata-1.3.5.dist-info/top_level.txt @@ -0,0 +1 @@ +tabledata diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tenacity/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tenacity/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0410031af6e2a3252b49caabb4236b43c6ad0c3c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tenacity/__init__.py @@ -0,0 +1,750 @@ +# Copyright 2016-2018 Julien Danjou +# Copyright 2017 Elisey Zanko +# Copyright 2016 Étienne Bersac +# Copyright 2016 Joshua Harlow +# Copyright 2013-2014 Ray Holder +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 dataclasses +import functools +import sys +import threading +import time +import types +import typing as t +import warnings +from abc import ABC, abstractmethod +from concurrent import futures + +from . import _utils + +# Import all built-in retry strategies for easier usage. +from .retry import retry_base # noqa +from .retry import retry_all # noqa +from .retry import retry_always # noqa +from .retry import retry_any # noqa +from .retry import retry_if_exception # noqa +from .retry import retry_if_exception_type # noqa +from .retry import retry_if_exception_cause_type # noqa +from .retry import retry_if_not_exception_type # noqa +from .retry import retry_if_not_result # noqa +from .retry import retry_if_result # noqa +from .retry import retry_never # noqa +from .retry import retry_unless_exception_type # noqa +from .retry import retry_if_exception_message # noqa +from .retry import retry_if_not_exception_message # noqa + +# Import all nap strategies for easier usage. +from .nap import sleep # noqa +from .nap import sleep_using_event # noqa + +# Import all built-in stop strategies for easier usage. +from .stop import stop_after_attempt # noqa +from .stop import stop_after_delay # noqa +from .stop import stop_before_delay # noqa +from .stop import stop_all # noqa +from .stop import stop_any # noqa +from .stop import stop_never # noqa +from .stop import stop_when_event_set # noqa + +# Import all built-in wait strategies for easier usage. +from .wait import wait_chain # noqa +from .wait import wait_combine # noqa +from .wait import wait_exception # noqa +from .wait import wait_exponential # noqa +from .wait import wait_fixed # noqa +from .wait import wait_incrementing # noqa +from .wait import wait_none # noqa +from .wait import wait_random # noqa +from .wait import wait_random_exponential # noqa +from .wait import wait_random_exponential as wait_full_jitter # noqa +from .wait import wait_exponential_jitter # noqa + +# Import all built-in before strategies for easier usage. +from .before import before_log # noqa +from .before import before_nothing # noqa + +# Import all built-in after strategies for easier usage. +from .after import after_log # noqa +from .after import after_nothing # noqa + +# Import all built-in before sleep strategies for easier usage. +from .before_sleep import before_sleep_log # noqa +from .before_sleep import before_sleep_nothing # noqa + +try: + import tornado +except ImportError: + tornado = None + +if t.TYPE_CHECKING: + from typing_extensions import Self + + from . import asyncio as tasyncio + from .retry import RetryBaseT + from .stop import StopBaseT + from .wait import WaitBaseT + + +WrappedFnReturnT = t.TypeVar("WrappedFnReturnT") +WrappedFn = t.TypeVar("WrappedFn", bound=t.Callable[..., t.Any]) +P = t.ParamSpec("P") +R = t.TypeVar("R") + + +@dataclasses.dataclass(slots=True) +class IterState: + actions: t.List[t.Callable[["RetryCallState"], t.Any]] = dataclasses.field( + default_factory=list + ) + retry_run_result: bool = False + delay_since_first_attempt: int = 0 + stop_run_result: bool = False + is_explicit_retry: bool = False + + def reset(self) -> None: + self.actions = [] + self.retry_run_result = False + self.delay_since_first_attempt = 0 + self.stop_run_result = False + self.is_explicit_retry = False + + +class TryAgain(Exception): + """Always retry the executed function when raised.""" + + +NO_RESULT = object() + + +class DoAttempt: + pass + + +class DoSleep(float): + pass + + +class BaseAction: + """Base class for representing actions to take by retry object. + + Concrete implementations must define: + - __init__: to initialize all necessary fields + - REPR_FIELDS: class variable specifying attributes to include in repr(self) + - NAME: for identification in retry object methods and callbacks + """ + + REPR_FIELDS: t.Sequence[str] = () + NAME: t.Optional[str] = None + + def __repr__(self) -> str: + state_str = ", ".join( + f"{field}={getattr(self, field)!r}" for field in self.REPR_FIELDS + ) + return f"{self.__class__.__name__}({state_str})" + + def __str__(self) -> str: + return repr(self) + + +class RetryAction(BaseAction): + REPR_FIELDS = ("sleep",) + NAME = "retry" + + def __init__(self, sleep: t.SupportsFloat) -> None: + self.sleep = float(sleep) + + +_unset = object() + + +def _first_set(first: t.Union[t.Any, object], second: t.Any) -> t.Any: + return second if first is _unset else first + + +class RetryError(Exception): + """Encapsulates the last attempt instance right before giving up.""" + + def __init__(self, last_attempt: "Future") -> None: + self.last_attempt = last_attempt + super().__init__(last_attempt) + + def reraise(self) -> t.NoReturn: + if self.last_attempt.failed: + raise self.last_attempt.result() + raise self + + def __str__(self) -> str: + return f"{self.__class__.__name__}[{self.last_attempt}]" + + +class AttemptManager: + """Manage attempt context.""" + + def __init__(self, retry_state: "RetryCallState"): + self.retry_state = retry_state + + def __enter__(self) -> None: + pass + + def __exit__( + self, + exc_type: t.Optional[t.Type[BaseException]], + exc_value: t.Optional[BaseException], + traceback: t.Optional["types.TracebackType"], + ) -> t.Optional[bool]: + if exc_type is not None and exc_value is not None: + self.retry_state.set_exception((exc_type, exc_value, traceback)) + return True # Swallow exception. + else: + # We don't have the result, actually. + self.retry_state.set_result(None) + return None + + +class BaseRetrying(ABC): + def __init__( + self, + sleep: t.Callable[[t.Union[int, float]], None] = sleep, + stop: "StopBaseT" = stop_never, + wait: "WaitBaseT" = wait_none(), + retry: "RetryBaseT" = retry_if_exception_type(), + before: t.Callable[["RetryCallState"], None] = before_nothing, + after: t.Callable[["RetryCallState"], None] = after_nothing, + before_sleep: t.Optional[t.Callable[["RetryCallState"], None]] = None, + reraise: bool = False, + retry_error_cls: t.Type[RetryError] = RetryError, + retry_error_callback: t.Optional[t.Callable[["RetryCallState"], t.Any]] = None, + ): + self.sleep = sleep + self.stop = stop + self.wait = wait + self.retry = retry + self.before = before + self.after = after + self.before_sleep = before_sleep + self.reraise = reraise + self._local = threading.local() + self.retry_error_cls = retry_error_cls + self.retry_error_callback = retry_error_callback + + def copy( + self, + sleep: t.Union[t.Callable[[t.Union[int, float]], None], object] = _unset, + stop: t.Union["StopBaseT", object] = _unset, + wait: t.Union["WaitBaseT", object] = _unset, + retry: t.Union[retry_base, object] = _unset, + before: t.Union[t.Callable[["RetryCallState"], None], object] = _unset, + after: t.Union[t.Callable[["RetryCallState"], None], object] = _unset, + before_sleep: t.Union[ + t.Optional[t.Callable[["RetryCallState"], None]], object + ] = _unset, + reraise: t.Union[bool, object] = _unset, + retry_error_cls: t.Union[t.Type[RetryError], object] = _unset, + retry_error_callback: t.Union[ + t.Optional[t.Callable[["RetryCallState"], t.Any]], object + ] = _unset, + ) -> "Self": + """Copy this object with some parameters changed if needed.""" + return self.__class__( + sleep=_first_set(sleep, self.sleep), + stop=_first_set(stop, self.stop), + wait=_first_set(wait, self.wait), + retry=_first_set(retry, self.retry), + before=_first_set(before, self.before), + after=_first_set(after, self.after), + before_sleep=_first_set(before_sleep, self.before_sleep), + reraise=_first_set(reraise, self.reraise), + retry_error_cls=_first_set(retry_error_cls, self.retry_error_cls), + retry_error_callback=_first_set( + retry_error_callback, self.retry_error_callback + ), + ) + + def __repr__(self) -> str: + return ( + f"<{self.__class__.__name__} object at 0x{id(self):x} (" + f"stop={self.stop}, " + f"wait={self.wait}, " + f"sleep={self.sleep}, " + f"retry={self.retry}, " + f"before={self.before}, " + f"after={self.after})>" + ) + + @property + def statistics(self) -> t.Dict[str, t.Any]: + """Return a dictionary of runtime statistics. + + This dictionary will be empty when the controller has never been + ran. When it is running or has ran previously it should have (but + may not) have useful and/or informational keys and values when + running is underway and/or completed. + + .. warning:: The keys in this dictionary **should** be some what + stable (not changing), but there existence **may** + change between major releases as new statistics are + gathered or removed so before accessing keys ensure that + they actually exist and handle when they do not. + + .. note:: The values in this dictionary are local to the thread + running call (so if multiple threads share the same retrying + object - either directly or indirectly) they will each have + there own view of statistics they have collected (in the + future we may provide a way to aggregate the various + statistics from each thread). + """ + if not hasattr(self._local, "statistics"): + self._local.statistics = t.cast(t.Dict[str, t.Any], {}) + return self._local.statistics # type: ignore[no-any-return] + + @property + def iter_state(self) -> IterState: + if not hasattr(self._local, "iter_state"): + self._local.iter_state = IterState() + return self._local.iter_state # type: ignore[no-any-return] + + def wraps(self, f: WrappedFn) -> WrappedFn: + """Wrap a function for retrying. + + :param f: A function to wraps for retrying. + """ + + @functools.wraps( + f, functools.WRAPPER_ASSIGNMENTS + ("__defaults__", "__kwdefaults__") + ) + def wrapped_f(*args: t.Any, **kw: t.Any) -> t.Any: + # Always create a copy to prevent overwriting the local contexts when + # calling the same wrapped functions multiple times in the same stack + copy = self.copy() + wrapped_f.statistics = copy.statistics # type: ignore[attr-defined] + return copy(f, *args, **kw) + + def retry_with(*args: t.Any, **kwargs: t.Any) -> WrappedFn: + return self.copy(*args, **kwargs).wraps(f) + + # Preserve attributes + wrapped_f.retry = self # type: ignore[attr-defined] + wrapped_f.retry_with = retry_with # type: ignore[attr-defined] + wrapped_f.statistics = {} # type: ignore[attr-defined] + + return wrapped_f # type: ignore[return-value] + + def begin(self) -> None: + self.statistics.clear() + self.statistics["start_time"] = time.monotonic() + self.statistics["attempt_number"] = 1 + self.statistics["idle_for"] = 0 + + def _add_action_func(self, fn: t.Callable[..., t.Any]) -> None: + self.iter_state.actions.append(fn) + + def _run_retry(self, retry_state: "RetryCallState") -> None: + self.iter_state.retry_run_result = self.retry(retry_state) + + def _run_wait(self, retry_state: "RetryCallState") -> None: + if self.wait: + sleep = self.wait(retry_state) + else: + sleep = 0.0 + + retry_state.upcoming_sleep = sleep + + def _run_stop(self, retry_state: "RetryCallState") -> None: + self.statistics["delay_since_first_attempt"] = retry_state.seconds_since_start + self.iter_state.stop_run_result = self.stop(retry_state) + + def iter(self, retry_state: "RetryCallState") -> t.Union[DoAttempt, DoSleep, t.Any]: # noqa + self._begin_iter(retry_state) + result = None + for action in self.iter_state.actions: + result = action(retry_state) + return result + + def _begin_iter(self, retry_state: "RetryCallState") -> None: # noqa + self.iter_state.reset() + + fut = retry_state.outcome + if fut is None: + if self.before is not None: + self._add_action_func(self.before) + self._add_action_func(lambda rs: DoAttempt()) + return + + self.iter_state.is_explicit_retry = fut.failed and isinstance( + fut.exception(), TryAgain + ) + if not self.iter_state.is_explicit_retry: + self._add_action_func(self._run_retry) + self._add_action_func(self._post_retry_check_actions) + + def _post_retry_check_actions(self, retry_state: "RetryCallState") -> None: + if not (self.iter_state.is_explicit_retry or self.iter_state.retry_run_result): + self._add_action_func(lambda rs: rs.outcome.result()) + return + + if self.after is not None: + self._add_action_func(self.after) + + self._add_action_func(self._run_wait) + self._add_action_func(self._run_stop) + self._add_action_func(self._post_stop_check_actions) + + def _post_stop_check_actions(self, retry_state: "RetryCallState") -> None: + if self.iter_state.stop_run_result: + if self.retry_error_callback: + self._add_action_func(self.retry_error_callback) + return + + def exc_check(rs: "RetryCallState") -> None: + fut = t.cast(Future, rs.outcome) + retry_exc = self.retry_error_cls(fut) + if self.reraise: + raise retry_exc.reraise() + raise retry_exc from fut.exception() + + self._add_action_func(exc_check) + return + + def next_action(rs: "RetryCallState") -> None: + sleep = rs.upcoming_sleep + rs.next_action = RetryAction(sleep) + rs.idle_for += sleep + self.statistics["idle_for"] += sleep + self.statistics["attempt_number"] += 1 + + self._add_action_func(next_action) + + if self.before_sleep is not None: + self._add_action_func(self.before_sleep) + + self._add_action_func(lambda rs: DoSleep(rs.upcoming_sleep)) + + def __iter__(self) -> t.Generator[AttemptManager, None, None]: + self.begin() + + retry_state = RetryCallState(self, fn=None, args=(), kwargs={}) + while True: + do = self.iter(retry_state=retry_state) + if isinstance(do, DoAttempt): + yield AttemptManager(retry_state=retry_state) + elif isinstance(do, DoSleep): + retry_state.prepare_for_next_attempt() + self.sleep(do) + else: + break + + @abstractmethod + def __call__( + self, + fn: t.Callable[..., WrappedFnReturnT], + *args: t.Any, + **kwargs: t.Any, + ) -> WrappedFnReturnT: + pass + + +class Retrying(BaseRetrying): + """Retrying controller.""" + + def __call__( + self, + fn: t.Callable[..., WrappedFnReturnT], + *args: t.Any, + **kwargs: t.Any, + ) -> WrappedFnReturnT: + self.begin() + + retry_state = RetryCallState(retry_object=self, fn=fn, args=args, kwargs=kwargs) + while True: + do = self.iter(retry_state=retry_state) + if isinstance(do, DoAttempt): + try: + result = fn(*args, **kwargs) + except BaseException: # noqa: B902 + retry_state.set_exception(sys.exc_info()) # type: ignore[arg-type] + else: + retry_state.set_result(result) + elif isinstance(do, DoSleep): + retry_state.prepare_for_next_attempt() + self.sleep(do) + else: + return do # type: ignore[no-any-return] + + +class Future(futures.Future[t.Any]): + """Encapsulates a (future or past) attempted call to a target function.""" + + def __init__(self, attempt_number: int) -> None: + super().__init__() + self.attempt_number = attempt_number + + @property + def failed(self) -> bool: + """Return whether a exception is being held in this future.""" + return self.exception() is not None + + @classmethod + def construct( + cls, attempt_number: int, value: t.Any, has_exception: bool + ) -> "Future": + """Construct a new Future object.""" + fut = cls(attempt_number) + if has_exception: + fut.set_exception(value) + else: + fut.set_result(value) + return fut + + +class RetryCallState: + """State related to a single call wrapped with Retrying.""" + + def __init__( + self, + retry_object: BaseRetrying, + fn: t.Optional[WrappedFn], + args: t.Any, + kwargs: t.Any, + ) -> None: + #: Retry call start timestamp + self.start_time = time.monotonic() + #: Retry manager object + self.retry_object = retry_object + #: Function wrapped by this retry call + self.fn = fn + #: Arguments of the function wrapped by this retry call + self.args = args + #: Keyword arguments of the function wrapped by this retry call + self.kwargs = kwargs + + #: The number of the current attempt + self.attempt_number: int = 1 + #: Last outcome (result or exception) produced by the function + self.outcome: t.Optional[Future] = None + #: Timestamp of the last outcome + self.outcome_timestamp: t.Optional[float] = None + #: Time spent sleeping in retries + self.idle_for: float = 0.0 + #: Next action as decided by the retry manager + self.next_action: t.Optional[RetryAction] = None + #: Next sleep time as decided by the retry manager. + self.upcoming_sleep: float = 0.0 + + @property + def seconds_since_start(self) -> t.Optional[float]: + if self.outcome_timestamp is None: + return None + return self.outcome_timestamp - self.start_time + + def prepare_for_next_attempt(self) -> None: + self.outcome = None + self.outcome_timestamp = None + self.attempt_number += 1 + self.next_action = None + + def set_result(self, val: t.Any) -> None: + ts = time.monotonic() + fut = Future(self.attempt_number) + fut.set_result(val) + self.outcome, self.outcome_timestamp = fut, ts + + def set_exception( + self, + exc_info: t.Tuple[ + t.Type[BaseException], BaseException, "types.TracebackType| None" + ], + ) -> None: + ts = time.monotonic() + fut = Future(self.attempt_number) + fut.set_exception(exc_info[1]) + self.outcome, self.outcome_timestamp = fut, ts + + def __repr__(self) -> str: + if self.outcome is None: + result = "none yet" + elif self.outcome.failed: + exception = self.outcome.exception() + result = f"failed ({exception.__class__.__name__} {exception})" + else: + result = f"returned {self.outcome.result()}" + + slept = float(round(self.idle_for, 2)) + clsname = self.__class__.__name__ + return f"<{clsname} {id(self)}: attempt #{self.attempt_number}; slept for {slept}; last result: {result}>" + + +class _AsyncRetryDecorator(t.Protocol): + @t.overload + def __call__( + self, fn: "t.Callable[P, types.CoroutineType[t.Any, t.Any, R]]" + ) -> "t.Callable[P, types.CoroutineType[t.Any, t.Any, R]]": ... + @t.overload + def __call__( + self, fn: t.Callable[P, t.Coroutine[t.Any, t.Any, R]] + ) -> t.Callable[P, t.Coroutine[t.Any, t.Any, R]]: ... + @t.overload + def __call__( + self, fn: t.Callable[P, t.Awaitable[R]] + ) -> t.Callable[P, t.Awaitable[R]]: ... + @t.overload + def __call__(self, fn: t.Callable[P, R]) -> t.Callable[P, t.Awaitable[R]]: ... + + +@t.overload +def retry(func: WrappedFn) -> WrappedFn: ... + + +@t.overload +def retry( + *, + sleep: t.Callable[[t.Union[int, float]], t.Awaitable[None]], + stop: "StopBaseT" = ..., + wait: "WaitBaseT" = ..., + retry: "t.Union[RetryBaseT, tasyncio.retry.RetryBaseT]" = ..., + before: t.Callable[["RetryCallState"], t.Union[None, t.Awaitable[None]]] = ..., + after: t.Callable[["RetryCallState"], t.Union[None, t.Awaitable[None]]] = ..., + before_sleep: t.Optional[ + t.Callable[["RetryCallState"], t.Union[None, t.Awaitable[None]]] + ] = ..., + reraise: bool = ..., + retry_error_cls: t.Type["RetryError"] = ..., + retry_error_callback: t.Optional[ + t.Callable[["RetryCallState"], t.Union[t.Any, t.Awaitable[t.Any]]] + ] = ..., +) -> _AsyncRetryDecorator: ... + + +@t.overload +def retry( + sleep: t.Callable[[t.Union[int, float]], None] = sleep, + stop: "StopBaseT" = stop_never, + wait: "WaitBaseT" = wait_none(), + retry: "t.Union[RetryBaseT, tasyncio.retry.RetryBaseT]" = retry_if_exception_type(), + before: t.Callable[ + ["RetryCallState"], t.Union[None, t.Awaitable[None]] + ] = before_nothing, + after: t.Callable[ + ["RetryCallState"], t.Union[None, t.Awaitable[None]] + ] = after_nothing, + before_sleep: t.Optional[ + t.Callable[["RetryCallState"], t.Union[None, t.Awaitable[None]]] + ] = None, + reraise: bool = False, + retry_error_cls: t.Type["RetryError"] = RetryError, + retry_error_callback: t.Optional[ + t.Callable[["RetryCallState"], t.Union[t.Any, t.Awaitable[t.Any]]] + ] = None, +) -> t.Callable[[WrappedFn], WrappedFn]: ... + + +def retry(*dargs: t.Any, **dkw: t.Any) -> t.Any: + """Wrap a function with a new `Retrying` object. + + :param dargs: positional arguments passed to Retrying object + :param dkw: keyword arguments passed to the Retrying object + """ + # support both @retry and @retry() as valid syntax + if len(dargs) == 1 and callable(dargs[0]): + return retry()(dargs[0]) + else: + + def wrap(f: WrappedFn) -> WrappedFn: + if isinstance(f, retry_base): + warnings.warn( + f"Got retry_base instance ({f.__class__.__name__}) as callable argument, " + f"this will probably hang indefinitely (did you mean retry={f.__class__.__name__}(...)?)" + ) + r: "BaseRetrying" + sleep = dkw.get("sleep") + if _utils.is_coroutine_callable(f) or ( + sleep is not None and _utils.is_coroutine_callable(sleep) + ): + r = AsyncRetrying(*dargs, **dkw) + elif ( + tornado + and hasattr(tornado.gen, "is_coroutine_function") + and tornado.gen.is_coroutine_function(f) + ): + r = TornadoRetrying(*dargs, **dkw) + else: + r = Retrying(*dargs, **dkw) + + return r.wraps(f) + + return wrap + + +from tenacity.asyncio import AsyncRetrying # noqa:E402,I100 + +if tornado: + from tenacity.tornadoweb import TornadoRetrying + + +__all__ = [ + "retry_base", + "retry_all", + "retry_always", + "retry_any", + "retry_if_exception", + "retry_if_exception_type", + "retry_if_exception_cause_type", + "retry_if_not_exception_type", + "retry_if_not_result", + "retry_if_result", + "retry_never", + "retry_unless_exception_type", + "retry_if_exception_message", + "retry_if_not_exception_message", + "sleep", + "sleep_using_event", + "stop_after_attempt", + "stop_after_delay", + "stop_before_delay", + "stop_all", + "stop_any", + "stop_never", + "stop_when_event_set", + "wait_chain", + "wait_combine", + "wait_exception", + "wait_exponential", + "wait_fixed", + "wait_incrementing", + "wait_none", + "wait_random", + "wait_random_exponential", + "wait_full_jitter", + "wait_exponential_jitter", + "before_log", + "before_nothing", + "after_log", + "after_nothing", + "before_sleep_log", + "before_sleep_nothing", + "retry", + "WrappedFn", + "TryAgain", + "NO_RESULT", + "DoAttempt", + "DoSleep", + "BaseAction", + "RetryAction", + "RetryError", + "AttemptManager", + "BaseRetrying", + "Retrying", + "Future", + "RetryCallState", + "AsyncRetrying", +] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tenacity/_utils.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tenacity/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..be148719b59a38b1ddc253f34709a49418dda60b --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tenacity/_utils.py @@ -0,0 +1,113 @@ +# Copyright 2016 Julien Danjou +# Copyright 2016 Joshua Harlow +# Copyright 2013-2014 Ray Holder +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 functools +import inspect +import sys +import typing +from datetime import timedelta + + +# sys.maxsize: +# An integer giving the maximum value a variable of type Py_ssize_t can take. +MAX_WAIT = sys.maxsize / 2 + + +class LoggerProtocol(typing.Protocol): + """ + Protocol used by utils expecting a logger (eg: before_log). + + Compatible with logging, structlog, loguru, etc... + """ + + def log( + self, level: int, msg: str, /, *args: typing.Any, **kwargs: typing.Any + ) -> typing.Any: ... + + +def find_ordinal(pos_num: int) -> str: + # See: https://en.wikipedia.org/wiki/English_numerals#Ordinal_numbers + if pos_num == 0: + return "th" + elif pos_num == 1: + return "st" + elif pos_num == 2: + return "nd" + elif pos_num == 3: + return "rd" + elif 4 <= pos_num <= 20: + return "th" + else: + return find_ordinal(pos_num % 10) + + +def to_ordinal(pos_num: int) -> str: + return f"{pos_num}{find_ordinal(pos_num)}" + + +def get_callback_name(cb: typing.Callable[..., typing.Any]) -> str: + """Get a callback fully-qualified name. + + If no name can be produced ``repr(cb)`` is called and returned. + """ + segments = [] + try: + segments.append(cb.__qualname__) + except AttributeError: + try: + segments.append(cb.__name__) + except AttributeError: + pass + if not segments: + return repr(cb) + else: + try: + # When running under sphinx it appears this can be none? + if cb.__module__: + segments.insert(0, cb.__module__) + except AttributeError: + pass + return ".".join(segments) + + +time_unit_type = typing.Union[int, float, timedelta] + + +def to_seconds(time_unit: time_unit_type) -> float: + return float( + time_unit.total_seconds() if isinstance(time_unit, timedelta) else time_unit + ) + + +def is_coroutine_callable(call: typing.Callable[..., typing.Any]) -> bool: + if inspect.isclass(call): + return False + if inspect.iscoroutinefunction(call): + return True + partial_call = isinstance(call, functools.partial) and call.func + dunder_call = partial_call or getattr(call, "__call__", None) + return inspect.iscoroutinefunction(dunder_call) + + +def wrap_to_async_func( + call: typing.Callable[..., typing.Any], +) -> typing.Callable[..., typing.Awaitable[typing.Any]]: + if is_coroutine_callable(call): + return call + + async def inner(*args: typing.Any, **kwargs: typing.Any) -> typing.Any: + return call(*args, **kwargs) + + return inner diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tenacity/after.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tenacity/after.py new file mode 100644 index 0000000000000000000000000000000000000000..a4b892241c9ffbe439f324fab75dd9fdf72cd850 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tenacity/after.py @@ -0,0 +1,49 @@ +# Copyright 2016 Julien Danjou +# Copyright 2016 Joshua Harlow +# Copyright 2013-2014 Ray Holder +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 typing + +from tenacity import _utils + +if typing.TYPE_CHECKING: + from tenacity import RetryCallState + + +def after_nothing(retry_state: "RetryCallState") -> None: + """After call strategy that does nothing.""" + + +def after_log( + logger: _utils.LoggerProtocol, + log_level: int, + sec_format: str = "%.3g", +) -> typing.Callable[["RetryCallState"], None]: + """After call strategy that logs to some logger the finished attempt.""" + + def log_it(retry_state: "RetryCallState") -> None: + if retry_state.fn is None: + # NOTE(sileht): can't really happen, but we must please mypy + fn_name = "" + else: + fn_name = _utils.get_callback_name(retry_state.fn) + logger.log( + log_level, + f"Finished call to '{fn_name}' " + f"after {sec_format % retry_state.seconds_since_start}(s), " + f"this was the {_utils.to_ordinal(retry_state.attempt_number)} time calling it.", + ) + + return log_it diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tenacity/before.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tenacity/before.py new file mode 100644 index 0000000000000000000000000000000000000000..5d9aa24ec51e01d72dd4a42b37c420c8a283ef6d --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tenacity/before.py @@ -0,0 +1,46 @@ +# Copyright 2016 Julien Danjou +# Copyright 2016 Joshua Harlow +# Copyright 2013-2014 Ray Holder +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 typing + +from tenacity import _utils + +if typing.TYPE_CHECKING: + from tenacity import RetryCallState + + +def before_nothing(retry_state: "RetryCallState") -> None: + """Before call strategy that does nothing.""" + + +def before_log( + logger: _utils.LoggerProtocol, log_level: int +) -> typing.Callable[["RetryCallState"], None]: + """Before call strategy that logs to some logger the attempt.""" + + def log_it(retry_state: "RetryCallState") -> None: + if retry_state.fn is None: + # NOTE(sileht): can't really happen, but we must please mypy + fn_name = "" + else: + fn_name = _utils.get_callback_name(retry_state.fn) + logger.log( + log_level, + f"Starting call to '{fn_name}', " + f"this is the {_utils.to_ordinal(retry_state.attempt_number)} time calling it.", + ) + + return log_it diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tenacity/before_sleep.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tenacity/before_sleep.py new file mode 100644 index 0000000000000000000000000000000000000000..a822cb863979a166f2e95922137d356fc16b3b6a --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tenacity/before_sleep.py @@ -0,0 +1,71 @@ +# Copyright 2016 Julien Danjou +# Copyright 2016 Joshua Harlow +# Copyright 2013-2014 Ray Holder +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 typing + +from tenacity import _utils + +if typing.TYPE_CHECKING: + from tenacity import RetryCallState + + +def before_sleep_nothing(retry_state: "RetryCallState") -> None: + """Before sleep strategy that does nothing.""" + + +def before_sleep_log( + logger: _utils.LoggerProtocol, + log_level: int, + exc_info: bool = False, + sec_format: str = "%.3g", +) -> typing.Callable[["RetryCallState"], None]: + """Before sleep strategy that logs to some logger the attempt.""" + + def log_it(retry_state: "RetryCallState") -> None: + local_exc_info: BaseException | bool | None + + if retry_state.outcome is None: + raise RuntimeError("log_it() called before outcome was set") + + if retry_state.next_action is None: + raise RuntimeError("log_it() called before next_action was set") + + if retry_state.outcome.failed: + ex = retry_state.outcome.exception() + verb, value = "raised", f"{ex.__class__.__name__}: {ex}" + + if exc_info: + local_exc_info = retry_state.outcome.exception() + else: + local_exc_info = False + else: + verb, value = "returned", retry_state.outcome.result() + local_exc_info = False # exc_info does not apply when no exception + + if retry_state.fn is None: + # NOTE(sileht): can't really happen, but we must please mypy + fn_name = "" + else: + fn_name = _utils.get_callback_name(retry_state.fn) + + logger.log( + log_level, + f"Retrying {fn_name} " + f"in {sec_format % retry_state.next_action.sleep} seconds as it {verb} {value}.", + exc_info=local_exc_info, + ) + + return log_it diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tenacity/nap.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tenacity/nap.py new file mode 100644 index 0000000000000000000000000000000000000000..72aa5bfd4b60d8e6ef6ed0cf2ae4f763d12195cc --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tenacity/nap.py @@ -0,0 +1,43 @@ +# Copyright 2016 Étienne Bersac +# Copyright 2016 Julien Danjou +# Copyright 2016 Joshua Harlow +# Copyright 2013-2014 Ray Holder +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 time +import typing + +if typing.TYPE_CHECKING: + import threading + + +def sleep(seconds: float) -> None: + """ + Sleep strategy that delays execution for a given number of seconds. + + This is the default strategy, and may be mocked out for unit testing. + """ + time.sleep(seconds) + + +class sleep_using_event: + """Sleep strategy that waits on an event to be set.""" + + def __init__(self, event: "threading.Event") -> None: + self.event = event + + def __call__(self, timeout: typing.Optional[float]) -> None: + # NOTE(harlowja): this may *not* actually wait for timeout + # seconds if the event is set (ie this may eject out early). + self.event.wait(timeout=timeout) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tenacity/py.typed b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tenacity/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tenacity/retry.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tenacity/retry.py new file mode 100644 index 0000000000000000000000000000000000000000..9f099ec06c331ba36986690f3e1e91d256a3da3b --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tenacity/retry.py @@ -0,0 +1,282 @@ +# Copyright 2016–2021 Julien Danjou +# Copyright 2016 Joshua Harlow +# Copyright 2013-2014 Ray Holder +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +import re +import typing + +if typing.TYPE_CHECKING: + from tenacity import RetryCallState + + +class retry_base(abc.ABC): + """Abstract base class for retry strategies.""" + + @abc.abstractmethod + def __call__(self, retry_state: "RetryCallState") -> bool: + pass + + def __and__(self, other: "retry_base") -> "retry_all": + return other.__rand__(self) + + def __rand__(self, other: "retry_base") -> "retry_all": + return retry_all(other, self) + + def __or__(self, other: "retry_base") -> "retry_any": + return other.__ror__(self) + + def __ror__(self, other: "retry_base") -> "retry_any": + return retry_any(other, self) + + +RetryBaseT = typing.Union[retry_base, typing.Callable[["RetryCallState"], bool]] + + +class _retry_never(retry_base): + """Retry strategy that never rejects any result.""" + + def __call__(self, retry_state: "RetryCallState") -> bool: + return False + + +retry_never = _retry_never() + + +class _retry_always(retry_base): + """Retry strategy that always rejects any result.""" + + def __call__(self, retry_state: "RetryCallState") -> bool: + return True + + +retry_always = _retry_always() + + +class retry_if_exception(retry_base): + """Retry strategy that retries if an exception verifies a predicate.""" + + def __init__(self, predicate: typing.Callable[[BaseException], bool]) -> None: + self.predicate = predicate + + def __call__(self, retry_state: "RetryCallState") -> bool: + if retry_state.outcome is None: + raise RuntimeError("__call__() called before outcome was set") + + if retry_state.outcome.failed: + exception = retry_state.outcome.exception() + if exception is None: + raise RuntimeError("outcome failed but the exception is None") + return self.predicate(exception) + else: + return False + + +class retry_if_exception_type(retry_if_exception): + """Retries if an exception has been raised of one or more types.""" + + def __init__( + self, + exception_types: typing.Union[ + typing.Type[BaseException], + typing.Tuple[typing.Type[BaseException], ...], + ] = Exception, + ) -> None: + self.exception_types = exception_types + super().__init__(lambda e: isinstance(e, exception_types)) + + +class retry_if_not_exception_type(retry_if_exception): + """Retries except an exception has been raised of one or more types.""" + + def __init__( + self, + exception_types: typing.Union[ + typing.Type[BaseException], + typing.Tuple[typing.Type[BaseException], ...], + ] = Exception, + ) -> None: + self.exception_types = exception_types + super().__init__(lambda e: not isinstance(e, exception_types)) + + +class retry_unless_exception_type(retry_if_exception): + """Retries until an exception is raised of one or more types.""" + + def __init__( + self, + exception_types: typing.Union[ + typing.Type[BaseException], + typing.Tuple[typing.Type[BaseException], ...], + ] = Exception, + ) -> None: + self.exception_types = exception_types + super().__init__(lambda e: not isinstance(e, exception_types)) + + def __call__(self, retry_state: "RetryCallState") -> bool: + if retry_state.outcome is None: + raise RuntimeError("__call__() called before outcome was set") + + # always retry if no exception was raised + if not retry_state.outcome.failed: + return True + + exception = retry_state.outcome.exception() + if exception is None: + raise RuntimeError("outcome failed but the exception is None") + return self.predicate(exception) + + +class retry_if_exception_cause_type(retry_base): + """Retries if any of the causes of the raised exception is of one or more types. + + The check on the type of the cause of the exception is done recursively (until finding + an exception in the chain that has no `__cause__`) + """ + + def __init__( + self, + exception_types: typing.Union[ + typing.Type[BaseException], + typing.Tuple[typing.Type[BaseException], ...], + ] = Exception, + ) -> None: + self.exception_cause_types = exception_types + + def __call__(self, retry_state: "RetryCallState") -> bool: + if retry_state.outcome is None: + raise RuntimeError("__call__ called before outcome was set") + + if retry_state.outcome.failed: + exc = retry_state.outcome.exception() + while exc is not None: + if isinstance(exc.__cause__, self.exception_cause_types): + return True + exc = exc.__cause__ + + return False + + +class retry_if_result(retry_base): + """Retries if the result verifies a predicate.""" + + def __init__(self, predicate: typing.Callable[[typing.Any], bool]) -> None: + self.predicate = predicate + + def __call__(self, retry_state: "RetryCallState") -> bool: + if retry_state.outcome is None: + raise RuntimeError("__call__() called before outcome was set") + + if not retry_state.outcome.failed: + return self.predicate(retry_state.outcome.result()) + else: + return False + + +class retry_if_not_result(retry_base): + """Retries if the result refutes a predicate.""" + + def __init__(self, predicate: typing.Callable[[typing.Any], bool]) -> None: + self.predicate = predicate + + def __call__(self, retry_state: "RetryCallState") -> bool: + if retry_state.outcome is None: + raise RuntimeError("__call__() called before outcome was set") + + if not retry_state.outcome.failed: + return not self.predicate(retry_state.outcome.result()) + else: + return False + + +class retry_if_exception_message(retry_if_exception): + """Retries if an exception message equals or matches.""" + + def __init__( + self, + message: typing.Optional[str] = None, + match: typing.Union[None, str, typing.Pattern[str]] = None, + ) -> None: + if message and match: + raise TypeError( + f"{self.__class__.__name__}() takes either 'message' or 'match', not both" + ) + + # set predicate + if message: + + def message_fnc(exception: BaseException) -> bool: + return message == str(exception) + + predicate = message_fnc + elif match: + prog = re.compile(match) + + def match_fnc(exception: BaseException) -> bool: + return bool(prog.match(str(exception))) + + predicate = match_fnc + else: + raise TypeError( + f"{self.__class__.__name__}() missing 1 required argument 'message' or 'match'" + ) + + super().__init__(predicate) + + +class retry_if_not_exception_message(retry_if_exception_message): + """Retries until an exception message equals or matches.""" + + def __init__( + self, + message: typing.Optional[str] = None, + match: typing.Union[None, str, typing.Pattern[str]] = None, + ) -> None: + super().__init__(message, match) + # invert predicate + if_predicate = self.predicate + self.predicate = lambda *args_, **kwargs_: not if_predicate(*args_, **kwargs_) + + def __call__(self, retry_state: "RetryCallState") -> bool: + if retry_state.outcome is None: + raise RuntimeError("__call__() called before outcome was set") + + if not retry_state.outcome.failed: + return True + + exception = retry_state.outcome.exception() + if exception is None: + raise RuntimeError("outcome failed but the exception is None") + return self.predicate(exception) + + +class retry_any(retry_base): + """Retries if any of the retries condition is valid.""" + + def __init__(self, *retries: retry_base) -> None: + self.retries = retries + + def __call__(self, retry_state: "RetryCallState") -> bool: + return any(r(retry_state) for r in self.retries) + + +class retry_all(retry_base): + """Retries if all the retries condition are valid.""" + + def __init__(self, *retries: retry_base) -> None: + self.retries = retries + + def __call__(self, retry_state: "RetryCallState") -> bool: + return all(r(retry_state) for r in self.retries) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tenacity/stop.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tenacity/stop.py new file mode 100644 index 0000000000000000000000000000000000000000..5cda59ab21727eae5de4c60a0622314103f8e973 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tenacity/stop.py @@ -0,0 +1,130 @@ +# Copyright 2016–2021 Julien Danjou +# Copyright 2016 Joshua Harlow +# Copyright 2013-2014 Ray Holder +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +import typing + +from tenacity import _utils + +if typing.TYPE_CHECKING: + import threading + + from tenacity import RetryCallState + + +class stop_base(abc.ABC): + """Abstract base class for stop strategies.""" + + @abc.abstractmethod + def __call__(self, retry_state: "RetryCallState") -> bool: + pass + + def __and__(self, other: "stop_base") -> "stop_all": + return stop_all(self, other) + + def __or__(self, other: "stop_base") -> "stop_any": + return stop_any(self, other) + + +StopBaseT = typing.Union[stop_base, typing.Callable[["RetryCallState"], bool]] + + +class stop_any(stop_base): + """Stop if any of the stop condition is valid.""" + + def __init__(self, *stops: stop_base) -> None: + self.stops = stops + + def __call__(self, retry_state: "RetryCallState") -> bool: + return any(x(retry_state) for x in self.stops) + + +class stop_all(stop_base): + """Stop if all the stop conditions are valid.""" + + def __init__(self, *stops: stop_base) -> None: + self.stops = stops + + def __call__(self, retry_state: "RetryCallState") -> bool: + return all(x(retry_state) for x in self.stops) + + +class _stop_never(stop_base): + """Never stop.""" + + def __call__(self, retry_state: "RetryCallState") -> bool: + return False + + +stop_never = _stop_never() + + +class stop_when_event_set(stop_base): + """Stop when the given event is set.""" + + def __init__(self, event: "threading.Event") -> None: + self.event = event + + def __call__(self, retry_state: "RetryCallState") -> bool: + return self.event.is_set() + + +class stop_after_attempt(stop_base): + """Stop when the previous attempt >= max_attempt.""" + + def __init__(self, max_attempt_number: int) -> None: + self.max_attempt_number = max_attempt_number + + def __call__(self, retry_state: "RetryCallState") -> bool: + return retry_state.attempt_number >= self.max_attempt_number + + +class stop_after_delay(stop_base): + """ + Stop when the time from the first attempt >= limit. + + Note: `max_delay` will be exceeded, so when used with a `wait`, the actual total delay will be greater + than `max_delay` by some of the final sleep period before `max_delay` is exceeded. + + If you need stricter timing with waits, consider `stop_before_delay` instead. + """ + + def __init__(self, max_delay: _utils.time_unit_type) -> None: + self.max_delay = _utils.to_seconds(max_delay) + + def __call__(self, retry_state: "RetryCallState") -> bool: + if retry_state.seconds_since_start is None: + raise RuntimeError("__call__() called but seconds_since_start is not set") + return retry_state.seconds_since_start >= self.max_delay + + +class stop_before_delay(stop_base): + """ + Stop right before the next attempt would take place after the time from the first attempt >= limit. + + Most useful when you are using with a `wait` function like wait_random_exponential, but need to make + sure that the max_delay is not exceeded. + """ + + def __init__(self, max_delay: _utils.time_unit_type) -> None: + self.max_delay = _utils.to_seconds(max_delay) + + def __call__(self, retry_state: "RetryCallState") -> bool: + if retry_state.seconds_since_start is None: + raise RuntimeError("__call__() called but seconds_since_start is not set") + return ( + retry_state.seconds_since_start + retry_state.upcoming_sleep + >= self.max_delay + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tenacity/tornadoweb.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tenacity/tornadoweb.py new file mode 100644 index 0000000000000000000000000000000000000000..a0aa64914a96b3f7dc635a0dd620e3b06fb45d6f --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tenacity/tornadoweb.py @@ -0,0 +1,63 @@ +# Copyright 2017 Elisey Zanko +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 sys +import typing + +from tenacity import BaseRetrying +from tenacity import DoAttempt +from tenacity import DoSleep +from tenacity import RetryCallState + +from tornado import gen + +if typing.TYPE_CHECKING: + from tornado.concurrent import Future + +_RetValT = typing.TypeVar("_RetValT") + + +class TornadoRetrying(BaseRetrying): + def __init__( + self, + sleep: "typing.Callable[[float], Future[None]]" = gen.sleep, + **kwargs: typing.Any, + ) -> None: + super().__init__(**kwargs) + self.sleep = sleep + + @gen.coroutine # type: ignore[untyped-decorator] + def __call__( + self, + fn: "typing.Callable[..., typing.Union[typing.Generator[typing.Any, typing.Any, _RetValT], Future[_RetValT]]]", + *args: typing.Any, + **kwargs: typing.Any, + ) -> "typing.Generator[typing.Any, typing.Any, _RetValT]": + self.begin() + + retry_state = RetryCallState(retry_object=self, fn=fn, args=args, kwargs=kwargs) + while True: + do = self.iter(retry_state=retry_state) + if isinstance(do, DoAttempt): + try: + result = yield fn(*args, **kwargs) + except BaseException: # noqa: B902 + retry_state.set_exception(sys.exc_info()) # type: ignore[arg-type] + else: + retry_state.set_result(result) + elif isinstance(do, DoSleep): + retry_state.prepare_for_next_attempt() + yield self.sleep(do) + else: + raise gen.Return(do) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tenacity/wait.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tenacity/wait.py new file mode 100644 index 0000000000000000000000000000000000000000..1cc17ea20427645e07e24ac4d0fa08fe8bc15013 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tenacity/wait.py @@ -0,0 +1,273 @@ +# Copyright 2016–2021 Julien Danjou +# Copyright 2016 Joshua Harlow +# Copyright 2013-2014 Ray Holder +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +import random +import typing + +from tenacity import _utils + +if typing.TYPE_CHECKING: + from tenacity import RetryCallState + + +class wait_base(abc.ABC): + """Abstract base class for wait strategies.""" + + @abc.abstractmethod + def __call__(self, retry_state: "RetryCallState") -> float: + pass + + def __add__(self, other: "wait_base") -> "wait_combine": + return wait_combine(self, other) + + def __radd__(self, other: "wait_base") -> typing.Union["wait_combine", "wait_base"]: + # make it possible to use multiple waits with the built-in sum function + if other == 0: # type: ignore[comparison-overlap] + return self + return self.__add__(other) + + +WaitBaseT = typing.Union[ + wait_base, typing.Callable[["RetryCallState"], typing.Union[float, int]] +] + + +class wait_fixed(wait_base): + """Wait strategy that waits a fixed amount of time between each retry.""" + + def __init__(self, wait: _utils.time_unit_type) -> None: + self.wait_fixed = _utils.to_seconds(wait) + + def __call__(self, retry_state: "RetryCallState") -> float: + return self.wait_fixed + + +class wait_none(wait_fixed): + """Wait strategy that doesn't wait at all before retrying.""" + + def __init__(self) -> None: + super().__init__(0) + + +class wait_random(wait_base): + """Wait strategy that waits a random amount of time between min/max.""" + + def __init__( + self, min: _utils.time_unit_type = 0, max: _utils.time_unit_type = 1 + ) -> None: # noqa + self.wait_random_min = _utils.to_seconds(min) + self.wait_random_max = _utils.to_seconds(max) + + def __call__(self, retry_state: "RetryCallState") -> float: + return self.wait_random_min + ( + random.random() * (self.wait_random_max - self.wait_random_min) + ) + + +class wait_combine(wait_base): + """Combine several waiting strategies.""" + + def __init__(self, *strategies: wait_base) -> None: + self.wait_funcs = strategies + + def __call__(self, retry_state: "RetryCallState") -> float: + return sum(x(retry_state=retry_state) for x in self.wait_funcs) + + +class wait_chain(wait_base): + """Chain two or more waiting strategies. + + If all strategies are exhausted, the very last strategy is used + thereafter. + + For example:: + + @retry(wait=wait_chain(*[wait_fixed(1) for i in range(3)] + + [wait_fixed(2) for j in range(5)] + + [wait_fixed(5) for k in range(4)])) + def wait_chained(): + print("Wait 1s for 3 attempts, 2s for 5 attempts and 5s " + "thereafter.") + """ + + def __init__(self, *strategies: wait_base) -> None: + self.strategies = strategies + + def __call__(self, retry_state: "RetryCallState") -> float: + wait_func_no = min(max(retry_state.attempt_number, 1), len(self.strategies)) + wait_func = self.strategies[wait_func_no - 1] + return wait_func(retry_state=retry_state) + + +class wait_exception(wait_base): + """Wait strategy that waits the amount of time returned by the predicate. + + The predicate is passed the exception object. Based on the exception, the + user can decide how much time to wait before retrying. + + For example:: + + def http_error(exception: BaseException) -> float: + if ( + isinstance(exception, requests.HTTPError) + and exception.response.status_code == requests.codes.too_many_requests + ): + return float(exception.response.headers.get("Retry-After", "1")) + return 60.0 + + + @retry( + stop=stop_after_attempt(3), + wait=wait_exception(http_error), + ) + def http_get_request(url: str) -> None: + response = requests.get(url) + response.raise_for_status() + """ + + def __init__(self, predicate: typing.Callable[[BaseException], float]) -> None: + self.predicate = predicate + + def __call__(self, retry_state: "RetryCallState") -> float: + if retry_state.outcome is None: + raise RuntimeError("__call__() called before outcome was set") + + exception = retry_state.outcome.exception() + if exception is None: + raise RuntimeError("outcome failed but the exception is None") + return self.predicate(exception) + + +class wait_incrementing(wait_base): + """Wait an incremental amount of time after each attempt. + + Starting at a starting value and incrementing by a value for each attempt + (and restricting the upper limit to some maximum value). + """ + + def __init__( + self, + start: _utils.time_unit_type = 0, + increment: _utils.time_unit_type = 100, + max: _utils.time_unit_type = _utils.MAX_WAIT, # noqa + ) -> None: + self.start = _utils.to_seconds(start) + self.increment = _utils.to_seconds(increment) + self.max = _utils.to_seconds(max) + + def __call__(self, retry_state: "RetryCallState") -> float: + result = self.start + (self.increment * (retry_state.attempt_number - 1)) + return max(0, min(result, self.max)) + + +class wait_exponential(wait_base): + """Wait strategy that applies exponential backoff. + + It allows for a customized multiplier and an ability to restrict the + upper and lower limits to some maximum and minimum value. + + The intervals are fixed (i.e. there is no jitter), so this strategy is + suitable for balancing retries against latency when a required resource is + unavailable for an unknown duration, but *not* suitable for resolving + contention between multiple processes for a shared resource. Use + wait_random_exponential for the latter case. + """ + + def __init__( + self, + multiplier: typing.Union[int, float] = 1, + max: _utils.time_unit_type = _utils.MAX_WAIT, # noqa + exp_base: typing.Union[int, float] = 2, + min: _utils.time_unit_type = 0, # noqa + ) -> None: + self.multiplier = multiplier + self.min = _utils.to_seconds(min) + self.max = _utils.to_seconds(max) + self.exp_base = exp_base + + def __call__(self, retry_state: "RetryCallState") -> float: + try: + exp = self.exp_base ** (retry_state.attempt_number - 1) + result = self.multiplier * exp + except OverflowError: + return self.max + return max(max(0, self.min), min(result, self.max)) + + +class wait_random_exponential(wait_exponential): + """Random wait with exponentially widening window. + + An exponential backoff strategy used to mediate contention between multiple + uncoordinated processes for a shared resource in distributed systems. This + is the sense in which "exponential backoff" is meant in e.g. Ethernet + networking, and corresponds to the "Full Jitter" algorithm described in + this blog post: + + https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/ + + Each retry occurs at a random time in a geometrically expanding interval. + It allows for a custom multiplier and an ability to restrict the upper + limit of the random interval to some maximum value. + + Example:: + + wait_random_exponential(multiplier=0.5, # initial window 0.5s + max=60) # max 60s timeout + + When waiting for an unavailable resource to become available again, as + opposed to trying to resolve contention for a shared resource, the + wait_exponential strategy (which uses a fixed interval) may be preferable. + + """ + + def __call__(self, retry_state: "RetryCallState") -> float: + high = super().__call__(retry_state=retry_state) + return random.uniform(self.min, high) + + +class wait_exponential_jitter(wait_base): + """Wait strategy that applies exponential backoff and jitter. + + It allows for a customized initial wait, maximum wait and jitter. + + This implements the strategy described here: + https://cloud.google.com/storage/docs/retry-strategy + + The wait time is min(initial * 2**n + random.uniform(0, jitter), maximum) + where n is the retry count. + """ + + def __init__( + self, + initial: float = 1, + max: float = _utils.MAX_WAIT, # noqa + exp_base: float = 2, + jitter: float = 1, + ) -> None: + self.initial = initial + self.max = max + self.exp_base = exp_base + self.jitter = jitter + + def __call__(self, retry_state: "RetryCallState") -> float: + jitter = random.uniform(0, self.jitter) + try: + exp = self.exp_base ** (retry_state.attempt_number - 1) + result = self.initial * exp + jitter + except OverflowError: + result = self.max + return max(0, min(result, self.max)) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/termcolor/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/termcolor/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c046c06f6b26aa0bd8c0c8ff320582194d9176e2 --- /dev/null +++ b/data/tefig/envs/olmes-eval/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/termcolor/__main__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/termcolor/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..a7bf672227323f31f0e556b887eb7f6f46d4dbbf --- /dev/null +++ b/data/tefig/envs/olmes-eval/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/termcolor/py.typed b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/termcolor/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/termcolor/termcolor.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/termcolor/termcolor.py new file mode 100644 index 0000000000000000000000000000000000000000..e288b403b1163e17f81148f9b70fe34b0661b63f --- /dev/null +++ b/data/tefig/envs/olmes-eval/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tiktoken_ext/openai_public.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tiktoken_ext/openai_public.py new file mode 100644 index 0000000000000000000000000000000000000000..02c9ee20fa186223145da1de759bdf001f1f1e1c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tiktoken_ext/openai_public.py @@ -0,0 +1,162 @@ +from tiktoken.load import data_gym_to_mergeable_bpe_ranks, load_tiktoken_bpe + +ENDOFTEXT = "<|endoftext|>" +FIM_PREFIX = "<|fim_prefix|>" +FIM_MIDDLE = "<|fim_middle|>" +FIM_SUFFIX = "<|fim_suffix|>" +ENDOFPROMPT = "<|endofprompt|>" + +# The pattern in the original GPT-2 release is: +# r"""'s|'t|'re|'ve|'m|'ll|'d| ?[\p{L}]+| ?[\p{N}]+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""" +# This is equivalent, but executes faster: +r50k_pat_str = ( + r"""'(?:[sdmt]|ll|ve|re)| ?\p{L}++| ?\p{N}++| ?[^\s\p{L}\p{N}]++|\s++$|\s+(?!\S)|\s""" +) + + +def gpt2(): + mergeable_ranks = data_gym_to_mergeable_bpe_ranks( + vocab_bpe_file="https://openaipublic.blob.core.windows.net/gpt-2/encodings/main/vocab.bpe", + encoder_json_file="https://openaipublic.blob.core.windows.net/gpt-2/encodings/main/encoder.json", + vocab_bpe_hash="1ce1664773c50f3e0cc8842619a93edc4624525b728b188a9e0be33b7726adc5", + encoder_json_hash="196139668be63f3b5d6574427317ae82f612a97c5d1cdaf36ed2256dbf636783", + ) + return { + "name": "gpt2", + "explicit_n_vocab": 50257, + "pat_str": r50k_pat_str, + "mergeable_ranks": mergeable_ranks, + "special_tokens": {ENDOFTEXT: 50256}, + } + + +def r50k_base(): + mergeable_ranks = load_tiktoken_bpe( + "https://openaipublic.blob.core.windows.net/encodings/r50k_base.tiktoken", + expected_hash="306cd27f03c1a714eca7108e03d66b7dc042abe8c258b44c199a7ed9838dd930", + ) + return { + "name": "r50k_base", + "explicit_n_vocab": 50257, + "pat_str": r50k_pat_str, + "mergeable_ranks": mergeable_ranks, + "special_tokens": {ENDOFTEXT: 50256}, + } + + +def p50k_base(): + mergeable_ranks = load_tiktoken_bpe( + "https://openaipublic.blob.core.windows.net/encodings/p50k_base.tiktoken", + expected_hash="94b5ca7dff4d00767bc256fdd1b27e5b17361d7b8a5f968547f9f23eb70d2069", + ) + return { + "name": "p50k_base", + "explicit_n_vocab": 50281, + "pat_str": r50k_pat_str, + "mergeable_ranks": mergeable_ranks, + "special_tokens": {ENDOFTEXT: 50256}, + } + + +def p50k_edit(): + mergeable_ranks = load_tiktoken_bpe( + "https://openaipublic.blob.core.windows.net/encodings/p50k_base.tiktoken", + expected_hash="94b5ca7dff4d00767bc256fdd1b27e5b17361d7b8a5f968547f9f23eb70d2069", + ) + special_tokens = {ENDOFTEXT: 50256, FIM_PREFIX: 50281, FIM_MIDDLE: 50282, FIM_SUFFIX: 50283} + return { + "name": "p50k_edit", + "pat_str": r50k_pat_str, + "mergeable_ranks": mergeable_ranks, + "special_tokens": special_tokens, + } + + +def cl100k_base(): + mergeable_ranks = load_tiktoken_bpe( + "https://openaipublic.blob.core.windows.net/encodings/cl100k_base.tiktoken", + expected_hash="223921b76ee99bde995b7ff738513eef100fb51d18c93597a113bcffe865b2a7", + ) + special_tokens = { + ENDOFTEXT: 100257, + FIM_PREFIX: 100258, + FIM_MIDDLE: 100259, + FIM_SUFFIX: 100260, + ENDOFPROMPT: 100276, + } + return { + "name": "cl100k_base", + "pat_str": r"""'(?i:[sdmt]|ll|ve|re)|[^\r\n\p{L}\p{N}]?+\p{L}++|\p{N}{1,3}+| ?[^\s\p{L}\p{N}]++[\r\n]*+|\s++$|\s*[\r\n]|\s+(?!\S)|\s""", + "mergeable_ranks": mergeable_ranks, + "special_tokens": special_tokens, + } + + +def o200k_base(): + mergeable_ranks = load_tiktoken_bpe( + "https://openaipublic.blob.core.windows.net/encodings/o200k_base.tiktoken", + expected_hash="446a9538cb6c348e3516120d7c08b09f57c36495e2acfffe59a5bf8b0cfb1a2d", + ) + special_tokens = {ENDOFTEXT: 199999, ENDOFPROMPT: 200018} + # This regex could be made more efficient. If I was the one working on this encoding, I would + # have done a few other things differently too, e.g. I think you can allocate tokens more + # efficiently across languages. + pat_str = "|".join( + [ + r"""[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*[\p{Ll}\p{Lm}\p{Lo}\p{M}]+(?i:'s|'t|'re|'ve|'m|'ll|'d)?""", + r"""[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]+[\p{Ll}\p{Lm}\p{Lo}\p{M}]*(?i:'s|'t|'re|'ve|'m|'ll|'d)?""", + r"""\p{N}{1,3}""", + r""" ?[^\s\p{L}\p{N}]+[\r\n/]*""", + r"""\s*[\r\n]+""", + r"""\s+(?!\S)""", + r"""\s+""", + ] + ) + return { + "name": "o200k_base", + "pat_str": pat_str, + "mergeable_ranks": mergeable_ranks, + "special_tokens": special_tokens, + } + + +def o200k_harmony(): + base_enc = o200k_base() + name = "o200k_harmony" + pat_str = base_enc["pat_str"] + mergeable_ranks = base_enc["mergeable_ranks"] + special_tokens = { + **base_enc["special_tokens"], + "<|startoftext|>": 199998, + "<|endoftext|>": 199999, + "<|reserved_200000|>": 200000, + "<|reserved_200001|>": 200001, + "<|return|>": 200002, + "<|constrain|>": 200003, + "<|reserved_200004|>": 200004, + "<|channel|>": 200005, + "<|start|>": 200006, + "<|end|>": 200007, + "<|message|>": 200008, + "<|reserved_200009|>": 200009, + "<|reserved_200010|>": 200010, + "<|reserved_200011|>": 200011, + "<|call|>": 200012, + } | {f"<|reserved_{i}|>": i for i in range(200013, 201088)} + return { + "name": name, + "pat_str": pat_str, + "mergeable_ranks": mergeable_ranks, + "special_tokens": special_tokens, + } + + +ENCODING_CONSTRUCTORS = { + "gpt2": gpt2, + "r50k_base": r50k_base, + "p50k_base": p50k_base, + "p50k_edit": p50k_edit, + "cl100k_base": cl100k_base, + "o200k_base": o200k_base, + "o200k_harmony": o200k_harmony, +} diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tomli-2.4.1.dist-info/INSTALLER b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tomli-2.4.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tomli-2.4.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tomli-2.4.1.dist-info/METADATA b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tomli-2.4.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..f8ba90619486d70d2c33f8eba1a1cd718e6cc151 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tomli-2.4.1.dist-info/METADATA @@ -0,0 +1,265 @@ +Metadata-Version: 2.4 +Name: tomli +Version: 2.4.1 +Summary: A lil' TOML parser +Keywords: toml +Author-email: Taneli Hukkinen +Requires-Python: >=3.8 +Description-Content-Type: text/markdown +License-Expression: MIT +Classifier: Operating System :: MacOS +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: POSIX :: Linux +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Typing :: Typed +License-File: LICENSE +Project-URL: Changelog, https://github.com/hukkin/tomli/blob/master/CHANGELOG.md +Project-URL: Homepage, https://github.com/hukkin/tomli + +[![Build Status](https://github.com/hukkin/tomli/actions/workflows/tests.yaml/badge.svg?branch=master)](https://github.com/hukkin/tomli/actions?query=workflow%3ATests+branch%3Amaster+event%3Apush) +[![codecov.io](https://codecov.io/gh/hukkin/tomli/branch/master/graph/badge.svg)](https://codecov.io/gh/hukkin/tomli) +[![PyPI version](https://img.shields.io/pypi/v/tomli)](https://pypi.org/project/tomli) + +# Tomli + +> A lil' TOML parser + +**Table of Contents** *generated with [mdformat-toc](https://github.com/hukkin/mdformat-toc)* + + + +- [Intro](#intro) +- [Installation](#installation) +- [Usage](#usage) + - [Parse a TOML string](#parse-a-toml-string) + - [Parse a TOML file](#parse-a-toml-file) + - [Handle invalid TOML](#handle-invalid-toml) + - [Construct `decimal.Decimal`s from TOML floats](#construct-decimaldecimals-from-toml-floats) + - [Building a `tomli`/`tomllib` compatibility layer](#building-a-tomlitomllib-compatibility-layer) +- [FAQ](#faq) + - [Why this parser?](#why-this-parser) + - [Is comment preserving round-trip parsing supported?](#is-comment-preserving-round-trip-parsing-supported) + - [Is there a `dumps`, `write` or `encode` function?](#is-there-a-dumps-write-or-encode-function) + - [How do TOML types map into Python types?](#how-do-toml-types-map-into-python-types) +- [Performance](#performance) + - [Mypyc generated wheel](#mypyc-generated-wheel) + - [Pure Python](#pure-python) + + + +## Intro + +Tomli is a Python library for parsing [TOML](https://toml.io). +Version 2.4.0 and later are compatible with [TOML v1.1.0](https://toml.io/en/v1.1.0). +Older versions are [TOML v1.0.0](https://toml.io/en/v1.0.0) compatible. + +A version of Tomli, the `tomllib` module, +was added to the standard library in Python 3.11 +via [PEP 680](https://www.python.org/dev/peps/pep-0680/). +Tomli continues to provide a backport on PyPI for Python versions +where the standard library module is not available +and that have not yet reached their end-of-life. + +Tomli uses [mypyc](https://github.com/mypyc/mypyc) +to generate binary wheels for most of the widely used platforms, +so Python 3.11+ users may prefer it over `tomllib` for improved performance. +Pure Python wheels are available on any platform and should perform the same as `tomllib`. + +## Installation + +```bash +pip install tomli +``` + +## Usage + +### Parse a TOML string + +```python +import tomli + +toml_str = """ +[[players]] +name = "Lehtinen" +number = 26 + +[[players]] +name = "Numminen" +number = 27 +""" + +toml_dict = tomli.loads(toml_str) +assert toml_dict == { + "players": [{"name": "Lehtinen", "number": 26}, {"name": "Numminen", "number": 27}] +} +``` + +### Parse a TOML file + +```python +import tomli + +with open("path_to_file/conf.toml", "rb") as f: + toml_dict = tomli.load(f) +``` + +The file must be opened in binary mode (with the `"rb"` flag). +Binary mode will enforce decoding the file as UTF-8 with universal newlines disabled, +both of which are required to correctly parse TOML. + +### Handle invalid TOML + +```python +import tomli + +try: + toml_dict = tomli.loads("]] this is invalid TOML [[") +except tomli.TOMLDecodeError: + print("Yep, definitely not valid.") +``` + +Note that error messages are considered informational only. +They should not be assumed to stay constant across Tomli versions. + +### Construct `decimal.Decimal`s from TOML floats + +```python +from decimal import Decimal +import tomli + +toml_dict = tomli.loads("precision-matters = 0.982492", parse_float=Decimal) +assert isinstance(toml_dict["precision-matters"], Decimal) +assert toml_dict["precision-matters"] == Decimal("0.982492") +``` + +Note that `decimal.Decimal` can be replaced with another callable that converts a TOML float from string to a Python type. +The `decimal.Decimal` is, however, a practical choice for use cases where float inaccuracies can not be tolerated. + +Illegal types are `dict` and `list`, and their subtypes. +A `ValueError` will be raised if `parse_float` produces illegal types. + +### Building a `tomli`/`tomllib` compatibility layer + +Python versions 3.11+ ship with a version of Tomli: +the `tomllib` standard library module. +To build code that uses the standard library if available, +but still works seamlessly with Python 3.6+, +do the following. + +Instead of a hard Tomli dependency, use the following +[dependency specifier](https://packaging.python.org/en/latest/specifications/dependency-specifiers/) +to only require Tomli when the standard library module is not available: + +``` +tomli >= 1.1.0 ; python_version < "3.11" +``` + +Then, in your code, import a TOML parser using the following fallback mechanism: + +```python +import sys + +if sys.version_info >= (3, 11): + import tomllib +else: + import tomli as tomllib + +tomllib.loads("['This parses fine with Python 3.6+']") +``` + +## FAQ + +### Why this parser? + +- it's lil' +- pure Python with zero dependencies +- the fastest pure Python parser [\*](#pure-python): + 14x as fast as [tomlkit](https://pypi.org/project/tomlkit/), + 2.1x as fast as [toml](https://pypi.org/project/toml/) +- outputs [basic data types](#how-do-toml-types-map-into-python-types) only +- 100% spec compliant: passes all tests in + [toml-lang/toml-test](https://github.com/toml-lang/toml-test) + test suite +- thoroughly tested: 100% branch coverage + +### Is comment preserving round-trip parsing supported? + +No. + +The `tomli.loads` function returns a plain `dict` that is populated with builtin types and types from the standard library only. +Preserving comments requires a custom type to be returned so will not be supported, +at least not by the `tomli.loads` and `tomli.load` functions. + +Look into [TOML Kit](https://github.com/sdispater/tomlkit) if preservation of style is what you need. + +### Is there a `dumps`, `write` or `encode` function? + +[Tomli-W](https://github.com/hukkin/tomli-w) is the write-only counterpart of Tomli, providing `dump` and `dumps` functions. + +The core library does not include write capability, as most TOML use cases are read-only, and Tomli intends to be minimal. + +### How do TOML types map into Python types? + +| TOML type | Python type | Details | +| ---------------- | ------------------- | ------------------------------------------------------------ | +| Document Root | `dict` | | +| Key | `str` | | +| String | `str` | | +| Integer | `int` | | +| Float | `float` | | +| Boolean | `bool` | | +| Offset Date-Time | `datetime.datetime` | `tzinfo` attribute set to an instance of `datetime.timezone` | +| Local Date-Time | `datetime.datetime` | `tzinfo` attribute set to `None` | +| Local Date | `datetime.date` | | +| Local Time | `datetime.time` | | +| Array | `list` | | +| Table | `dict` | | +| Inline Table | `dict` | | + +## Performance + +The `benchmark/` folder in this repository contains a performance benchmark for comparing the various Python TOML parsers. + +Below are the results for commit [064e492](https://github.com/hukkin/tomli/tree/064e492919b2338def788753b8c981c9131334c0). + +### Mypyc generated wheel + +```console +foo@bar:~/dev/tomli$ python --version +Python 3.14.2 +foo@bar:~/dev/tomli$ pip freeze +pytomlpp==1.1.0 +rtoml==0.13.0 +toml==0.10.2 +tomli @ file:///home/foo/dev/tomli +tomlkit==0.13.3 +foo@bar:~/dev/tomli$ python benchmark/run.py +Parsing data.toml 5000 times: +------------------------------------------------------ + parser | exec time | performance (more is better) +-----------+------------+----------------------------- + rtoml | 0.328 s | baseline (100%) + pytomlpp | 0.365 s | 89.75% + tomli | 0.838 s | 39.12% + toml | 3.01 s | 10.90% + tomlkit | 20.7 s | 1.59% +``` + +### Pure Python + +```console +foo@bar:~/dev/tomli$ python benchmark/run.py +Parsing data.toml 5000 times: +------------------------------------------------------ + parser | exec time | performance (more is better) +-----------+------------+----------------------------- + rtoml | 0.323 s | baseline (100%) + pytomlpp | 0.365 s | 88.40% + tomli | 1.44 s | 22.36% + toml | 3.03 s | 10.65% + tomlkit | 20.6 s | 1.57% +``` + diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tomli-2.4.1.dist-info/RECORD b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tomli-2.4.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..73d0d569ec86944a53650118c05b740aad64a704 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tomli-2.4.1.dist-info/RECORD @@ -0,0 +1,14 @@ +tomli-2.4.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +tomli-2.4.1.dist-info/METADATA,sha256=srP98lZrujExBqv0qAb5whf4-BRYfxAXxJTUkHmgpoM,10463 +tomli-2.4.1.dist-info/RECORD,, +tomli-2.4.1.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82 +tomli-2.4.1.dist-info/licenses/LICENSE,sha256=uAgWsNUwuKzLTCIReDeQmEpuO2GSLCte6S8zcqsnQv4,1072 +tomli/__init__.py,sha256=nrBC18DbXRTCFo7ElG5BDeWpHJzOhokvXk215GM8Z2I,314 +tomli/__pycache__/__init__.cpython-310.pyc,, +tomli/__pycache__/_parser.cpython-310.pyc,, +tomli/__pycache__/_re.cpython-310.pyc,, +tomli/__pycache__/_types.cpython-310.pyc,, +tomli/_parser.py,sha256=pBIjTIa_cQs2HglDJ2lh8OJfptfDa6eg5-7Iej4BjHs,26440 +tomli/_re.py,sha256=oSNZ_ilFI6chEuQ01YRSoUydBQr_okF_mSdHTkFmv90,3396 +tomli/_types.py,sha256=-GTG2VUqkpxwMqzmVO4F7ybKddIbAnuAHXfmWQcTi3Q,254 +tomli/py.typed,sha256=8PjyZ1aVoQpRVvt71muvuq5qE-jTFZkK-GLHkhdebmc,26 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tomli-2.4.1.dist-info/WHEEL b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tomli-2.4.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..d8b9936dad9ab2513fa6979f411560d3b6b57e37 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tomli-2.4.1.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: flit 3.12.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_VF.pyi b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_VF.pyi new file mode 100644 index 0000000000000000000000000000000000000000..33298b279c00b6fb061e3799ad7f9a4b201f4c73 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_VF.pyi @@ -0,0 +1,32949 @@ +# @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 Sequence +from types import EllipsisType +from typing import Any, Callable, 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", + "_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_is_symbolic", + "_functionalize_mark_mutation_hidden_from_autograd", + "_functionalize_replace", + "_functionalize_set_storage_changed", + "_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_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_det", + "_linalg_eigh", + "_linalg_eigh", + "_linalg_slogdet", + "_linalg_slogdet", + "_linalg_solve_ex", + "_linalg_solve_ex", + "_linalg_svd", + "_linalg_svd", + "_log_softmax", + "_log_softmax_backward_data", + "_logcumsumexp", + "_lstm_mps", + "_lu_with_info", + "_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_cudnn_attention", + "_scaled_dot_product_efficient_attention", + "_scaled_dot_product_efficient_attention", + "_scaled_dot_product_flash_attention", + "_scaled_dot_product_flash_attention", + "_scaled_dot_product_flash_attention_for_cpu", + "_scaled_dot_product_flash_attention_for_cpu", + "_scaled_grouped_mm", + "_scaled_mm", + "_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", + "_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", + "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", + "cummax", + "cummin", + "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", + "frexp", + "frobenius_norm", + "from_file", + "from_numpy", + "frombuffer", + "full", + "full_like", + "fused_moving_avg_obs_fake_quant", + "gather", + "gcd", + "gcd_", + "ge", + "geqrf", + "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", + "heaviside", + "hinge_embedding_loss", + "histc", + "histogram", + "histogram", + "histogramdd", + "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", + "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", + "lu_unpack", + "margin_ranking_loss", + "masked_fill", + "masked_scatter", + "masked_select", + "matmul", + "matrix_exp", + "matrix_power", + "max", + "max", + "max_pool1d", + "max_pool1d_with_indices", + "max_pool2d", + "max_pool3d", + "maximum", + "mean", + "median", + "median", + "min", + "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", + "mode", + "moveaxis", + "movedim", + "msort", + "mul", + "multinomial", + "multiply", + "mv", + "mvlgamma", + "nan_to_num", + "nan_to_num_", + "nanmean", + "nanmedian", + "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", + "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", + "slogdet", + "smm", + "softmax", + "sort", + "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", + "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", + "topk", + "trace", + "transpose", + "transpose_copy", + "trapezoid", + "trapz", + "triangular_solve", + "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_is_symbolic(tensor: Tensor) -> _bool: ... +def _functionalize_mark_mutation_hidden_from_autograd(t: Tensor) -> None: ... +def _functionalize_replace(self_: Tensor, other: Tensor) -> None: ... +def _functionalize_set_storage_changed(tensor: Tensor) -> _bool: ... +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_ndim: _int, + weight: Tensor, + eps: _float, +) -> 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_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 _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 + + Computes the inverse cosine 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 ``max``/``min`` and ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + + 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 ``max``/``min`` and ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + + 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) + 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) + 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) + 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. + + .. 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 of :attr:`input`. + + .. 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 of :attr:`input`. + + .. 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`. + + 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`. + + .. 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, +) -> 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. + + 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]) + """ + +def fbgemm_linear_fp16_weight( + input: Tensor, + packed_weight: Tensor, + bias: Tensor, +) -> Tensor: ... +def fbgemm_linear_fp16_weight_fp32_activation( + input: Tensor, + packed_weight: Tensor, + bias: 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``. + """ + +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. + + 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. + + 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. + + 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. + + 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. + + 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. + + 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. + + 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. + + 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. + + 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, periodic=True, alpha=0.54, beta=0.46, *, dtype=None, layout=torch.strided, device=None, 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 + periodic (bool, optional): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float, optional): The coefficient :math:`\alpha` in the equation above + beta (float, optional): 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. + 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, periodic=True, alpha=0.54, beta=0.46, *, dtype=None, layout=torch.strided, device=None, 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 + periodic (bool, optional): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float, optional): The coefficient :math:`\alpha` in the equation above + beta (float, optional): 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. + 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, periodic=True, alpha=0.54, beta=0.46, *, dtype=None, layout=torch.strided, device=None, 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 + periodic (bool, optional): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float, optional): The coefficient :math:`\alpha` in the equation above + beta (float, optional): 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. + 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, periodic=True, alpha=0.54, beta=0.46, *, dtype=None, layout=torch.strided, device=None, 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 + periodic (bool, optional): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float, optional): The coefficient :math:`\alpha` in the equation above + beta (float, optional): 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. + 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 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 exclusive 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 exclusive 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 exclusive 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` which is a `LongTensor`. + + 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` which is a `LongTensor`. + + 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) -> (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. + """ + +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) -> (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. + """ + +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: bool value of Tensor with more than one value is ambiguous + >>> torch.is_nonzero(torch.tensor([])) + Traceback (most recent call last): + ... + RuntimeError: bool 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 multiple and removed after. + The non-matrix (i.e. batch) dimensions are :ref:`broadcasted ` (and thus + must be broadcastable). For example, if :attr:`input` is a + :math:`(j \times 1 \times n \times n)` tensor and :attr:`other` is a :math:`(k \times n \times n)` + tensor, :attr:`out` will be a :math:`(j \times k \times n \times n)` tensor. + + Note that the broadcasting logic only looks at the batch dimensions when determining if the inputs + are broadcastable, and not the matrix dimensions. 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, these inputs are valid for broadcasting even though the final two dimensions (i.e. the + matrix dimensions) are different. :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. + + 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 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 (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. + + 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 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 (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. + + 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 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 (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. + + 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 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 (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. + + 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 ``None``, all dimensions are reduced. + + + 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. + + 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 ``None``, all dimensions are reduced. + + + 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. + + 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 ``None``, all dimensions are reduced. + + + 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. + + 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 ``None``, all dimensions are reduced. + + + 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`. + + .. note:: This function is not defined for ``torch.cuda.Tensor`` yet. + + 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`. + + .. note:: This function is not defined for ``torch.cuda.Tensor`` yet. + + 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 (rounding down for .5 fractions). + - ``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): 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 (rounding down for .5 fractions). + - ``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): 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]]) + """ + +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, *, 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: + 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, + *, + 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, \*, 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: + 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, \*, 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: + 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, \*, 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: + 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 + """ + +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, *, 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: + 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: ... +@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 of :attr:`input`. + + .. 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) + stable (bool, optional): makes the sorting routine stable, which guarantees that the order + of equivalent elements is preserved. + + 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.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) + stable (bool, optional): makes the sorting routine stable, which guarantees that the order + of equivalent elements is preserved. + + 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.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) + stable (bool, optional): makes the sorting routine stable, which guarantees that the order + of equivalent elements is preserved. + + 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.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) + stable (bool, optional): makes the sorting routine stable, which guarantees that the order + of equivalent elements is preserved. + + 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.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 co-ordinates 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 co-ordinates 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) + co-ordinates 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 co-ordinates 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 co-ordinates 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 of :attr:`input`. + + .. 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 = 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 = 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/__config__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/__config__.py new file mode 100644 index 0000000000000000000000000000000000000000..1187fab3713996932d4f3bad71bac243c6baff35 --- /dev/null +++ b/data/tefig/envs/olmes-eval/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/__future__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/__future__.py new file mode 100644 index 0000000000000000000000000000000000000000..f172ee3c8fe223aa316667f37f356e5b6658d20e --- /dev/null +++ b/data/tefig/envs/olmes-eval/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fae804c8160fba8a5ac323ef8933eb2b675401ac --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/__init__.py @@ -0,0 +1,2866 @@ +""" +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 +from typing import ( + Any as _Any, + Callable as _Callable, + get_origin as _get_origin, + Optional as _Optional, + overload as _overload, + TYPE_CHECKING, + TypeVar as _TypeVar, + Union as _Union, +) +from typing_extensions import ParamSpec as _ParamSpec + + +if TYPE_CHECKING: + from .types import Device, IntLikeType + + +# multipy/deploy is setting this import before importing torch, this is the most +# reliable way we have to detect if we're running within deploy. +# https://github.com/pytorch/multipy/blob/d60f34ad38c371e441fe7ffdb77a3c3dda5a5d19/multipy/runtime/interpreter/interpreter_impl.cpp#L134-L137 +def _running_with_deploy() -> builtins.bool: + return sys.modules.get("torch._meta_registrations", None) is object + + +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, +) + + +# TODO(torch_deploy) figure out how to freeze version.py in fbcode build +if _running_with_deploy(): + __version__ = "torch-deploy-1.8" + # TODO: Remove this ugly hack when deploy typing extensions are updated to 4.10+ + if not TYPE_CHECKING: + import typing_extensions + + _TypeIs = typing_extensions.TypeGuard + typing_extensions.TypeIs = _TypeIs +else: + from typing_extensions import TypeIs as _TypeIs + + from torch.torch_version import __version__ as __version__ + +__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 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 (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/16/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/lib_folder/lib + nvidia_lib_paths = glob.glob( + os.path.join(path, "nvidia", lib_folder, "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_deps(lib_folder: str, lib_name: str) -> None: + """Preloads cuda deps if they 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: + raise ValueError(f"{lib_name} not found in the system path {sys.path}") + ctypes.CDLL(lib_path) + + +# See Note [Global dependencies] +def _load_global_deps() -> None: + if _running_with_deploy() or 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 via wheel + if "nvidia/cuda_runtime/lib/libcudart.so" not in _maps: + return + # If all above-mentioned conditions are met, preload nvrtc and nvjitlink + # Please note that order are important for CUDA-11.8 , as nvjitlink does not exist there + _preload_cuda_deps("cuda_nvrtc", "libnvrtc.so.*[0-9]") + _preload_cuda_deps("nvjitlink", "libnvJitLink.so.*[0-9]") + except Exception: + pass + + except OSError as err: + # Can only happen for wheel with cuda libs as PYPI deps + # As PyTorch is not purelib, but nvidia-*-cu12 is + from torch.version import cuda as cuda_version + + cuda_libs: dict[str, str] = { + "cublas": "libcublas.so.*[0-9]", + "cudnn": "libcudnn.so.*[0-9]", + "cuda_nvrtc": "libnvrtc.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]", + } + # cufiile is only available on cuda 12+ + # TODO: Remove once CUDA 11.8 binaries are deprecated + if cuda_version is not None: + t_version = cuda_version.split(".") + t_major = int(t_version[0]) # type: ignore[operator] + if t_major >= 12: + cuda_libs["cufile"] = "libcufile.so.*[0-9]" + + is_cuda_lib_err = [ + lib for lib in cuda_libs.values() if lib.split(".")[0] in err.args[0] + ] + if not is_cuda_lib_err: + raise err + for lib_folder, lib_name in cuda_libs.items(): + _preload_cuda_deps(lib_folder, lib_name) + ctypes.CDLL(global_deps_lib_path, mode=ctypes.RTLD_GLOBAL) + + +if (USE_RTLD_GLOBAL_WITH_LIBTORCH or os.getenv("TORCH_USE_RTLD_GLOBAL")) and ( + _running_with_deploy() or 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) + + # 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_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) == 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 + + # The __file__ check only works for Python 3.7 and above. + 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 setup.py install && python -c "import torch" + + This error can generally be solved using the `develop` workflow + $ python setup.py develop && 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. + + Note that this function is simply doing ``isinstance(obj, Tensor)``. + Using that ``isinstance`` check is better for typechecking with mypy, + and more explicit - so it's recommended to use that instead of + ``is_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, /) -> _TypeIs[_Union["TypedStorage", "UntypedStorage"]]: + r"""Returns True if `obj` is a PyTorch storage object. + + Args: + obj (Object): Object to test + """ + 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) + + if hasattr(_GLOBAL_DEVICE_CONTEXT, "device_context"): + device = _GLOBAL_DEVICE_CONTEXT.device_context.device + return _get_device_with_index(device) + else: + 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: _Union[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.kthvalue` with called on a CUDA tensor + * :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. + + A handful of CUDA operations are nondeterministic if the CUDA version is + 10.2 or greater, unless the environment variable ``CUBLAS_WORKSPACE_CONFIG=:4096:8`` + or ``CUBLAS_WORKSPACE_CONFIG=:16:8`` is set. See the CUDA documentation for more + details: ``_ + If one of these environment variable configurations is not set, a :class:`RuntimeError` + will be raised from these operations when called with CUDA tensors: + + * :func:`torch.mm` + * :func:`torch.mv` + * :func:`torch.bmm` + + Note that deterministic operations tend to have worse performance than + nondeterministic operations. + + .. 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) + + # Forward mode nondeterministic error + >>> torch.randn(10, device='cuda').kthvalue(1) + ... + RuntimeError: kthvalue CUDA does not have a deterministic implementation... + + # 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... + """ + _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: _Union[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: _Union[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) + + +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) + + +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) + + +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) + + +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, 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[_Union[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 _running_with_deploy() or 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 dependenices +################################################################################ + +# 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, + 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: _Optional[str]): + 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: _Optional[dict[str, _Any]]): + 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 _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: _Optional[builtins.bool] = None, + backend: _Union[str, _Callable] = "inductor", + mode: _Union[str, None] = None, + options: _Optional[ + dict[str, _Union[str, builtins.int, builtins.bool, _Callable]] + ] = None, + disable: builtins.bool = False, +) -> _Callable[_InputT, _RetT]: ... + + +@_overload +def compile( + model: None = None, + *, + fullgraph: builtins.bool = False, + dynamic: _Optional[builtins.bool] = None, + backend: _Union[str, _Callable] = "inductor", + mode: _Union[str, None] = None, + options: _Optional[ + dict[str, _Union[str, builtins.int, builtins.bool, _Callable]] + ] = None, + disable: builtins.bool = False, +) -> _Callable[[_Callable[_InputT, _RetT]], _Callable[_InputT, _RetT]]: ... + + +def compile( + model: _Optional[_Callable[_InputT, _RetT]] = None, + *, + fullgraph: builtins.bool = False, + dynamic: _Optional[builtins.bool] = None, + backend: _Union[str, _Callable] = "inductor", + mode: _Union[str, None] = None, + options: _Optional[ + dict[str, _Union[str, builtins.int, builtins.bool, _Callable]] + ] = None, + disable: builtins.bool = False, +) -> _Union[ + _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 compileable 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. + 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, 14): + raise RuntimeError("torch.compile is not supported on Python 3.14+") + 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( + 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(): + backend = bisect_backend + + guard_filter_fn = None + if options and isinstance(options, dict): + guard_filter_fn = options.pop("guard_filter_fn", None) + + if backend == "inductor": + 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() + +if not _running_with_deploy(): + 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: _Optional[_Union[torch.device, str]] = 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: _Optional[builtins.int] = None, + max: _Optional[builtins.int] = 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" + if sys.version_info < (3, 10): + backend_extensions = entry_points().get(group_name, ()) + else: + 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_appdirs.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_appdirs.py new file mode 100644 index 0000000000000000000000000000000000000000..291963f6f6f627cb69081e4fc764d7cdc0c02df5 --- /dev/null +++ b/data/tefig/envs/olmes-eval/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(object): + """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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_classes.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_classes.py new file mode 100644 index 0000000000000000000000000000000000000000..069f13dcb6793d1e1abeb7b20e633e7ad4171007 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_classes.py @@ -0,0 +1,56 @@ +# mypy: allow-untyped-defs +import types + +import torch._C + + +class _ClassNamespace(types.ModuleType): + def __init__(self, name): + super().__init__("torch.classes" + name) + self.name = name + + def __getattr__(self, attr): + 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): + namespace = _ClassNamespace(name) + setattr(self, name, namespace) + return namespace + + @property + def loaded_libraries(self): + return torch.ops.loaded_libraries + + 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 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_compile.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_compile.py new file mode 100644 index 0000000000000000000000000000000000000000..33855b44b70572f7f465ca6d2e483075ffa82be9 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_compile.py @@ -0,0 +1,59 @@ +""" +APIs related to torch.compile which lazily import torch._dynamo to avoid +circular dependencies. +""" + +import functools +from typing import Callable, Literal, Optional, overload, TypeVar, Union +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: Literal[None] = None, recursive: bool = True +) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]: ... + + +def _disable_dynamo( + fn: Optional[Callable[_P, _T]] = None, recursive: bool = True +) -> Union[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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_custom_ops.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_custom_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..5203da640fa58e9ab7bf6785eb26ae1186059bee --- /dev/null +++ b/data/tefig/envs/olmes-eval/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_deploy.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_deploy.py new file mode 100644 index 0000000000000000000000000000000000000000..0443a2447d00dde7ef893a794df95a8ddfb61638 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_deploy.py @@ -0,0 +1,104 @@ +# mypy: allow-untyped-defs +import io + +import torch +from torch.package import Importer, OrderedImporter, PackageImporter, sys_importer +from torch.package._package_pickler import create_pickler +from torch.package._package_unpickler import PackageUnpickler +from torch.serialization import _maybe_decode_ascii + + +def _save_storages(importer, obj): + serialized_storages = [] + serialized_dtypes = [] + + importer = importer if isinstance(importer, torch.package.PackageImporter) else None + importers: Importer + if importer is not None: + importers = OrderedImporter(importer, sys_importer) + else: + importers = sys_importer + + def persistent_id(obj): + if torch.is_storage(obj) or isinstance(obj, torch.storage.TypedStorage): + if isinstance(obj, torch.storage.TypedStorage): + # TODO: Once we decide to break serialization FC, we can + # remove this case + dtype = obj.dtype + else: + dtype = torch.uint8 + + serialized_storages.append(obj) + serialized_dtypes.append(dtype) + return ("storage", len(serialized_storages) - 1) + + if hasattr(obj, "__reduce_deploy__"): + if _serialized_reduces.get(id(obj)) is None: + _serialized_reduces[id(obj)] = ( + "reduce_deploy", + id(obj), + *obj.__reduce_deploy__(importers), + ) + return _serialized_reduces[id(obj)] + + return None + + # Write the pickle data for `obj` + data_buf = io.BytesIO() + pickler = create_pickler(data_buf, importers) + pickler.persistent_id = persistent_id + pickler.dump(obj) + data_value = data_buf.getvalue() + return ( + data_value, + serialized_storages, + serialized_dtypes, + importer.zip_reader if importer else None, + ) + + +def _load_storages(id, zip_reader, obj_bytes, serialized_storages, serialized_dtypes): + def persistent_load(saved_id): + assert isinstance(saved_id, tuple) + typename = _maybe_decode_ascii(saved_id[0]) + data = saved_id[1:] + + if typename == "storage": + # TODO: Once we decide to break serialization FC, we can + # stop wrapping with TypedStorage + storage = serialized_storages[data[0]] + dtype = serialized_dtypes[data[0]] + return torch.storage.TypedStorage( + wrap_storage=storage.untyped(), dtype=dtype + ) + + if typename == "reduce_deploy": + reduce_id, func, args = data + if reduce_id not in _loaded_reduces: + _loaded_reduces[reduce_id] = func(_raw_packages[zip_reader], *args) + return _loaded_reduces[reduce_id] + + return None + + importer: Importer + if zip_reader is not None: + importer = OrderedImporter(_get_package(zip_reader), sys_importer) + else: + importer = sys_importer + + unpickler = PackageUnpickler(importer, io.BytesIO(obj_bytes)) + unpickler.persistent_load = persistent_load # type: ignore[method-assign] + result = _deploy_objects[id] = unpickler.load() + return result + + +def _get_package(zip_reader): + if zip_reader not in _raw_packages: + _raw_packages[zip_reader] = PackageImporter(zip_reader) + return _raw_packages[zip_reader] + + +_raw_packages: dict = {} +_deploy_objects: dict = {} +_serialized_reduces: dict = {} +_loaded_reduces: dict = {} diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_environment.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_environment.py new file mode 100644 index 0000000000000000000000000000000000000000..65cbd5d35ad5164f66f37a7d75ac29e4df5f5cfa --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_environment.py @@ -0,0 +1,2 @@ +def is_fbcode() -> bool: + return False diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_jit_internal.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_jit_internal.py new file mode 100644 index 0000000000000000000000000000000000000000..b718ab87c863f816b9d2a7c376fbb5a931927fe8 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_jit_internal.py @@ -0,0 +1,1552 @@ +# 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") + +IS_PY310_PLUS: Final[bool] = sys.version_info >= (3, 10) + +BuiltinUnionType: Union[type, tuple[type, ...]] +if sys.version_info >= (3, 10): + # NOTE: IS_PY310_PLUS doesn't work with mypy. + # cf. https://mypy.readthedocs.io/en/stable/common_issues.html#python-version-and-system-platform-checks + BuiltinUnionType = types.UnionType +else: + BuiltinUnionType = () # trick: this makes isinstance short circuit. + +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 + + # 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 manging 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 manualy 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 not 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 indicies 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 + + 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 + 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. {}", + 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. {}", + 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}." + ) + 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, None) + 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, None) + 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, None) + 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 useable 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: Optional[torch._C._jit_tree_views.SourceRange] = 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 = [] + # In 3.10 recommended way to get annotations is to call `inspect.get_annotations` function + # Also, annotations from base class are not inherited so they need to be queried explicitly + if sys.version_info[:2] < (3, 10): + obj_annotations = getattr(obj, "__annotations__", {}) + else: + obj_annotations = inspect.get_annotations(obj) + if len(obj_annotations) == 0 and hasattr(obj, "__base__"): + obj_annotations = inspect.get_annotations(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 evaluted 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]." + ) + + +# 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( + 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 thet + # 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) -> Optional[str]: + 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_linalg_utils.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_linalg_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..fe168cb33c4bae1a9dd6156fb8ec4c1932475268 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_linalg_utils.py @@ -0,0 +1,150 @@ +# mypy: allow-untyped-defs +"""Various linear algebra utility methods for internal use.""" + +from typing import Optional + +import torch +from torch import Tensor + + +def is_sparse(A): + """Check if tensor A is a sparse tensor""" + 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: Optional[Tensor], 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: Optional[Tensor], Y: Tensor) -> Tensor: + """Return bilinear form of matrices: :math:`X^T A Y`.""" + return matmul(X.mT, matmul(A, Y)) + + +def qform(A: Optional[Tensor], 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: Optional[bool] = 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_lowrank.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_lowrank.py new file mode 100644 index 0000000000000000000000000000000000000000..b8f9390232c87a502746e4c3a3b0d893ae822cb1 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_lowrank.py @@ -0,0 +1,294 @@ +"""Implement various linear algebra algorithms for low rank matrices.""" + +__all__ = ["svd_lowrank", "pca_lowrank"] + +from typing import Optional + +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: Optional[int] = 2, + M: Optional[Tensor] = 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 + choosen 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: Optional[int] = 6, + niter: Optional[int] = 2, + M: Optional[Tensor] = 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 + choosen 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: Optional[int] = 6, + niter: Optional[int] = 2, + M: Optional[Tensor] = 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: Optional[int] = 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_meta_registrations.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_meta_registrations.py new file mode 100644 index 0000000000000000000000000000000000000000..aaab720456ad7aa6b4645f79a41be870e0e4384e --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_meta_registrations.py @@ -0,0 +1,8016 @@ +# mypy: allow-untyped-defs +import math +import operator +from collections.abc import Sequence +from enum import Enum +from functools import reduce, wraps +from typing import Callable, Optional, TypeVar, Union +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, + view_of, +) +from torch._prims_common import ( + BoolLike, + corresponding_complex_dtype, + corresponding_real_dtype, + definitely_contiguous, + elementwise_dtypes, + ELEMENTWISE_TYPE_PROMOTION_KIND, + FloatLike, + IntLike, + is_contiguous, + 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.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 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) + + +# This function is python match of computeStride_impl in TensorUtils.cpp +def _compute_stride(old_shape, old_stride, new_shape, size_oblivious=False): + from torch.fx.experimental.symbolic_shapes import ( + guard_or_false, + guard_or_true, + sym_eq, + ) + + def maybe_guard_or_false(x): + if size_oblivious: + return guard_or_false(x) + + return x + + def maybe_guard_or_true(x): + if size_oblivious: + return guard_or_true(x) + + return x + + if len(old_shape) == 0: + return [1] * len(new_shape) + + numel = reduce(operator.mul, old_shape, 1) + zero_numel = maybe_guard_or_false(numel == 0) + if zero_numel and maybe_guard_or_false(sym_eq(old_shape, new_shape)): + return old_stride + + new_stride = [0] * len(new_shape) + + if zero_numel: + for view_d in range(len(new_shape) - 1, -1, -1): + if view_d == len(new_shape) - 1: + new_stride[view_d] = 1 + else: + new_stride[view_d] = ( + max(new_shape[view_d + 1], 1) * new_stride[view_d + 1] + ) + return new_stride + + view_d = len(new_shape) - 1 + chunk_base_stride = old_stride[-1] + tensor_numel = 1 + view_numel = 1 + + for tensor_d in range(len(old_shape) - 1, -1, -1): + tensor_numel *= old_shape[tensor_d] + + if tensor_d == 0 or ( + maybe_guard_or_true(old_shape[tensor_d - 1] != 1) + and maybe_guard_or_true( + old_stride[tensor_d - 1] != tensor_numel * chunk_base_stride + ) + ): + while view_d >= 0 and ( + maybe_guard_or_true(view_numel < tensor_numel) + or maybe_guard_or_false(new_shape[view_d] == 1) + ): + new_stride[view_d] = view_numel * chunk_base_stride + view_numel *= new_shape[view_d] + view_d -= 1 + + if maybe_guard_or_true(view_numel != tensor_numel): + return None + + if tensor_d > 0: + chunk_base_stride = old_stride[tensor_d - 1] + tensor_numel = 1 + view_numel = 1 + if view_d != -1: + return None + return new_stride + + +def _view_has_unbacked_input(a, shape): + from torch.fx.experimental.symbolic_shapes import has_hint + + return ( + any(not has_hint(s) for s in a.size()) + or any(not has_hint(s) for s in a.stride()) + or any(not has_hint(s) for s in shape) + ) + + +def _view_unbacked_meta(a, shape, size_oblivious_enabled=True): + from torch.fx.experimental.symbolic_shapes import guard_or_false, sym_eq + + # Creates a valid shape + shape = utils.extract_shape_from_varargs(shape, validate=False) + + # Reshape may be given a shape with a -1 length + # This indicates that the dimension's length should be inferred + shape = utils.infer_size(shape, a.numel()) + + # Special-cases reshaping zero dim tensors + if a.ndim == 0: + _a = a + for length in shape: + torch._check(length == 1) + _a = torch._refs.unsqueeze(_a, -1) + if _a is a: + return view_of(a) + else: + return _a + + # Special-cases reshaping to zero dim tensors + if len(shape) == 0: + _a = a + for length in a.shape: + torch._check(length == 1) + _a = torch._refs.squeeze(_a, -1) + if _a is a: + return view_of(a) + else: + return _a + + shape_numel = reduce(operator.mul, shape, 1) + + torch._check( + a.numel() == shape_numel, + lambda: f"Could not reshape a tensor with shape {a.shape} as a tensor with shape {shape}!", + ) + + if len(shape) == len(a.shape) and guard_or_false(sym_eq(shape, a.shape)): + return view_of(a) + + if definitely_contiguous(a) if size_oblivious_enabled else is_contiguous(a): + strides = utils.make_contiguous_strides_for(shape) + return a.as_strided(shape, strides) + + new_strides = _compute_stride( + a.size(), a.stride(), shape, size_oblivious=size_oblivious_enabled + ) + + if new_strides is not None: + return a.as_strided(shape, new_strides) + + # If we fail to do size oblivious view, and backed_size_oblivious was on, + # then we redo everything by looking at hints and guarding instead of failing. + # Also if the expression has unbacked symbols, then we run again with size_oblivious_enabled=False + # to throw a data dependent error. + + if size_oblivious_enabled and ( + torch.fx.experimental._config.backed_size_oblivious + or _view_has_unbacked_input(a, shape) + ): + return _view_unbacked_meta(a, shape, size_oblivious_enabled=False) + + msg = f"Cannot view a tensor with shape {a.shape} and strides {a.stride()} as a tensor with shape {shape}!" + raise ValueError(msg) + + +@register_meta(aten.view.default) +def _view_meta(a, *shape): + if torch.fx.experimental._config.backed_size_oblivious or _view_has_unbacked_input( + a, shape + ): + return _view_unbacked_meta(a, shape) + else: + return torch._refs._reshape_view_helper(a, *shape, allow_copy=False) + + +@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()) + new_stride = 1 if dim >= tensor.dim() else result_sizes[dim] * result_strides[dim] + result_sizes.insert(dim, 1) + 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: Optional[Tensor] = None, + _activation_opt: Optional[str] = None, + out_dtype: Optional[torch.dtype] = 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: Optional[torch.dtype] = 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: Optional[torch.dtype] = 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: Optional[Tensor] = None, + alpha: Optional[Tensor] = None, + out_dtype: Optional[torch.dtype] = 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] + compression_factor = 10 if is_8bit_input_type else 9 + + if is_8bit_input_type: + assert not dense_B.is_contiguous(), ( + "dense input must be transposed for 8bit dtypes" + ) + + k = dense_B.size(0) + n = dense_B.size(1) + m = (compressed_A.numel() * 16) // (compression_factor * k) + 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, + }, ( + "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: Optional[Tensor] = None, + indices: Optional[Tensor] = None, + offsets: Optional[Tensor] = 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_is_size(size) + 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) + 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: Optional[str] = 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: Optional[str], +) -> 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: Optional[Tensor] = None, + LU: Optional[Tensor] = None, + pivots: Optional[Tensor] = None, + info: Optional[Tensor] = 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: Optional[Tensor] = 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(0, 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.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): + 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}].", + ) + return a.new_empty(N, P) + + +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: Union[list[int], int], + padding: Union[list[int], int], + dilation: Union[list[int], int], + is_transposed: bool, + groups: int, + output_padding: Optional[Union[list[int], int]] = 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): + stride = [stride] * len(dims) + elif len(stride) == 1: + stride = [stride[0]] * len(dims) + + if isinstance(padding, IntLike): + padding = [padding] * len(dims) + elif len(padding) == 1: + padding = [padding[0]] * len(dims) + + if isinstance(dilation, IntLike): + dilation = [dilation] * len(dims) + elif len(dilation) == 1: + dilation = [dilation[0]] * len(dims) + + output_padding_list: Optional[list[int]] = None + if output_padding: + if isinstance(output_padding, IntLike): + 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], + padding[i], + dilation[i], + kernel_size[i], + stride[i], + output_padding_list[i], + ) + ) + else: + ret_shape.append( + _formula(dims[i], padding[i], dilation[i], kernel_size[i], stride[i]) + ) + + torch._check( + any(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: Optional[torch.Tensor], + running_mean: Optional[torch.Tensor], + running_var: Optional[torch.Tensor], + 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 + # provded 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, +): + def pick_memory_format(): + if device_hint(input_tensor) == "cuda": + if is_channels_last(input_tensor) or is_channels_last(weight): + return torch.channels_last + else: + if is_channels_last(input_tensor): + return torch.channels_last + if input_tensor.is_contiguous(memory_format=torch.contiguous_format): + return torch.contiguous_format + elif input_tensor.is_contiguous(memory_format=torch.preserve_format): + return torch.preserve_format + + 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) + out = out.to(memory_format=pick_memory_format()) # type: ignore[call-overload] + 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) + 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, + ) + assert output_dtype in [torch.float32, torch.bfloat16, torch.uint8, torch.int8] + out = x.new_empty(shape_out, dtype=output_dtype) + assert len(shape_out) in [3, 4], "only conv1d/2d are supported" + format = torch.channels_last if len(shape_out) == 4 else torch.contiguous_format + out = out.to(memory_format=format) + return out + + @register_meta(torch.ops.onednn.qconv2d_pointwise.binary) + 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] + 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] + 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, f"x must be a 2D tensor, got {x.dim()}D") + torch._check(w.dim() == 2, f"w must be a 2D tensor, got {w.dim()}D") + torch._check( + x.dtype in [torch.float32, torch.float16, torch.bfloat16], + f"expected x to be f32/f16/bf16, got {x.dtype}", + ) + torch._check(w.dtype == torch.uint8, f"expected w to be uint8, got {w.dtype}") + torch._check( + q_group_size.dtype == torch.int64, + f"q_group_size must be int64, got {q_group_size.dtype}", + ) + torch._check( + q_scale_and_zeros.dtype == x.dtype, + 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 + out_shape = _broadcast_shapes(real.shape, imag.shape) + return real.new_empty(out_shape, dtype=corresponding_complex_dtype(real.dtype)) + + +@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[Optional[Tensor]] = [] + 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()) + 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_size_oblivious + + if guard_size_oblivious(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: + 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 funtion retuns 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: Optional[Tensor], 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() + 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 in [torch.float32], + lambda: f"expected input to be f32, got {inp.dtype}", + ) + 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: "cdist only supports floating-point dtypes, X1 got: {x1.dtype}", + ) + torch._check( + utils.is_float_dtype(x2.dtype), + lambda: "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, 1, 2), + lambda: f"possible modes: None, 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.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 + + +@register_meta(aten.alias.default) +def meta_alias(self): + return self.view(self.shape) + + +def common_meta_baddbmm_bmm(batch1, batch2, is_bmm, self_baddbmm=None, out_dtype=None): + 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( + batch2_sizes[0] == bs and 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( + 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: "kernel size should be greater than zero, but got kH: {kH}, kW: {kW}", + ) + torch._check( + dW > 0 and dH > 0, + lambda: "stride should be greater than zero, but got dH: {dH}, dW: {dW}", + ) + torch._check( + dilationH > 0 and dilationW > 0, + lambda: "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" + " 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: "Unsupport 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, + f"fractional_max_pool2d: Expected input to have non-zero " + f" size for non-batch dimenions, 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, + "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", None) + if not dtype: + dtype = utils.get_dtype(fill_value) + kwargs["dtype"] = dtype + 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.int) +def meta_select(self, dim, index): + from torch.fx.experimental.symbolic_shapes import guard_size_oblivious + + ndim = self.dim() + torch._check_index( + ndim != 0, + lambda: "select() cannot be applied to a 0-dim tensor.", + ) + + dim = dim if dim >= 0 else dim + ndim + size = self.size(dim) + + torch._check_index( + not ( + guard_size_oblivious(-index > size) or guard_size_oblivious(index >= size) + ), + lambda: f"select(): index {index} out of range for tensor of size " + f"{self.size()} at dimension {dim}", + ) + + index = index if index >= 0 else index + size + + new_size = list(self.size()) + new_stride = list(self.stride()) + + new_storage_offset = self.storage_offset() + index * new_stride[dim] + del new_size[dim] + del new_stride[dim] + + return self.as_strided(new_size, new_stride, new_storage_offset) + + +@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_size_oblivious + + wrapped_dim = maybe_wrap_dim(dim, self.dim()) + is_index_empty = guard_size_oblivious(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_size_oblivious + + if guard_size_oblivious(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_size_oblivious + + if guard_size_oblivious(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: Optional[float] = 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) + + query_t = query.transpose(1, 2) + attention = torch.empty_like(query_t).transpose(1, 2) + 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(): + # Maintian 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: + query_t = query.transpose(1, 2) + res = torch.empty_like(query_t).transpose(1, 2) + 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: Optional[Tensor], + compute_log_sumexp: bool, + dropout_p: float = 0.0, + is_causal: bool = False, + return_debug_mask: bool = False, + scale: Optional[float] = 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), + 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: Optional[Tensor] = None, + dropout_p: float = 0.0, + is_causal: bool = False, + return_debug_mask: bool = False, + scale: Optional[float] = 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: Optional[float] = None, +): + grad_q = torch.empty_like(query.transpose(1, 2)).transpose(1, 2) + grad_k = torch.empty_like(key.transpose(1, 2)).transpose(1, 2) + grad_v = torch.empty_like(value.transpose(1, 2)).transpose(1, 2) + 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: Optional[Tensor] = None, + scale: Optional[float] = 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: Optional[Tensor] = None, + scale: Optional[float] = None, +): + # cpus's grad layout is different from cuda's, + # i.e. (batch_size, seq_len,num_heads, head_dim) + batch_size = query.size(0) + num_heads = query.size(1) + head_dim = query.size(3) + len_q = query.size(2) + len_k = key.size(2) + + grad_q = torch.empty_permuted( + (batch_size, num_heads, len_q, head_dim), + (0, 2, 1, 3), + dtype=query.dtype, + device=query.device, + ) + grad_k = torch.empty_permuted( + (batch_size, num_heads, len_k, head_dim), + (0, 2, 1, 3), + dtype=key.dtype, + device=key.device, + ) + grad_v = torch.empty_permuted( + (batch_size, num_heads, len_k, head_dim), + (0, 2, 1, 3), + dtype=value.dtype, + device=value.device, + ) + + return grad_q, grad_k, grad_v + + +@register_meta([aten._scaled_dot_product_efficient_attention]) +def meta__scaled_dot_product_efficient_attention( + query: Tensor, + key: Tensor, + value: Tensor, + attn_bias: Optional[Tensor], + compute_log_sumexp: bool, + dropout_p=0.0, + is_causal: bool = False, + scale: Optional[float] = 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: Optional[Tensor], + out: Tensor, + logsumexp: Tensor, + philox_seed: Tensor, + philox_offset: Tensor, + dropout_p: float, + grad_input_mask: list[bool], + is_causal: bool = False, + scale: Optional[float] = 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: Optional[float] = 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: Optional[Tensor], + cum_seq_k: Optional[Tensor], + max_q: int, + max_k: int, + dropout_p: float, + is_causal: bool, + return_debug_mask: bool, + scale: Optional[float] = None, + window_size_left: Optional[int] = None, + window_size_right: Optional[int] = None, + seqused_k: Optional[Tensor] = None, + alibi_slopes: Optional[Tensor] = 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(): + # Maintian 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: Optional[float] = None, + window_size_left: Optional[int] = None, + window_size_right: Optional[int] = 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: Optional[Tensor], + cu_seqlens_q: Optional[Tensor], + cu_seqlens_k: Optional[Tensor], + max_seqlen_q: Optional[int], + max_seqlen_k: Optional[int], + dropout_p: float, + custom_mask_type: int, + compute_log_sumexp: bool = False, + scale: Optional[float] = None, + causal_diagonal: Optional[Tensor] = None, + seqlen_k: Optional[Tensor] = None, + window_size: Optional[int] = 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: Optional[Tensor], + cu_seqlens_q: Optional[Tensor], + cu_seqlens_k: Optional[Tensor], + 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: Optional[float] = None, + num_splits_key: Optional[int] = 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 + + +@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: Optional[torch.Tensor] = None, + scale_result: Optional[torch.Tensor] = None, + out_dtype: Optional[torch.dtype] = 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": + + 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 divisble 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 + ) + + 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 + + def ceil_div(a, b): + return (a + b - 1) // b + + 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.", + ) + 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"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.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 probabilty 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[Union[int, torch.SymInt]], + input_size: Sequence[Union[int, torch.SymInt]], + scales_h: Optional[float] = None, + scales_w: Optional[float] = 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( + 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_is_size(k) + 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: "{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): + result_size = list(self.size()) + return self.new_empty(result_size) + + +@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, + "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, + "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), "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), "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), "batched dimension has to match") + out_size = [mat1.size(0), mat1.size(1), mat2.size(-1)] + + out_dtype = out_dtype or mat1.dtype + + 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) + return out + + +def _meta_grouped_mm_common( + mat_a: Tensor, + mat_b: Tensor, + scale_a: Optional[torch.Tensor], + scale_b: Optional[torch.Tensor], + offs: Optional[Tensor] = None, + bias: Optional[Tensor] = None, + scale_result: Optional[torch.Tensor] = None, + out_dtype: Optional[torch.dtype] = 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: + torch._check( + mat_a.dtype == torch.float8_e4m3fn and mat_b.dtype == torch.float8_e4m3fn, + lambda: f"Expected inputs of E4M3 FP8 type but got mat_a.dtype={mat_a.dtype} and mat_b.dtype={mat_b.dtype}.", + ) + 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}.", + ) + + 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()}", + ) + + mat_a_is_2d = mat_a.dim() == 2 + mat_b_is_2d = mat_b.dim() == 2 + + 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:]}", + ) + 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:]}", + ) + + 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]}.", + ) + 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, + lambda: "Both scale_a and scale_b must be float (fp32) tensors, but got scale_a.dtype={scale_a.dtype} and scale_b.dtype={scale_b.dtype}.", # noqa: B950 + ) + + def check_scale(scale_name, scale, mat, scaled_dim, scale_multiplier=1): + if mat.dim() == 2: + torch._check( + scale.dim() == 1, + lambda: f"Expected {scale_name} to be 1D tensor, but got {scale.dim()}D tensor.", + ) + torch._check( + scale.is_contiguous(), + lambda: f"Expected {scale_name} to be contiguous.", + ) + 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.dim() == 2, + lambda: f"Expected {scale_name} to be 2D tensor, but got {scale.dim()}D tensor.", + ) + 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]}.", + ) + 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]}.", + ) + + 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 grouped_mm( + mat_a: Tensor, + mat_b: Tensor, + offs: Optional[Tensor] = None, + bias: Optional[Tensor] = None, + out_dtype: Optional[torch.dtype] = 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.default]) +def meta_scaled_grouped_mm( + mat_a: torch.Tensor, + mat_b: torch.Tensor, + scale_a: torch.Tensor, + scale_b: torch.Tensor, + offs: Optional[torch.Tensor] = None, + bias: Optional[torch.Tensor] = None, + scale_result: Optional[torch.Tensor] = None, + out_dtype: Optional[torch.dtype] = None, + use_fast_accum: bool = False, +): + 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 == torch.half + 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.", + ) + + 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 + + +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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_namedtensor_internals.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_namedtensor_internals.py new file mode 100644 index 0000000000000000000000000000000000000000..16d04f181525d45259bcb77d1e215c1cd1118632 --- /dev/null +++ b/data/tefig/envs/olmes-eval/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.keys(): + new_dim = rename_map[old_dim] + if old_dim in dim_map.keys(): + 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_ops.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..337b9a11e6a180e752a415f5df78b9f5a289d078 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_ops.py @@ -0,0 +1,1483 @@ +# mypy: allow-untyped-defs +import abc +import contextlib +import ctypes +import importlib +import inspect +import sys +import types +from collections.abc import Iterator +from functools import cached_property +from typing import ( + Any, + Callable, + ClassVar, + final, + Generic, + Optional, + TYPE_CHECKING, + Union, +) +from typing_extensions import Concatenate, 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, Union[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 + # 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[Union[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: Union[ + 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: Optional[FunctionalTensorMode], *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] +] + + +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 certaion + # 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: Union[ + 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: + raise NotImplementedError( + f"There was no rule registered for HOP {self._name} and mode {curr_mode}. " + f"We recommend filing an issue." + ) + 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__ + == 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"Multiple dispatch failed for {self._name}. There was no registered that " + f"did not return NotImplemented. Use HOP.py_impl to register some. " + f"Tried mode: {curr_mode}) and subclasses: " + f"{[type(a) for a in overloaded_args]}" + ) + + 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): + def wrapper(): + 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 + ) + + return wrapper() + + # NOTE [HigherOrderOprator 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 + + +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(): + if mode_key == 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 == 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): + assert mode_key in ( + torch._C._TorchDispatchModeKey.PROXY, + torch._C._TorchDispatchModeKey.FUNCTIONAL, + ) + if mode_key == torch._C._TorchDispatchModeKey.PROXY: + return mode_stack_state_for_pre_dispatch().get(0) + else: + 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: + 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 + + # 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) -> Union[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) + + 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 + add_cached_op(self) + return r + + 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, + ] + + 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) + ] + + @contextlib.contextmanager + def _register_as_effectful_op_temporarily(self): + from torch._higher_order_ops.effects import ( + _EffectType, + _register_effectful_op, + SIDE_EFFECTS, + ) + + try: + if self not in SIDE_EFFECTS: + _register_effectful_op(self, _EffectType.ORDERED) + yield + finally: + if self in SIDE_EFFECTS: + del SIDE_EFFECTS[self] + + # 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. + # + # Note: + # 1. We only register the torchbind op temporarily as effectful op because we only want + # the effect token functionalization logic to be applied during tracing. Otherwise, the behavior + # of the eagerly executing the op might change after tracing. + # 2. We don't want to register the op as effectful for all torchbind ops in ctor because this might + # cause unexpected behavior for some autograd.profiler ops e.g. profiler._record_function_exit._RecordFunction. + with self._register_as_effectful_op_temporarily(): + 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 happpen 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) + + +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): + 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: + # Re-use 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, None) + 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. + """ + if torch._running_with_deploy(): + return + + 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. + ctypes.CDLL(path) + self.loaded_libraries.add(path) + + +# The ops "namespace" +ops: _Ops = _Ops() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_python_dispatcher.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_python_dispatcher.py new file mode 100644 index 0000000000000000000000000000000000000000..d2d4fbbf621e560ce0e8ee5afddfb0420b3d949c --- /dev/null +++ b/data/tefig/envs/olmes-eval/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_storage_docs.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_storage_docs.py new file mode 100644 index 0000000000000000000000000000000000000000..f0d16bc4250ffb2a383af727c974e9f910a5b2a5 --- /dev/null +++ b/data/tefig/envs/olmes-eval/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_tensor.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..10535cc80652eff5eedfd08a0119fdb0705e7ba8 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_tensor.py @@ -0,0 +1,1796 @@ +# mypy: allow-untyped-defs +import copyreg +import enum +import functools +import warnings +from collections import OrderedDict +from copy import deepcopy +from numbers import Number +from typing import Any, Callable, cast, Optional, Union + +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, +) + + +def _handle_torch_function_and_wrap_type_error_to_not_implemented(f): + assigned = functools.WRAPPER_ASSIGNMENTS + + @functools.wraps(f, assigned=assigned) + def wrapped(*args, **kwargs): + try: + # See https://github.com/pytorch/pytorch/issues/75462 + if has_torch_function(args): + return handle_torch_function(wrapped, args, *args, **kwargs) + return f(*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"] 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), + ) + # Legacy comment that does not hold anymore. + # Note: Numpy array is chosen to be the rebuild component for XLA, MTIA, MAIA Tensors. + # We considered a few options: + # 1. CPU tensor can't be used here. + # Otherwise in torch.load CPU storage is reconstructed with randomly + # initialized data, moved onto backend device, and then storage is updated + # to the serialized content. This works perfectly for CPU/CUDA but not these backends; + # their tensors are disconnected with storage so they don't get the update. + # 2. Python list is not a good fit due to performance reason. + # `tolist()` converts every single element in the tensor into python objects + # and serialize them one by one. + if self.device.type in ["mtia"]: + # Convert BFloat16 tesors to Float32 before conversion to numpy, as numpy doesn't + # support BFloat16. The rebuild tensor from numpy takes in the original self.dtype, + # this would reconstruct the BFloat16 tensor from numpy. + if skip_data: + raise RuntimeError( + "Cannot serialize tensors on backends with no storage under skip_data context manager" + ) + numpy_tensor = ( + self.cpu().numpy() + if self.dtype != torch.bfloat16 + else self.cpu().to(torch.float32).numpy() + ) + return ( + torch._utils._rebuild_device_tensor_from_numpy, + (numpy_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" + ) + 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: Union[ + 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 + 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 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] = 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: Optional[Union[float, str]] = "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: Optional[int] = None, + win_length: Optional[int] = None, + window: "Optional[Tensor]" = None, + center: bool = True, + pad_mode: str = "reflect", + normalized: bool = False, + onesided: Optional[bool] = None, + return_complex: Optional[bool] = None, + align_to_window: Optional[bool] = 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: Optional[int] = None, + win_length: Optional[int] = None, + window: "Optional[Tensor]" = None, + center: bool = True, + normalized: bool = False, + onesided: Optional[bool] = None, + length: Optional[int] = 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") + 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") + 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, 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): + return _C._VariableFunctions.rsub(self, other) + + @_handle_torch_function_and_wrap_type_error_to_not_implemented + def __rdiv__(self, other): + return self.reciprocal() * other + + __rtruediv__ = __rdiv__ + __itruediv__ = _C.TensorBase.__idiv__ + + __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): + 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): + return torch.pow(other, self) + + @_handle_torch_function_and_wrap_type_error_to_not_implemented + def __floordiv__(self, other): + return torch.floor_divide(self, other) + + @_handle_torch_function_and_wrap_type_error_to_not_implemented + def __rfloordiv__(self, other): + return torch.floor_divide(other, self) + + @_handle_torch_function_and_wrap_type_error_to_not_implemented + def __rlshift__(self, other): + return torch.bitwise_left_shift(other, self) + + @_handle_torch_function_and_wrap_type_error_to_not_implemented + def __rrshift__(self, other): + return torch.bitwise_right_shift(other, self) + + @_handle_torch_function_and_wrap_type_error_to_not_implemented + def __rmatmul__(self, other): + 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): + 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): + 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: Union[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") + ... 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. + """ + + sizes = tensor.size() + strides = tensor.stride() + + # Check if there are any duplicate strides + has_duplicate_strides = any( + earlier == later for earlier, later in zip(strides, strides[1:]) + ) + + # Check if there are any singleton dimensions + has_singleton_dims = any(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 + + return tuple(utils.compute_elementwise_output_logical_to_physical_perm(self)) + + 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=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 None or -1 is passed then no synchronization is performed. + If 1 (on CUDA) or 0 (on ROCM) then the default stream is used for + synchronization. + """ + if has_torch_function_unary(self): + return handle_torch_function(Tensor.__dlpack__, (self,), self, stream) + + # 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 RuntimeError( + "Can't export tensors that require gradient, use tensor.detach()" + ) + if self.is_conj(): + raise RuntimeError("Can't export tensors with the conjugate bit set") + if self.layout != torch.strided: + raise RuntimeError( + "Can't export tensors with layout other than torch.strided" + ) + + 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 stream is not None and stream != -1: + if self.device.type == "cuda": + # 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 + if stream == 1 and torch.version.hip is None: + stream = torch.cuda.default_stream() + elif stream == 0 and torch.version.hip is not None: + stream = torch.cuda.default_stream() + else: + stream = torch.cuda.ExternalStream(stream) + # Only synchronize on different streams + sync_stream = torch.cuda.current_stream() + if stream != sync_stream: + event = torch.cuda.Event() + event.record(sync_stream) + stream.wait_event(event) + 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." + ) + return xla_dlpack.to_dlpack(self) + return torch.to_dlpack(self) + + 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.kDLCPUPinned + elif torch_device_type == "cuda": + device_type = DLDeviceType.kDLGPU + 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.kDLGPU + 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_tensor_docs.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_tensor_docs.py new file mode 100644 index 0000000000000000000000000000000000000000..38a8708b1b59a1caa0abf03db0c0a589fa475f8a --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_tensor_docs.py @@ -0,0 +1,6971 @@ +# 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): 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. +""", +) + +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`): The destination GPU device. + Defaults to the current CUDA 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. 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`): The destination MTIA device. + Defaults to the current MTIA 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. 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`): The destination IPU device. + Defaults to the current IPU 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. 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`): The destination XPU device. + Defaults to the current XPU 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. 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): the diagonal 'wrapped' after N columns for tall matrices. + +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 identites. + +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): 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): whether to accumulate into self + +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`. + +:attr:`self`, :attr:`index` and :attr:`src` (if it is a Tensor) 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. + +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. + +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( + "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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_tensor_str.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_tensor_str.py new file mode 100644 index 0000000000000000000000000000000000000000..921e97be233ad18e6beea5ee50f4b809506c60ea --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_tensor_str.py @@ -0,0 +1,726 @@ +# mypy: allow-untyped-defs +import contextlib +import dataclasses +import math +import textwrap +from typing import Any, Optional + +import torch +from torch import inf + + +@dataclasses.dataclass +class __PrinterOptions: + precision: int = 4 + threshold: float = 1000 + edgeitems: int = 3 + linewidth: int = 80 + sci_mode: Optional[bool] = 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 + + 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 ( + nonzero_finite_max / nonzero_finite_min > 1000.0 + or nonzero_finite_max > 1.0e8 + ): + self.sci_mode = True + 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 ( + nonzero_finite_max / nonzero_finite_min > 1000.0 + or nonzero_finite_max > 1.0e8 + or nonzero_finite_min < 1.0e-4 + ): + self.sci_mode = True + 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)) + + if PRINT_OPTS.sci_mode is not None: + self.sci_mode = PRINT_OPTS.sci_mode + + 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, int(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(0, 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(0, 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(0, 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] + grad_fn_name = type(grad_fn).__name__ + if grad_fn_name == "CppFunction": + 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_thread_safe_fork.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_thread_safe_fork.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_torch_docs.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_torch_docs.py new file mode 100644 index 0000000000000000000000000000000000000000..c7a10a8dfaeb3b5fef92221f52c1c1abe92577a9 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_torch_docs.py @@ -0,0 +1,14140 @@ +# 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. +""" + }, + { + "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`. + 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 + +Computes the inverse cosine 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. + +.. 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 of :attr:`input`. + +.. 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 of :attr:`input`. + +.. 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`. + +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`. + +.. 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. + +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. + +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.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 exclusive 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` which is a `LongTensor`. + +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) -> (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} +""".format(**common_args), +) + +add_docstr( + torch.is_complex, + r""" +is_complex(input) -> (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} +""".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: bool value of Tensor with more than one value is ambiguous + >>> torch.is_nonzero(torch.tensor([])) + Traceback (most recent call last): + ... + RuntimeError: bool 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. + +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_all_reduce} + {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(**multi_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 ``max``/``min`` and ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + +{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 (rounding down for .5 fractions). +- ``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): 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. + +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_all_reduce} + {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 ``max``/``min`` and ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + +{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 multiple and removed after. + The non-matrix (i.e. batch) dimensions are :ref:`broadcasted ` (and thus + must be broadcastable). For example, if :attr:`input` is a + :math:`(j \times 1 \times n \times n)` tensor and :attr:`other` is a :math:`(k \times n \times n)` + tensor, :attr:`out` will be a :math:`(j \times k \times n \times n)` tensor. + + Note that the broadcasting logic only looks at the batch dimensions when determining if the inputs + are broadcastable, and not the matrix dimensions. 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, these inputs are valid for broadcasting even though the final two dimensions (i.e. the + matrix dimensions) are different. :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`. + +.. note:: This function is not defined for ``torch.cuda.Tensor`` yet. + +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, + r""" +rand_like(input, *, 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} + +Keyword args: + {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, \\*, 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} + 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: + {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, + r""" +randn_like(input, *, 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} + +Keyword args: + {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.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 of :attr:`input`. + +.. 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) + stable (bool, optional): makes the sorting routine stable, which guarantees that the order + of equivalent elements is preserved. + +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.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) + 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) + co-ordinates 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 co-ordinates 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 co-ordinates 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 co-ordinates 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 co-ordinates 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 of :attr:`input`. + +.. 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. + +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} +""".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, periodic=True, alpha=0.54, beta=0.46, *, dtype=None, \ +layout=torch.strided, device=None, 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 + periodic (bool, optional): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float, optional): The coefficient :math:`\alpha` in the equation above + beta (float, optional): 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} + {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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_utils.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8e818f58d9885e4d2ae08b1e47fb0491cf3650ba --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_utils.py @@ -0,0 +1,1111 @@ +# mypy: allow-untyped-defs +import copyreg +import functools +import importlib +import logging +import sys +import traceback +import warnings +from collections import defaultdict +from types import ModuleType +from typing import Any, Callable, Generic, Optional, 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 == 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'") + 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 readding 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] specifing 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 mimicks 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) + buf_and_size[1] += size + 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] + 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}" + if self.exc_type == 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 + raise self.exc_type(message=msg) + try: + exception = self.exc_type(msg) + 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: Optional[int] = 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) + # 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) + # 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) -> Optional[ModuleType]: + # 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_utils_internal.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_utils_internal.py new file mode 100644 index 0000000000000000000000000000000000000000..b5da1941450792df60aeab67d4a52267525e4fba --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_utils_internal.py @@ -0,0 +1,284 @@ +# mypy: allow-untyped-defs +import functools +import logging +import os +import sys +import tempfile +from typing import Any, Callable, Optional, 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 overrideable behavior. The motivating +# use is the FB build environment, where this source file is replaced +# by an equivalent. + +if torch._running_with_deploy(): + # __file__ is meaningless in the context of frozen torch used in torch deploy. + # setting empty torch_parent should allow below functions to operate without crashing, + # but it's unclear if there is a valid use case for them in the context of deploy. + torch_parent = "" +else: + 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(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 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_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 + + +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(): + 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() -> Optional[tuple[str, int]]: + 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) -> Optional[str]: + 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 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_vmap_internals.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_vmap_internals.py new file mode 100644 index 0000000000000000000000000000000000000000..6baee77ade54d2602be2eff99fa300d65661fd31 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_vmap_internals.py @@ -0,0 +1,245 @@ +# mypy: allow-untyped-defs +import functools +from typing import Any, Callable, Optional, Union +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 = Union[int, tuple] +out_dims_t = Union[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[Optional[int]], + 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: Union[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: Union[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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_weights_only_unpickler.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_weights_only_unpickler.py new file mode 100644 index 0000000000000000000000000000000000000000..2352bb836a9d263b8732013691c17a300e481a85 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_weights_only_unpickler.py @@ -0,0 +1,573 @@ +# 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 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, Callable, Union + +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[Union[Callable, tuple[Callable, str]]] = set() + + +def _add_safe_globals(safe_globals: list[Union[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[Union[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[Union[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[Union[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().keys(): + 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() + ): + raise UnpicklingError( + f"Trying to call reduce for unrecognized function {func}" + ) + 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 + 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.stack[-1][k] = v + elif key[0] == SETITEMS[0]: + items = self.pop_mark() + 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 not 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 {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(): + max_len = 0 + for shape in shapes: + if isinstance(shape, (int, torch.SymInt)): + if max_len < 1: + max_len = 1 + elif isinstance(shape, (tuple, list)): + s = len(shape) + if max_len < s: + max_len = s + result = [1] * max_len + + from torch.fx.experimental.symbolic_shapes import ( + guard_size_oblivious, + is_nested_int, + ) + + for shape in shapes: + if isinstance(shape, (int, torch.SymInt)): + shape = (shape,) + if isinstance(shape, (tuple, list)): + for i in range(-1, -1 - len(shape), -1): + if shape[i] < 0: + raise RuntimeError( + f"Trying to create tensor with negative dimension ({shape[i]}): ({shape[i]})" + ) + + # NB: handle nested ints specially to avoid invalid guarding on Ne(j0, 1). + if is_nested_int(shape[i]): + # Broadcasting is allowed for (j0, 1) or (j0, j0); + # not (j0, j1), (j0, 5), etc. + if is_nested_int(result[i]) and guard_size_oblivious( + shape[i] == result[i] + ): + continue + else: + # NB: result is initialized to 1 so this is effectively an + # equals one test + if guard_size_oblivious(shape[i] == 1) or guard_size_oblivious( + shape[i] == result[i] + ): + continue + + if result[i] != 1: + raise RuntimeError( + "Shape mismatch: objects cannot be broadcast to a single shape" + ) + result[i] = shape[i] + else: + raise RuntimeError( + "Input shapes should be of type ints, a tuple of ints, or a list of ints, got ", + shape, + ) + 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: Union[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 incase 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: Union[Tensor, list[Tensor]], indexing: Optional[str] = None + ) -> tuple[Tensor, ...]: + return _meshgrid(*tensors, indexing=indexing) + +else: + + def meshgrid(*tensors, indexing: Optional[str] = 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: Optional[str]): + 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: Optional[int] = None, + win_length: Optional[int] = None, + window: Optional[Tensor] = None, + center: bool = True, + pad_mode: str = "reflect", + normalized: bool = False, + onesided: Optional[bool] = None, + return_complex: Optional[bool] = None, + align_to_window: Optional[bool] = 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: Optional[int] = 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: Optional[int] = 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: Optional[torch.Tensor] = None, + ): + pass + + @overload + def tensordot( # noqa: F811 + a, + b, + dims: tuple[list[int], list[int]], + out: Optional[torch.Tensor] = None, + ): + pass + + @overload + def tensordot( # noqa: F811 + a, + b, + dims: list[list[int]], + out: Optional[torch.Tensor] = None, + ): + pass + + @overload + def tensordot( # noqa: F811 + a, + b, + dims: torch.Tensor, + out: Optional[torch.Tensor] = None, + ): + pass + + +def tensordot( # noqa: F811 + a, + b, + dims=2, + out: Optional[torch.Tensor] = 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 list of Tensors) + + 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.])) + """ + # 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 list of Tensors) + + 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.]])) + """ + # 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 list of Tensors) + + 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.]]])) + """ + # 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: Optional[Union[float, str]] = "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 + ): + 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 BraodcastingList1 + # 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: Union[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: Union[int, Sequence[int]]) -> Tensor: + torch._check_type( + not indices.is_complex() + and not indices.is_floating_point() + and not 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]) + 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): controls whether pivoting is done. 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/hub.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/hub.py new file mode 100644 index 0000000000000000000000000000000000000000..f2ad124f9286044bd04594c197fd0cf8e0f34a56 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/hub.py @@ -0,0 +1,875 @@ +# 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, Optional, Union +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: Optional[str] = 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}" + 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 explicitely 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." + ) + 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 " + "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" + ) + 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 len(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") + + if _hub_dir is not None: + return _hub_dir + return os.path.join(_get_torch_home(), "hub") + + +def set_dir(d: Union[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: Optional[str] = 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", + ... ) + + """ + file_size = None + req = Request(url, headers={"User-Agent": "torch.hub"}) + u = urlopen(req) + meta = u.info() + if hasattr(meta, "getheaders"): + content_length = meta.getheaders("Content-Length") + else: + content_length = meta.get_all("Content-Length") + if content_length is not None and len(content_length) > 0: + file_size = int(content_length[0]) + + # 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") + except FileExistsError: + continue + break + else: + raise FileExistsError(errno.EEXIST, "No usable temporary file name found") + + try: + if hash_prefix is not None: + sha256 = hashlib.sha256() + 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) # type: ignore[possibly-undefined] + if hash_prefix is not None: + sha256.update(buffer) # type: ignore[possibly-undefined] + pbar.update(len(buffer)) + + f.close() + if hash_prefix is not None: + digest = sha256.hexdigest() # type: ignore[possibly-undefined] + 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): + infolist = zipfile.ZipFile(filename).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: Optional[str] = None, + map_location: MAP_LOCATION = None, + progress: bool = True, + check_hash: bool = False, + file_name: Optional[str] = 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" + ) + + 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/library.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/library.py new file mode 100644 index 0000000000000000000000000000000000000000..b0934a2511165078212d0d017e339df18e2ef44d --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/library.py @@ -0,0 +1,1620 @@ +# mypy: allow-untyped-defs +import contextlib +import functools +import inspect +import re +import sys +import traceback +import weakref +from collections.abc import Sequence +from typing import ( + Any, + Callable, + Literal, + Optional, + 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.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", + "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.", + ) + if torch._running_with_deploy(): + _library.utils.warn_deploy() + return + + frame = traceback.extract_stack(limit=3)[0] + filename, lineno = frame.filename, frame.lineno + self.m: Optional[Any] = 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") + """ + if torch._running_with_deploy(): + _library.utils.warn_deploy() + return + + # 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.""" + if torch._running_with_deploy(): + _library.utils.warn_deploy() + return + + 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 + """ + if torch._running_with_deploy(): + _library.utils.warn_deploy() + return + + 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 torch._running_with_deploy(): + _library.utils.warn_deploy() + return + + if dispatch_key == "": + dispatch_key = self.dispatch_key + 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 torch._running_with_deploy(): + _library.utils.warn_deploy() + return + + 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 torch._running_with_deploy(): + _library.utils.warn_deploy() + return + + if dispatch_key == "": + dispatch_key = self.dispatch_key + + if self.ns != "_": + raise RuntimeError( + f"""Fallback can only be registered using libary 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 _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: Union[str, Sequence[str]], + func: Literal[None] = None, + *, + lib: Optional[Library] = None, +) -> Callable[[Callable[..., object]], None]: ... + + +@overload +def impl( + qualname: str, + types: Union[str, Sequence[str]], + func: Callable[..., object], + *, + lib: Optional[Library] = 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: Union[str, Sequence[str]], + func: Optional[Callable[_P, _T]] = None, + *, + lib: Optional[Library] = 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: Union[str, Sequence[str]], + func: Literal[None] = None, + *, + lib: Optional[Library] = None, + disable_dynamo: bool = False, +) -> Callable[[Callable[..., object]], None]: ... + + +@overload +def _impl( + qualname: str, + types: Union[str, Sequence[str]], + func: Callable[..., object], + *, + lib: Optional[Library] = None, + disable_dynamo: bool = False, +) -> None: ... + + +def _impl( + qualname: str, + types: Union[str, Sequence[str]], + func: Optional[Callable[..., object]] = None, + *, + lib: Optional[Library] = None, + disable_dynamo: bool = False, +) -> Optional[Callable[[Callable[..., object]], 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: Optional[Callable] = None, + /, + *, + lib: Optional[Library] = 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: Optional[Library] = 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 kernel(_, *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)) + + 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: Optional[Callable] = None, + /, + *, + lib: Optional[Library] = 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_autograd( + op: _op_identifier, + backward: Callable, + /, + *, + setup_context: Optional[Callable] = 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: Optional[Callable] = None, + /, + *, + lib: Optional[Library] = 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: Optional[Callable] = 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() + + +_OPCHECK_DEFAULT_UTILS = ( + "test_schema", + "test_autograd_registration", + "test_faketensor", + "test_aot_dispatch_dynamic", +) + + +def opcheck( + op: Union[torch._ops.OpOverload, torch._ops.OpOverloadPacket, CustomOpDef], + args: tuple[Any, ...], + kwargs: Optional[dict[str, Any]] = None, + *, + test_utils: Union[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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/overrides.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/overrides.py new file mode 100644 index 0000000000000000000000000000000000000000..7f89475a164dd47ac1c42c30b286311fa9993a1c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/overrides.py @@ -0,0 +1,2117 @@ +""" +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 types +import warnings +from collections.abc import Iterable +from functools import wraps +from typing import Any, Callable, Optional, 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 + return { + 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.randn, + torch.randint, + 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.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._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, + } + + +@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: -1, + torch.fbgemm_linear_fp16_weight_fp32_activation: lambda input, packed_weight, bias: -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.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.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.rand_like: lambda input, dtype=None, layout=None, device=None, requires_grad=False: -1, + torch.randint_like: lambda input, high, dtype=None, layout=torch.strided, device=None, requires_grad=False: -1, + torch.randn_like: lambda input, dtype=None, layout=None, device=None, requires_grad=False: -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._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: -1, + Tensor.__dlpack_device__: lambda self: -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: Optional[Callable[[Any], type]] = 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__ != 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, + ) + + # 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__`` overrideable 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()`" + ) + 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/py.typed b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/quasirandom.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/quasirandom.py new file mode 100644 index 0000000000000000000000000000000000000000..b5d4540e592f190e5e239391c40003a0bbc30146 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/quasirandom.py @@ -0,0 +1,217 @@ +# mypy: allow-untyped-defs +from typing import Optional + +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: Optional[torch.Tensor] = None, + dtype: Optional[torch.dtype] = 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: Optional[torch.Tensor] = None, + dtype: Optional[torch.dtype] = 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: Optional[torch.Generator] = 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/random.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/random.py new file mode 100644 index 0000000000000000000000000000000000000000..18a1cf9a5d5de2f2385687d9fe62c847b098642d --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/random.py @@ -0,0 +1,203 @@ +# 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`. + """ + 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) + _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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/return_types.pyi b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/return_types.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e8dce0869e225ea2a50200240469d220ed296e34 --- /dev/null +++ b/data/tefig/envs/olmes-eval/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/serialization.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..ce74c9cc85fa64d527ae537f288208decd3711ab --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/serialization.py @@ -0,0 +1,2130 @@ +# 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 contextlib import closing, contextmanager +from enum import Enum +from typing import Any, Callable, cast, Generic, IO, Optional, TypeVar, Union +from typing_extensions import TypeAlias, 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 = Optional[ + Union[Callable[[Storage, str], Storage], torch.device, str, dict[str, str]] +] +STORAGE: TypeAlias = Union[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: Optional[MAP_LOCATION] = 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], Optional[str]], + Callable[[STORAGE, str], Optional[STORAGE]], + ] +] = [] + + +class LoadEndianness(Enum): + NATIVE = 1 + LITTLE = 2 + BIG = 3 + + +def get_default_load_endianness() -> Optional[LoadEndianness]: + """ + 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 compuation flag + """ + from torch.utils.serialization import config + + config.save.compute_crc32 = compute_crc32 + + +def get_default_mmap_options() -> Optional[int]: + """ + 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[Union[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[Union[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], Optional[str]], + deserializer: Callable[[STORAGE, str], Optional[STORAGE]], +): + """ + 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") + 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"), +) + + +def location_tag( + storage: Union[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[Union[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: Union[str, os.PathLike[str]], mode: str) -> None: + super().__init__(open(name, mode)) + + 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: Union[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. + self.file_stream = io.FileIO(self.name, mode="w") + super().__init__( + torch._C.PyTorchFileWriter( + 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: Union[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) -> Optional[tuple]: + # 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." + ) + 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: Optional[tuple[str, int, int]] + + # 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 occurance 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 = dict( + protocol_version=PROTOCOL_VERSION, + little_endian=sys.byteorder == "little", + type_sizes=dict( + 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) + + pickler = PyTorchLegacyPickler(f, protocol=pickle_protocol) + pickler.dump(obj) + + 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 = {} + 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) + + pickler = PyTorchPickler(data_buf, protocol=pickle_protocol) + pickler.dump(obj) + 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.keys(): + 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: Optional[bool] = None, + mmap: Optional[bool] = 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), + ... 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 += 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.keys(): + 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, + ) + 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." + ) + 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) + + 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, + ) + + 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 of 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") + 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/torch_version.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/torch_version.py new file mode 100644 index 0000000000000000000000000000000000000000..0496a1b564feefe4a52280e2d7f268516f256a70 --- /dev/null +++ b/data/tefig/envs/olmes-eval/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/types.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/types.py new file mode 100644 index 0000000000000000000000000000000000000000..ab6f4639f444153c00f4e03a63d1b45561dad786 --- /dev/null +++ b/data/tefig/envs/olmes-eval/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, Union +from typing_extensions import Self, TypeAlias + +# `as` imports have better static analysis support than assignment `ExposedType: TypeAlias = HiddenType` +from torch import ( # noqa: F401 + device as _device, + DispatchKey as DispatchKey, + dtype as _dtype, + layout as _layout, + qscheme as _qscheme, + Size as Size, + SymBool as SymBool, + SymFloat as SymFloat, + SymInt as SymInt, + Tensor as 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 = Union[Tensor, Sequence[Tensor]] # noqa: PYI047 +_TensorOrTensorsOrGradEdge: TypeAlias = Union[ # noqa: PYI047 + Tensor, + Sequence[Tensor], + "GradientEdge", + Sequence["GradientEdge"], +] + +_size: TypeAlias = Union[Size, list[int], tuple[int, ...]] # noqa: PYI042,PYI047 +_symsize: TypeAlias = Union[Size, Sequence[Union[int, SymInt]]] # noqa: PYI042,PYI047 +_dispatchkey: TypeAlias = Union[str, DispatchKey] # noqa: PYI042,PYI047 + +# int or SymInt +IntLikeType: TypeAlias = Union[int, SymInt] +# float or SymFloat +FloatLikeType: TypeAlias = Union[float, SymFloat] +# bool or SymBool +BoolLikeType: TypeAlias = Union[bool, SymBool] + +py_sym_types = (SymInt, SymFloat, SymBool) # left un-annotated intentionally +PySymType: TypeAlias = Union[SymInt, SymFloat, SymBool] + +# Meta-type for "numeric" things; matches our docs +Number: TypeAlias = Union[int, float, bool] +# tuple for isinstance(x, Number) checks. +# FIXME: refactor once python 3.9 support is dropped. +_Number = (int, float, bool) + +FileLike: TypeAlias = Union[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 = Union[_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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/version.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/version.py new file mode 100644 index 0000000000000000000000000000000000000000..ad43d871af92191ab970268faeeaad58a5eb4fb4 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/version.py @@ -0,0 +1,9 @@ +from typing import Optional + +__all__ = ['__version__', 'debug', 'cuda', 'git_version', 'hip', 'xpu'] +__version__ = '2.8.0+cu128' +debug = False +cuda: Optional[str] = '12.8' +git_version = 'a1cb3cc05d46d198467bebbb6e8fba50a325d4e7' +hip: Optional[str] = None +xpu: Optional[str] = None diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9fae790ddec6eaf37078f2f459ee9deb97556914 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/__init__.py @@ -0,0 +1,121 @@ +import logging +import os +import re + +# torch/nested/_internal/nested_tensor.py:417: UserWarning: Failed to initialize NumPy: No module named 'numpy' +import warnings + +import torch + +warnings.filterwarnings( + "ignore", message="Failed to initialize NumPy: No module named 'numpy'" +) + +# We use this "hack" to set torchao.__version__ correctly +# the version of ao is dependent on environment variables for multiple architectures +# For local development this will default to whatever is version.txt +# For release builds this will be set the version+architecture_postfix +from importlib.metadata import PackageNotFoundError, version + +try: + __version__ = version("torchao") +except PackageNotFoundError: + __version__ = "unknown" # In case this logic breaks don't break the build + + +logger = logging.getLogger(__name__) + + +def is_fbcode(): + return not hasattr(torch.version, "git_version") + + +def _parse_version(version_string): + """ + Parse version string representing pre-release with -1 + + Examples: "2.5.0.dev20240708+cu121" -> [2, 5, -1], "2.5.0" -> [2, 5, 0] + """ + # Check for pre-release indicators + is_prerelease = bool(re.search(r"(git|dev)", version_string)) + match = re.match(r"(\d+)\.(\d+)\.(\d+)", version_string) + if match: + major, minor, patch = map(int, match.groups()) + if is_prerelease: + patch = -1 + return [major, minor, patch] + else: + raise ValueError(f"Invalid version string format: {version_string}") + + +skip_loading_so_files = False +_skip_reason = None +force_skip_loading_so_files = ( + os.getenv("TORCHAO_FORCE_SKIP_LOADING_SO_FILES", "0") == "1" +) +if force_skip_loading_so_files: + # user override + # users can set env var TORCHAO_FORCE_SKIP_LOADING_SO_FILES=1 to skip loading .so files + # this way, if they are using an incompatbile torch version, they can still use the API by setting the env var + skip_loading_so_files = True + _skip_reason = ( + "Skipping import of cpp extensions due to TORCHAO_FORCE_SKIP_LOADING_SO_FILES=1" + ) +elif is_fbcode(): + skip_loading_so_files = False +# if torchao version has "+git", assume it's locally built and we don't know +# anything about the PyTorch version used to build it unless user provides override flag +# otherwise, assume it's prebuilt by torchao's build scripts and we can make +# assumptions about the PyTorch version used to build it. +elif not ("+git" in __version__) and not ("unknown" in __version__): + current_torch_version = _parse_version(torch.__version__) + min_torch_version = _parse_version("2.11.0") + if current_torch_version >= min_torch_version: + skip_loading_so_files = False + else: + skip_loading_so_files = True + _skip_reason = ( + f"Skipping import of cpp extensions due to incompatible torch version. " + f"Please upgrade to torch >= 2.11.0 (found {torch.__version__})." + ) + +if skip_loading_so_files: + logger.warning(_skip_reason) +else: + try: + from pathlib import Path + + # Load .so files + so_files = list(Path(__file__).parent.glob("_C*.so")) + if len(so_files) > 0: + for file in so_files: + logger.debug(f"Loading {file}") + try: + torch.ops.load_library(str(file)) + except Exception as e: + logger.warning(f"Failed to load {file}: {e}") + from . import ops + + # The following registers meta kernels for some CPU kernels + from torchao.csrc_meta_ops import * # noqa: F403 + except Exception as e: + logger.debug(f"Skipping import of cpp extensions: {e}") + +# must import dtypes before quantization +from . import dtypes # noqa: I001 + +from torchao.quantization import ( + quantize_, +) + +from . import optim, quantization, swizzle, testing + +__all__ = [ + "dtypes", + "optim", + "quantize_", + "swizzle", + "testing", + "ops", + "quantization", +] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/_executorch_ops.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/_executorch_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..5d680bcf82e05d02dacef5cf88be314a29334969 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/_executorch_ops.py @@ -0,0 +1,50 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. +import torch + +# TODO: delete these ops + + +def _quantized_decomposed_quantize_per_channel_group_wrapper(*args, **kwargs): + """ + Wrapper around torch.ops.quantized_decomposed.quantize_per_channel_group to mitigate + availability issue until it can be supplanted by new quantize_affine function. + """ + return torch.ops.quantized_decomposed.quantize_per_channel_group(*args, **kwargs) + + +def _quantized_decomposed_choose_qparams_per_token_asymmetric_wrapper(*args, **kwargs): + """ + Wrapper around torch.ops.quantized_decomposed.choose_qparams_per_token_asymmetric to mitigate + availability issue until it can be supplanted by new choose_qparams_affine function. + """ + return torch.ops.quantized_decomposed.choose_qparams_per_token_asymmetric( + *args, **kwargs + ) + + +def _quantized_decomposed_dequantize_per_channel_group_wrapper(*args, **kwargs): + """ + Wrapper around torch.ops.quantized_decomposed.dequantize_per_channel_group to mitigate + availability issue until it can be supplanted by new choose_qparams_affine function. + """ + return torch.ops.quantized_decomposed.dequantize_per_channel_group(*args, **kwargs) + + +def _quantized_decomposed_quantize_per_token_wrapper(*args, **kwargs): + """ + Wrapper around torch.ops.quantized_decomposed.quantize_per_token to mitigate + availability issue until it can be supplanted by new choose_qparams_affine function. + """ + return torch.ops.quantized_decomposed.quantize_per_token(*args, **kwargs) + + +def _quantized_decomposed_dequantize_per_token_wrapper(*args, **kwargs): + """ + Wrapper around torch.ops.quantized_decomposed.dequantize_per_token to mitigate + availability issue until it can be supplanted by new choose_qparams_affine function. + """ + return torch.ops.quantized_decomposed.dequantize_per_token(*args, **kwargs) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc_meta_ops.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc_meta_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..771bbfc4ce9cfc88e3a6734379adf367a22dba97 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc_meta_ops.py @@ -0,0 +1,63 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +from torch import Tensor +from torch.library import impl + +# Define meta ops. To support dynamic shapes, some meta ops need to +# be defined in python instead of C++. +torchao_lib = torch.library.Library("torchao", "IMPL") +for weight_nbit in range(1, 9): + + @impl(torchao_lib, f"_linear_8bit_act_{weight_nbit}bit_weight", "Meta") + def _( + activations: Tensor, + packed_weights: Tensor, + group_size: int, + n: int, + k: int, + ): + assert activations.dim() == 2 + m, k_ = activations.shape + assert k_ == k + return torch.empty(m, n, dtype=activations.dtype, device="meta") + + @impl(torchao_lib, f"_embedding_{weight_nbit}bit", "Meta") + def _( + packed_weight_qvals: Tensor, + num_embeddings: int, + embedding_dim: int, + weight_scales: Tensor, + weight_zeros: Tensor, + indices: Tensor, + ): + assert indices.dim() == 1 + num_out = indices.shape[0] + return torch.empty(num_out, embedding_dim, dtype=torch.float32, device="meta") + + @impl(torchao_lib, f"_shared_embedding_{weight_nbit}bit", "Meta") + def _(packed_weights: Tensor, group_size: int, n: int, k: int, indices: Tensor): + assert indices.dim() == 1 + num_out = indices.shape[0] + return torch.empty(num_out, k, dtype=torch.float32, device="meta") + + +for weight_nbit in range(1, 5): + + @impl(torchao_lib, f"_linear_groupwise_{weight_nbit}bit_weight_with_lut", "Meta") + def _( + activations: Tensor, + packed_weights: Tensor, + scale_group_size: int, + lut_group_size: int, + n: int, + k: int, + ): + assert activations.dim() == 2 + m, k_ = activations.shape + assert k_ == k + return torch.empty(m, n, dtype=activations.dtype, device="meta") diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/ops.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/ops.py new file mode 100644 index 0000000000000000000000000000000000000000..ec60bd9a6db5da97c27e0c7ca4c0e2fa12870ce1 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/ops.py @@ -0,0 +1,476 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. +import functools +from typing import Optional + +import torch +from torch import Tensor + +lib = torch.library.Library("torchao", "FRAGMENT") +lib.define( + "rowwise_scaled_linear_sparse_cutlass_f8f8(Tensor input, Tensor input_scale, Tensor weight, Tensor weight_meta, Tensor weight_scale, Tensor? bias=None, ScalarType? out_dtype=None) -> Tensor" +) +lib.define( + "to_sparse_semi_structured_cutlass_sm9x_f8(Tensor weight) -> (Tensor, Tensor)" +) +lib.define( + "swizzle_mm(Tensor mat1, Tensor mat2, bool mat1_is_swizzled, bool mat2_is_swizzled) -> Tensor" +) +lib.define( + "swizzle_scaled_mm(Tensor mat1, Tensor mat2, bool mat1_is_swizzled, bool mat2_is_swizzled, Tensor scale_a, Tensor scale_b, Tensor? bias=None, Tensor? scale_result=None, ScalarType? out_dtype=None) -> Tensor" +) +# Note: we need to add the `torch._C.Tag.needs_fixed_stride_order` tag in order for inductor +# to honor the layout constraints for `b` in the two ops below. +lib.define( + "mx_fp8_bf16(Tensor a, Tensor b, Tensor a_scale, Tensor b_scale) -> Tensor", + tags=[torch._C.Tag.needs_fixed_stride_order], +) +lib.define( + "qscaled_dot_product(Tensor query, Tensor key, Tensor value, Tensor? attn_mask=None, float dropout_p=0.0, bool is_causal=False, float? scale=None, float q_scale=1.0, int q_zp=0, float k_scale=1.0, int k_zp=0, float v_scale=1.0, int v_zp=0, float a_scale=1.0, int a_zp=0, float o_scale=1.0, int o_zp=0) -> Tensor" +) +lib.define( + "da8w4_linear_prepack_cpu(Tensor weight, Tensor scales, Tensor qzeros) -> (Tensor, Tensor, Tensor, Tensor)" +) +lib.define( + "da8w4_linear_cpu(Tensor input, Tensor input_scales, Tensor input_qzeros, Tensor weight, Tensor weight_scales, Tensor weight_qzeros, Tensor compensation, Tensor? bias, ScalarType output_dtype) -> Tensor" +) +lib.define( + "_scaled_embedding_bag(Tensor qweight, Tensor indices, Tensor offsets, Tensor weight_scale, float o_scale, int mode, bool include_last_offset, ScalarType output_dtype) -> Tensor" +) +lib.define( + "float8_linear_prepack_cpu(Tensor weight, Tensor scales) -> (Tensor, Tensor)" +) +lib.define( + "float8_linear_cpu(Tensor input, Tensor input_scales, Tensor weight, Tensor weight_scales, Tensor? bias, ScalarType output_dtype) -> Tensor" +) + + +def register_custom_op(name): + def decorator(func): + return torch.library.register_fake(f"{name}")(func) + + return decorator + + +def register_custom_op_impl(name): + def decorator(func): + return torch.library.custom_op(f"{name}", mutates_args=())(func) + + return decorator + + +@functools.lru_cache +def cached_compute_capability(): + device_props = torch.cuda.get_device_properties(torch.cuda.current_device()) + compute_capability = device_props.major * 10 + device_props.minor + return compute_capability + + +def qscaled_dot_product( + query: Tensor, + key: Tensor, + value: Tensor, + attn_mask: Optional[Tensor] = None, + dropout_p: float = 0.0, + is_causal: bool = False, + scale: Optional[float] = None, + q_scale: float = 1.0, + q_zp: int = 0, + k_scale: float = 1.0, + k_zp: int = 0, + v_scale: float = 1.0, + v_zp: int = 0, + a_scale: float = 1.0, + a_zp: int = 0, + o_scale: float = 1.0, + o_zp: int = 0, +) -> Tensor: + """ + Quantized SDPA with quantized inputs and outputs. + Arguments + query: input query tensor, + key: input key tensor, + value: input value tensor, + attn_mask: attention mask tensor, + dropout_p: dropout probability, + is_causal: causal flag, + scale: scaling factor applied prior to softmax, + q_scale: scale for query from linear quantization, + q_zp: zero point for query from linear quantization, + k_scale: scale for key from linear quantization, + k_zp: zero point of key from linear quantization, + v_scale: zero point for value from linear quantization, + v_zp: zero point of value from linear quantization, + a_scale: scale for attention from softmax quantization, + a_zp: zero point for attention from softmax quantization, + o_scale: scale for output from linear quantization, + o_zp: zero point for output from linear quantization, + Returns + output of quantized SDPA + """ + return torch.ops.torchao.qscaled_dot_product.default( + query, + key, + value, + attn_mask, + dropout_p, + is_causal, + scale, + q_scale, + q_zp, + k_scale, + k_zp, + v_scale, + v_zp, + a_scale, + a_zp, + o_scale, + o_zp, + ) + + +@register_custom_op("torchao::qscaled_dot_product") +def _( + query: Tensor, + key: Tensor, + value: Tensor, + attn_mask: Optional[Tensor] = None, + dropout_p: float = 0.0, + is_causal: bool = False, + scale: Optional[float] = None, + q_scale: float = 1.0, + q_zp: int = 0, + k_scale: float = 1.0, + k_zp: int = 0, + v_scale: float = 1.0, + v_zp: int = 0, + a_scale: float = 1.0, + a_zp: int = 0, + o_scale: float = 1.0, + o_zp: int = 0, +) -> Tensor: + return query + + +def rowwise_scaled_linear_sparse_cutlass_f8f8( + input: Tensor, + input_scale: Tensor, + weight: Tensor, + weight_meta: Tensor, + weight_scale: Tensor, + bias: Optional[Tensor] = None, + out_dtype: Optional[torch.dtype] = None, +) -> Tensor: + """ + CUTLASS-based row-wise scaled F8F8 linear operator, for sparsified weight case. + Args: + input: quantized input tensor, in row-major layout. + input_scale: scale factors for input tensor, has to be tensor of the same shape as the input tensor, minus the last dimension. + weight: sparsified quantized weight matrix, in row-major layout. + weight_meta: sparsify metadata for weight tensor. + weight_scale: scale factors for weight tensor, one value per row of weight matrix (thus also tensor of the same shape as the weight tensor, minus the last dimension). + bias: an optional vector of size equal to number of rows of weight tensor, or None. + out_dtype: optional data type for output tensor. + Returns: + output: result tensor, in row-major layout. + """ + + return torch.ops.torchao.rowwise_scaled_linear_sparse_cutlass_f8f8.default( + input, input_scale, weight, weight_meta, weight_scale, bias, out_dtype + ) + + +@register_custom_op("torchao::rowwise_scaled_linear_sparse_cutlass_f8f8") +def _( + input: Tensor, + input_scale: Tensor, + weight: Tensor, + weight_meta: Tensor, + weight_scale: Tensor, + bias: Optional[Tensor] = None, + out_dtype: Optional[torch.dtype] = None, +) -> Tensor: + # No checks here, as detailed checks are performed by the + # operator itself. + + dtype = out_dtype if out_dtype is not None else input_scale.dtype + device = input.device + return torch.empty((*input.shape[:-1], weight.shape[0]), dtype=dtype, device=device) + + +def to_sparse_semi_structured_cutlass_sm9x_f8( + weight: Tensor, +) -> (Tensor, Tensor): + """ + CUTLASS-based conversion from sparsified input tensor to corresponding compressed tensor, along with corresponding metadata tensor. + Args: + weight: input tensor, in row-major layout. + Returns: + weight_compressed: compressed weight tensor, with sparsity eliminated, in row-major layout. + weight_meta: metadata tensor, describing the sparsity structure of the input tensor, also in row-major layout. + """ + + return torch.ops.torchao.to_sparse_semi_structured_cutlass_sm9x_f8.default(weight) + + +@register_custom_op("torchao::to_sparse_semi_structured_cutlass_sm9x_f8") +def _( + weight: Tensor, +) -> (Tensor, Tensor): + # No checks here, as detailed checks are performed by the + # operator itself. + + return ( + weight.new_empty(weight[0], weight[1] // 2), + weight.new_empty(weight[0], max(weight[1] // 8, 16), dtype=torch.char), + ) + + +def swizzle_mm( + mat1: Tensor, mat2: Tensor, mat1_is_swizzled: bool, mat2_is_swizzled: bool +) -> Tensor: + """ + Similar to torch.mm but Tensor inputs can be SwizzleTensor instances. + """ + return torch.ops.torchao.swizzle_mm.default( + mat1, mat2, mat1_is_swizzled, mat2_is_swizzled + ) + + +@register_custom_op("torchao::swizzle_mm") +def _( + mat1: Tensor, mat2: Tensor, mat1_is_swizzled: bool, mat2_is_swizzled: bool +) -> Tensor: + return mat1.new_empty(mat1.shape[0], mat2.shape[1]) + + +def swizzle_scaled_mm( + mat1: Tensor, + mat2: Tensor, + mat1_is_swizzled: bool, + mat2_is_swizzled: bool, + scale_a: Tensor, + scale_b: Tensor, + bias: Optional[Tensor], + scale_result: Optional[Tensor], + out_dtype: Optional[torch.dtype], +) -> Tensor: + """ + Similar to torch.mm but Tensor inputs can be SwizzleTensor instances. + + """ + return torch.ops.torchao.swizzle_scaled_mm.default( + mat1, + mat2, + mat1_is_swizzled, + mat2_is_swizzled, + scale_a, + scale_b, + bias, + scale_result, + out_dtype, + ) + + +@register_custom_op("torchao::swizzle_scaled_mm") +def _( + mat1: Tensor, + mat2: Tensor, + mat1_is_swizzled: bool, + mat2_is_swizzled: bool, + scale_a: Tensor, + scale_b: Tensor, + bias: Optional[Tensor], + scale_result: Optional[Tensor], + out_dtype: Optional[torch.dtype], +) -> Tensor: + return mat1.new_empty(mat1.shape[0], mat2.shape[1]) + + +@functools.lru_cache() +def _get_dtypes(): + """TODO: when e8m0 is hardened and major release lets remove uint8 support""" + if hasattr(torch, "float8_e8m0fnu"): + return (torch.uint8, torch.float8_e8m0fnu) + return (torch.uint8,) + + +def _check_scale_dtypes(A_scale, B_scale): + allowed_dtypes = _get_dtypes() + + torch._check( + A_scale.dtype in allowed_dtypes, + lambda: f"A_scale tensor must be uint8 or float8_e8m0fnu, got {A_scale.dtype}", + ) + torch._check( + B_scale.dtype in allowed_dtypes, + lambda: f"B_scale tensor must be uint8 or float8_e8m0fnu, got {B_scale.dtype}", + ) + + +@register_custom_op("torchao::mx_fp8_bf16") +def meta_mx_fp8_bf16(A: Tensor, B: Tensor, A_scale: Tensor, B_scale: Tensor): + """Meta impl for mx_fp8_bf16""" + return torch.empty((A.size(0), B.size(1)), dtype=torch.bfloat16, device=A.device) + + +def da8w4_linear_prepack_cpu( + weight: Tensor, + scales: Tensor, + qzeros: Tensor, +) -> Tensor: + """ + Prepack weights for DA8W4 linear operator on CPU. + Args: + weight: weight tensor. + scales: scales for weight tensor. + qzeros: zero points for weight tensor. + Returns: + packed weight, scales, and zero points. + """ + return torch.ops.torchao.da8w4_linear_prepack_cpu.default(weight, scales, qzeros) + + +@register_custom_op("torchao::da8w4_linear_prepack_cpu") +def _(weight: Tensor, scales: Tensor, qzeros: Tensor) -> Tensor: + return weight, scales, qzeros, torch.Tensor() + + +def da8w4_linear_cpu( + input: Tensor, + input_scales: Tensor, + input_qzeros: Tensor, + weight: Tensor, + weight_scales: Tensor, + weight_qzeros: Tensor, + compensation: Tensor, + bias: Optional[Tensor], + out_dtype: torch.dtype, +): + """ + DA8W4 linear operator on CPU. + Args: + input: input tensor. + input_scales: scales for input tensor. + input_qzeros: zero points for input tensor. + weight: weight tensor. + weight_scales: scales for weight tensor. + weight_qzeros: zero points for weight tensor. + compensation: compensation tensor for weight. + bias: optional bias tensor. + out_dtype: output data type. + Returns: + output tensor in out_dtype. + """ + return torch.ops.torchao.da8w4_linear_cpu.default( + input, + input_scales, + input_qzeros, + weight, + weight_scales, + weight_qzeros, + compensation, + bias, + out_dtype, + ) + + +@register_custom_op("torchao::da8w4_linear_cpu") +def _( + input: Tensor, + input_scales: Tensor, + input_qzeros: Tensor, + weight: Tensor, + weight_scales: Tensor, + weight_qzeros: Tensor, + compensation: Tensor, + bias: Optional[Tensor], + out_dtype: torch.dtype, +) -> Tensor: + assert weight.dim() == 4 + N = weight.size(0) * weight.size(3) * 2 + return input.new_empty(*input.shape[:-1], N, dtype=out_dtype) + + +@register_custom_op("torchao::_scaled_embedding_bag") +def _( + qweight: Tensor, + indices: Tensor, + offsets: Tensor, + w_scales: Tensor, + o_scale: float, + mode: int, + include_last_offset: bool, + out_dtype: torch.dtype, +) -> Tensor: + # Only support include_last_offset == True + assert include_last_offset == True + batch_size = offsets.shape[0] - 1 + return qweight.new_empty(batch_size, qweight.shape[1], dtype=out_dtype) + + +def float8_linear_prepack_cpu( + weight: Tensor, + scales: Tensor, +) -> Tensor: + """ + Prepack weights for float8 linear operator on CPU. + Args: + weight: weight tensor. + scales: scales for weight tensor. + Returns: + packed weight, packed scales + """ + return torch.ops.torchao.float8_linear_prepack_cpu.default(weight, scales) + + +@register_custom_op("torchao::float8_linear_prepack_cpu") +def _(weight: Tensor, scales: Tensor) -> Tensor: + return weight, scales + + +def float8_linear_cpu( + input: Tensor, + input_scales: Tensor, + weight: Tensor, + weight_scales: Tensor, + bias: Optional[Tensor], + out_dtype: torch.dtype, +): + """ + float8 linear operator on CPU. + Args: + input: input tensor. + input_scales: scales for input tensor. + weight: weight tensor. + weight_scales: scales for weight tensor. + bias: optional bias tensor. + out_dtype: output data type. + Returns: + output tensor in out_dtype. + """ + return torch.ops.torchao.float8_linear_cpu.default( + input, + input_scales, + weight, + weight_scales, + bias, + out_dtype, + ) + + +@register_custom_op("torchao::float8_linear_cpu") +def _( + input: Tensor, + input_scales: Tensor, + weight: Tensor, + weight_scales: Tensor, + bias: Optional[Tensor], + out_dtype: torch.dtype, +) -> Tensor: + assert weight.dim() in (2, 4) + N = weight.size(0) * weight.size(3) if weight.dim() == 4 else weight.size(0) + return input.new_empty(*input.shape[:-1], N, dtype=out_dtype) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/utils.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0bb2218a7f99afeb8381674380d1ff8ce9ac910b --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/utils.py @@ -0,0 +1,1299 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. +import functools +import importlib +import itertools +import re +import time +from functools import reduce +from importlib.metadata import version +from math import gcd +from typing import Any, Callable, Optional + +import torch +import torch.nn.utils.parametrize as parametrize +from torch.utils._python_dispatch import return_and_correct_aliasing + +__all__ = [ + "benchmark_model", + "profiler_runner", + "get_available_devices", + "get_compute_capability", + "benchmark_torch_function_in_microseconds", + "find_multiple", + "_register_custom_op", + "get_model_size_in_bytes", + "unwrap_tensor_subclass", + "TorchAOBaseTensor", + "is_cuda_version_at_least", + "is_MI300", + "is_sm_at_least_89", + "is_sm_at_least_90", + "is_sm_at_least_100", + "is_package_at_least", + "DummyModule", + "register_as_pytree_constant", +] + + +def register_as_pytree_constant(cls): + """Decorator to register a class as a pytree constant for dynamo non-strict trace mode.""" + torch.utils._pytree.register_constant(cls) + return cls + + +# Referenced from: https://github.com/pytorch/pytorch/blob/9105d54c6b37099575c0059ef274c86c4dc80c57/torch/ao/quantization/utils.py#L711 +@functools.cache +def _assert_and_get_unique_device(module: torch.nn.Module) -> Any: + """ + Returns the unique device for a module, or None if no device is found. + Throws an error if multiple devices are detected. + """ + devices = {p.device for p in module.parameters()} | { + p.device for p in module.buffers() + } + + assert len(devices) <= 1, ( + "prepare only works with cpu or single-device CUDA modules, " + f"but got devices {devices}" + ) + device = next(iter(devices)) if len(devices) > 0 else None + return device + + +def benchmark_model(model, num_runs, args=(), kwargs=None, device_type=None): + """Benchmark model runs with `args` and `kwargs` both are optional""" + if kwargs is None: + kwargs = {} + + if device_type is None: + assert isinstance(model, torch.nn.Module), ( + "Expecting `model` to be torch.nn.Module if device_type is not provided" + ) + device_type = _assert_and_get_unique_device(model).type + + if device_type == "cuda": + torch.cuda.synchronize() + start_event = torch.cuda.Event(enable_timing=True) + end_event = torch.cuda.Event(enable_timing=True) + start_event.record() + + # benchmark + for _ in range(num_runs): + with torch.autograd.profiler.record_function("timed region"): + model(*args, **kwargs) + + end_event.record() + torch.cuda.synchronize() + return start_event.elapsed_time(end_event) / num_runs + + elif device_type == "mps": + torch.mps.synchronize() + start_event = torch.mps.event.Event(enable_timing=True) + end_event = torch.mps.event.Event(enable_timing=True) + start_event.record() + + # benchmark + for _ in range(num_runs): + with torch.autograd.profiler.record_function("timed region"): + model(*args, **kwargs) + + end_event.record() + torch.mps.synchronize() + return start_event.elapsed_time(end_event) / num_runs + + elif device_type == "cpu": + torch.cpu.synchronize() + start_time = time.time() + + # benchmark + for _ in range(num_runs): + with torch.autograd.profiler.record_function("timed region"): + model(*args, **kwargs) + + end_time = time.time() + torch.cpu.synchronize() + average_time_per_run = (end_time - start_time) / num_runs + return average_time_per_run + + elif device_type == "xpu": + torch.xpu.synchronize() + start_event = torch.xpu.Event(enable_timing=True) + end_event = torch.xpu.Event(enable_timing=True) + start_event.record() + + # benchmark + for _ in range(num_runs): + with torch.autograd.profiler.record_function("timed region"): + model(*args, **kwargs) + + end_event.record() + torch.xpu.synchronize() + return start_event.elapsed_time(end_event) / num_runs + + +def profiler_runner(path, fn, *args, **kwargs): + with torch.profiler.profile( + activities=[ + torch.profiler.ProfilerActivity.CPU, + torch.profiler.ProfilerActivity.CUDA, + ], + record_shapes=True, + ) as prof: + result = fn(*args, **kwargs) + prof.export_chrome_trace(path) + return result + + +def get_available_devices(): + devices = ["cpu"] + if torch.cuda.is_available(): + devices.append("cuda") + elif torch.xpu.is_available(): + devices.append("xpu") + if torch.mps.is_available(): + devices.append("mps") + return devices + + +def get_current_accelerator_device(): + assert torch.accelerator.is_available() + return torch.accelerator.current_accelerator() + + +def get_compute_capability(): + if torch.cuda.is_available(): + capability = torch.cuda.get_device_capability() + return float(f"{capability[0]}.{capability[1]}") + return 0.0 + + +def compute_max_diff(output: torch.Tensor, output_ref: torch.Tensor) -> torch.Tensor: + return torch.mean(torch.abs(output - output_ref)) / torch.mean( + torch.abs(output_ref) + ) + + +def benchmark_torch_function_in_microseconds(f, *args, **kwargs): + import torch.utils.benchmark as benchmark # this avoids importing numpy when torchao module is loaded + + # Manual warmup + f(*args, **kwargs) + f(*args, **kwargs) + + t0 = benchmark.Timer( + stmt="f(*args, **kwargs)", + globals={"args": args, "kwargs": kwargs, "f": f}, # noqa: E501 + ) + measurement = t0.blocked_autorange() + return measurement.mean * 1e6 + + +def find_multiple(n: int, *args: int) -> int: + k: int = reduce(lambda x, y: x * y // gcd(x, y), args + (1,)) # type: ignore[9] + if n % k == 0: + return n + return n + k - (n % k) + + +def _register_custom_op(lib, inductor_decomposed=True): + """This decorator is used to preserve some high level operators for torch.export.export + while still allow them to be decomposed for inductor path + + requirement: make sure `fn.__name__[1:]` is the operator name you want to register + + NOTE: This should be applied at the top, after all other decorators have been applied + NOTE: We haven't tested the case when `fn` accepts tensor subclass instance as input, + e.g. uint4 tensor subclass instance, and we'll probably need to figure out what would make + sense for downstream system (like executorch) to accept as well + + Example: + lib = torch.library.Library("my_namespace', "FRAGMENT") + + register_custom_op = _register_custom_op(lib) + + @register_custom_op + def _the_op_that_needs_to_be_preserved(...) + ... + + # after this, `_the_op_that_needs_to_be_preserved` will be preserved as + # torch.ops.my_namespace.the_op_that_needs_to_be_preserved operator after + # torch.export.export + + """ + from torch._inductor.decomposition import register_decomposition + + dispatch_key = ( + "CompositeImplicitAutograd" + if inductor_decomposed + else "CompositeExplicitAutograd" + ) + + def decorator(fn): + from torch._library.infer_schema import infer_schema + + assert not any(c in fn.__name__ for c in ".<>"), ( + f"Expecting op to be defined in normal functions, not lambda or local: {fn.__name__}" + ) + op_name = fn.__name__ + if op_name[0] == "_": + op_name = op_name[1:] + schema = op_name + infer_schema(fn, mutates_args={}) + lib.define(schema) + lib.impl(op_name, fn, dispatch_key) + + lib_namespace = lib.ns + op = getattr(getattr(torch.ops, lib_namespace), op_name) + if inductor_decomposed: + register_decomposition([op])(fn) + return op + + return decorator + + +def _register_meta_op(lib, op_name): + def decorator(fn): + op = lib.impl(op_name, fn, "Meta") + return op + + return decorator + + +def get_model_size_in_bytes(model, ignore_embeddings=False): + """ + Returns the model size in bytes. The option to ignore embeddings + is useful for models with disproportionately large embeddings compared + to other model parameters that get quantized/sparsified. + """ + + def flat_size(tensor): + if hasattr(tensor, "__tensor_flatten__"): + size = 0 + # 0th element is a list of attributes that + # hold tensors + for attr_name in tensor.__tensor_flatten__()[0]: + sub_tensor = getattr(tensor, attr_name) + size += flat_size(sub_tensor) + return size + else: + return tensor.numel() * tensor.element_size() + + model_size = 0 + for name, child in model.named_children(): + if not (isinstance(child, torch.nn.Embedding) and ignore_embeddings): + for p in itertools.chain( + child.parameters(recurse=False), child.buffers(recurse=False) + ): + model_size += flat_size(p) + model_size += get_model_size_in_bytes(child, ignore_embeddings) + return model_size + + +class UnwrapTensorSubclass(torch.nn.Module): + def forward(self, *tensors): + todo = list(tensors) + for tp, meta, inner_tensors in reversed(self.rebuild_stack): + nb_tensor = len(inner_tensors) + inner_tensors = {a: b for a, b in zip(inner_tensors, todo[-nb_tensor:])} + todo = todo[nb_tensor:] + rebuilt = tp.__tensor_unflatten__(inner_tensors, meta, None, None) + todo.append(rebuilt) + + assert len(todo) == 1 + return todo[0] + + def right_inverse(self, tensor): + assert type(tensor) is not torch.Tensor + rebuild_stack = [] + plain_tensors = [] + todo = [tensor] + while todo: + obj = todo.pop() + inner_tensors, metadata = obj.__tensor_flatten__() + rebuild_stack.append((type(obj), metadata, inner_tensors)) + for attr_name in inner_tensors: + val = getattr(obj, attr_name) + if type(val) is torch.Tensor: + plain_tensors.append(val) + else: + assert isinstance(val, torch.Tensor) + todo.append(val) + + self.rebuild_stack = rebuild_stack + + return plain_tensors + + +def unwrap_tensor_subclass(model, filter_fn=None): + """Unwraps (nested) tensor subclass in the model to plain tensors + This is a workaround to make a model with tensor subclass to work with `torch.export.export` + and `torch.aot_compile`, we hope this can be integrated into compile stack soon + tracking issue: https://github.com/pytorch/ao/issues/345 + """ + for name, child in model.named_children(): + # make sure child.weight is a tensor subclass + if ( + ( + isinstance(child, torch.nn.Linear) + or isinstance(child, torch.nn.Embedding) + ) + and hasattr(child, "weight") + and type(child.weight) is not torch.Tensor + and type(child.weight) is not torch.nn.Parameter + and isinstance(child.weight, torch.Tensor) + and issubclass(type(child.weight), torch.Tensor) + and isinstance(child.weight, TorchAOBaseTensor) + and not parametrize.is_parametrized(child) + ): + parametrize.register_parametrization( + child, "weight", UnwrapTensorSubclass() + ) + unwrap_tensor_subclass(child) + return model + + +def _is_float8_type(dtype: torch.dtype) -> bool: + fp8_types = { + torch.float8_e4m3fn, + torch.float8_e4m3fnuz, + torch.float8_e5m2, + torch.float8_e5m2fnuz, + } + return dtype in fp8_types + + +def parse_version(version_string): + """ + Parse version string representing pre-release with -1 + + Examples: "2.5.0.dev20240708+cu121" -> [2, 5, -1], "2.5.0" -> [2, 5, 0] + """ + # Check for pre-release indicators + is_prerelease = bool(re.search(r"(git|dev)", version_string)) + match = re.match(r"(\d+)\.(\d+)\.(\d+)", version_string) + if match: + major, minor, patch = map(int, match.groups()) + if is_prerelease: + patch = -1 + return [major, minor, patch] + else: + raise ValueError(f"Invalid version string format: {version_string}") + + +def is_fbcode(): + return not hasattr(torch.version, "git_version") + + +def torch_version_at_least(min_version): + if is_fbcode(): + return True + + # Parser for local identifiers + return parse_version(torch.__version__) >= parse_version(min_version) + + +""" +Helper function for implementing aten op or torch function dispatch +and dispatching to these implementations. +""" + + +def _implements(cls, aten_ops): + """Decorator for implementing aten ops like `torch.ops.aten.linear.default` for + tensor subclass, the implemented functions are called in ``__torch_dispatch__`` callback + for ``torch.Tensor`` subclasses + + Examples:: + + implements = MyTensor.implements + + @implements(torch.ops.aten.linear.default): + def _(func, types, args, kwargs): + ... + + """ + if not hasattr(cls, "_ATEN_OP_TABLE"): + cls._ATEN_OP_TABLE = {} + if cls not in cls._ATEN_OP_TABLE: + cls._ATEN_OP_TABLE[cls] = {} + if not isinstance(aten_ops, (list, tuple)): + aten_ops = [aten_ops] + + def decorator(func): + for op in aten_ops: + + @functools.wraps(func) + def wrapper(f, types, args, kwargs, _func=func): + return _func(f, types, args, kwargs) + + cls._ATEN_OP_TABLE[cls][op] = wrapper + return func + + return decorator + + +def _implements_torch_function(cls, torch_fns): + """Decorator for implementing torch functions / ops + like ``torch.nn.functional.linear``, ``torch.Tensor.t`` for the tensor subclass + the implemented functions are called in ``__torch_function__`` callback + for ``torch.Tensor`` subclasses + + Examples:: + + implements_torch_function = MyTensor.implements_torch_function + + @implements_torch_function(torch.nn.functional.linear): + def _(func, types, args, kwargs): + ... + + """ + if not hasattr(cls, "_TORCH_FN_TABLE"): + cls._TORCH_FN_TABLE = {} + if cls not in cls._TORCH_FN_TABLE: + cls._TORCH_FN_TABLE[cls] = {} + if not isinstance(torch_fns, (list, tuple)): + torch_fns = [torch_fns] + + def decorator(func): + for fn in torch_fns: + + @functools.wraps(func) + def wrapper(f, types, args, kwargs, _func=func): + return _func(f, types, args, kwargs) + + cls._TORCH_FN_TABLE[cls][fn] = wrapper + return func + + return decorator + + +def _implements_common_tensor_ops(cls): + implements = cls.implements + implements_torch_function = cls.implements_torch_function + aten = torch.ops.aten + + @implements(torch.ops.aten.to.dtype_layout) + def _(func, types, args, kwargs): + # only support kwargs for now + assert len(args) == 1 + self = args[0] + # only support dtype, layout, and device for now + for k in kwargs.keys(): + assert k in ["dtype", "layout", "device"] + # only support same dtype and layout + # different dtype and layout has undefined behavior + if "dtype" in kwargs: + assert kwargs["dtype"] == self.dtype + if "layout" in kwargs: + assert kwargs["layout"] == self.layout + # if device is the same, treat this like a no-op + device = kwargs.get("device") + if device == self.device: + return self + new_tensor = args[0]._apply_fn_to_data(lambda x: func(x, device=device)) + return return_and_correct_aliasing(func, args, kwargs, new_tensor) + + # This is called during _apply() to see if we can shallow + # copy the content of one tensor into another. For now, + # we only allow shallow copy if both tensors are of the + # same type and have the same shape. + @implements_torch_function(torch._has_compatible_shallow_copy_type) + def _(func, types, args, kwargs): + assert len(args) == 2 + return type(args[0]) == type(args[1]) and args[0].shape == args[1].shape + + @implements_torch_function( + [ + torch.Tensor.contiguous, + ] + ) + def _(func, types, args, kwargs): + return args[0]._apply_fn_to_data(lambda x: func(x, *args[1:], **kwargs)) + + @implements( + [ + aten.detach.default, + aten.clone.default, + aten.alias.default, + aten.contiguous.default, + ] + ) + def _(func, types, args, kwargs): + return return_and_correct_aliasing( + func, + args, + kwargs, + args[0]._apply_fn_to_data(lambda x: func(x, *args[1:], **kwargs)), + ) + + def _same_metadata(self: TorchAOBaseTensor, src: TorchAOBaseTensor) -> bool: + _tensor_shape_match = all( + getattr(self, t_name).shape == getattr(src, t_name).shape + for t_name in self.tensor_data_names + ) + _optional_tensor_shape_match = True + if hasattr(self, "optional_tensor_data_names"): + # either both are None or both are not Tensors and the shape match + _optional_tensor_shape_match = all( + ( + getattr(self, t_name).shape == getattr(src, t_name).shape + if getattr(self, t_name) is not None + else getattr(src, t_name) is None + ) + for t_name in self.optional_tensor_data_names + ) + + _attr_match = all( + getattr(self, a_name) == getattr(src, a_name) + for a_name in self.tensor_attribute_names + ) + + _optional_attr_match = True + if hasattr(self, "optional_tensor_attribute_names"): + _optional_attr_match = all( + getattr(self, a_name) == getattr(src, a_name) + for a_name in self.optional_tensor_attribute_names + ) + + return ( + type(self) == type(src) + and self.shape == src.shape + and _tensor_shape_match + and _optional_tensor_shape_match + and _attr_match + and _optional_attr_match + ) + + @implements(aten.copy_.default) + def _(func, types, args, kwargs): + self = args[0] + src = args[1] + if _same_metadata(self, src): + self_tensors = self.__tensor_flatten__()[0] + for tensor_name in self_tensors: + getattr(self, tensor_name).copy_(getattr(src, tensor_name)) + return + raise ValueError( + f"Not supported args for copy_ due to metadata mismatch: {args[0], args[1]}" + ) + + @implements(aten._to_copy.default) + def _(func, types, args, kwargs): + self = args[0] + if hasattr(self, "tensor_data_names") and hasattr( + self, "tensor_attribute_names" + ): + kwargs = self._get_to_kwargs(*args[1:], **kwargs) + device = kwargs.pop("device") + tensors = [ + getattr(self, name).to(device) for name in self.tensor_data_names + ] + optional_tensors = [] + if hasattr(self, "optional_tensor_data_names"): + for tensor_data_name in self.optional_tensor_data_names: + maybe_tensor = getattr(self, tensor_data_name) + if maybe_tensor is not None: + optional_tensors.append(maybe_tensor.to(device)) + else: + optional_tensors.append(None) + + # change device + tensor_attributes = [ + getattr(self, attr_name) if attr_name != "device" else device + for attr_name in self.tensor_attribute_names + ] + optional_tensor_attributes = [] + if hasattr(self, "optional_tensor_attribute_names"): + optional_tensor_attributes = [ + getattr(self, attr_name) if attr_name != "device" else device + for attr_name in self.optional_tensor_attribute_names + ] + + t = self.__class__( + *tensors, + *tensor_attributes, + *optional_tensors, + *optional_tensor_attributes, + ) + return return_and_correct_aliasing(func, args, kwargs, t) + + raise NotImplementedError( + "Subclasses must implement `aten._to_copy.default` or specify `tensor_data_names` and `tensor_attribute_names` for tensor class or tensor instance before using it" + ) + + +def _torchao_base_tensor__setstate__(self, state): + assert hasattr(self, "tensor_data_names") and hasattr( + self, "tensor_attribute_names" + ) + torch._utils._set_obj_state(self, state) + for optional_tensor_data_name in getattr(self, "optional_tensor_data_names", []): + if optional_tensor_data_name not in self.__dict__ and not hasattr( + self, optional_tensor_data_name + ): + setattr(self, optional_tensor_data_name, None) + + for optional_tensor_attribute_name in getattr( + self, "optional_tensor_attribute_names", [] + ): + if optional_tensor_attribute_name not in self.__dict__ and not hasattr( + self, optional_tensor_attribute_name + ): + setattr(self, optional_tensor_attribute_name, None) + + +def _dispatch__torch_function__(cls, func, types, args=(), kwargs=None): + """Use this util function for a common `__torch_function__` implementation + that dispatches to ops/functions registered with `_implements` + + class MyTensor(torch.Tensor): + ... + __torch_function__ = classmethod(_dispatch__torch_function__) + """ + kwargs = {} if kwargs is None else kwargs + if ( + hasattr(cls, "_TORCH_FN_TABLE") + and cls in cls._TORCH_FN_TABLE + and func in cls._TORCH_FN_TABLE[cls] + ): + return cls._TORCH_FN_TABLE[cls][func](func, types, args, kwargs) + with torch._C.DisableTorchFunctionSubclass(): + return func(*args, **kwargs) + + +def _dispatch__torch_dispatch__(cls, func, types, args, kwargs): + """Use this util function for a common `__torch_dispatch__` implementation + that dispatches to ops/functions registered with `_implements` + + class MyTensor(torch.Tensor): + ... + __torch_dispatch__ = classmethod(_dispatch__torch_dispatch__) + """ + if ( + hasattr(cls, "_ATEN_OP_TABLE") + and cls in cls._ATEN_OP_TABLE + and func in cls._ATEN_OP_TABLE[cls] + ): + return cls._ATEN_OP_TABLE[cls][func](func, types, args, kwargs) + + arg_types = tuple(type(arg) for arg in args) + kwarg_types = {k: type(arg) for k, arg in kwargs.items()} + raise NotImplementedError( + f"{cls.__name__} dispatch: attempting to run unimplemented operator/function: {func=}, {types=}, {arg_types=}, {kwarg_types=}" + ) + + +def _register_layout(tensor_class: Callable, layout_class: Callable): + """ + .. deprecated:: 0.15.1 + This method is deprecated as of version 0.15.1 since it's + part of the older tensor subclass development stack, + for information about new dev stack, please check + https://docs.pytorch.org/ao/main/quantization_overview.html + and https://docs.pytorch.org/ao/main/contributor_guide.html + + Helper function for layout registrations, this is used to implement + register_layout decorator for each tensor subclass, see aqt.py for example usage + + Args: + tensor_class: Tensor subclass type + layout_class: the class type of subclass of `Layout`, e.g. `PlainLayout` + + Returns: + a decorator that registers the tensor impl constructor in the table + """ + + # tensor_class._LAYOUT_CONSTRUCTOR_TABLE is a map from layout_class like TensorCoreTiledLayout + # to tensor_impl class constructor like TensorCoreTiledAQTTensorImpl.from_plain that can construct a tensor_impl + # from plain data like (quantized, unpacked) `data`, `scale`, `zero_point` + if not hasattr(tensor_class, "_LAYOUT_CONSTRUCTOR_TABLE"): + tensor_class._LAYOUT_CONSTRUCTOR_TABLE = {} + + def decorator(tensor_impl_class): + tensor_class._LAYOUT_CONSTRUCTOR_TABLE[layout_class] = ( + tensor_impl_class.from_plain + ) + # Allow serialization to work for models uses this tensor impl subclass + torch.serialization.add_safe_globals([layout_class, tensor_impl_class]) + return tensor_impl_class + + return decorator + + +def _get_tensor_impl_constructor( + tensor_class: Callable, layout_class: Callable +) -> Callable: + """ + .. deprecated:: 0.15.1 + This method is deprecated as of version 0.15.1 since it's + part of the older tensor subclass development stack, + for information about new dev stack, please check + https://docs.pytorch.org/ao/main/quantization_overview.html + and https://docs.pytorch.org/ao/main/contributor_guide.html + + Get TensorImpl class constructor (TensorImplClass.from_plain) for `tensor_class` based on `layout_class` + `layout_class` means the class type of subclass of `Layout`, e.g. `PlainLayout` + + Args: + tensor_class: Tensor subclass type + layout_class: the class type of subclass of `Layout`, e.g. `PlainLayout` + + Returns: + tensor impl subclass constructor for the layout_class + """ + if not hasattr(tensor_class, "_LAYOUT_CONSTRUCTOR_TABLE"): + raise ValueError( + f"no registered tensor_impl class constructor for: {tensor_class}" + ) + if layout_class not in tensor_class._LAYOUT_CONSTRUCTOR_TABLE: + raise ValueError( + f"layout_name: {layout_class} is not supported yet for {tensor_class}" + ) + + return tensor_class._LAYOUT_CONSTRUCTOR_TABLE[layout_class] + + +def _get_to_kwargs(self, *args, **kwargs): + """Helper function to get the device and dtype keyword args for `aten._to_copy.default` op + only device and dtype are kept + + Returns: {"device": device, "dtype": dtype} + """ + # `torch._C._nn._parse_to` can't handle `layout` argument + args = tuple(arg for arg in args if not isinstance(arg, torch.layout)) + if "layout" in kwargs: + kwargs.pop("layout") + # ignoring `non_blocking` and `memory_format` args since these are not + # very useful for most of the tensor subclasses + # if in the future there are use cases that need these, we'd recommend + # to override `_get_to_kwargs` and return these args + device, dtype, _, _ = torch._C._nn._parse_to(*args, **kwargs) + device = self.device if device is None else device + dtype = self.dtype if dtype is None else dtype + kwargs = { + "device": device, + "dtype": dtype, + } + return kwargs + + +class TorchAOBaseTensor(torch.Tensor): + r"""A util tensor subclass that provides commonly used functions + new tensor subclass can inherit to get all the utility functions + + Attributes (defined by subclass of ``TorchAOBaseTensor``): + + * :attr:`tensor_data_names` (List[str]): list of names of all required tensor_data, order should match + the `__init__` list of tensor subclass (optional to define to use ``TorchAOBaseTensor``, + required for getting the util functions been defined (see Note section)) + + * :attr:`tensor_attribute_names` (List[str]): list of names of non-``Tensor`` attributes, + order should match the ``__init__`` list of tensor subclass, following all the ``tensor_data_names`` arguments (optional to define to use ``TorchAOBaseTensor``, required for getting the + util functions been defined (see Note section)) + + * :attr:`optional_tensor_data_names` (List[str]): it's not required to get the + additional util functions been implemented, but this will be need if there are + some optional ``Tensor`` data attributes, when defined, this will be a list of names of ``Tensor``s that + can be optional + + * :attr:`optional_tensor_attribute_names` (List[str]): it's not required to get the + additional util functions been implemented, but this will be need if there are + some optional non-``Tensor`` attributes, when defined, this will be a list of names of attributes + that can be optional + + Note: + **Argument Order** + + Argument order in ``__init__`` and ``__new__`` of subclass of ``TorchAOBaseTensor`` should match exaclty with ``tensor_data_names`` + ``tensor_attribute_names`` + ``optional_tensor_data_names`` (if present) + ``optional_tensor_attribute_names`` (if present) + + + Note: + **How to Get Predefined Util Functions** + + If ``tensor_data_names`` (torch.Tensor data attribute names) and ``tensor_attribute_names`` (non-torch.Tensor attribute names) are defined, there are some additional util + functions that will be added, this includes: + + ``__tensor_flatten__``: flattens a subclassed tensor instance, returns a ``tuple``, first element is tensor data names for valid tensor data, second element is a dict from attribute_name to non-``Tensor`` attributes + + ``__tensor_unflatten__``: takes a ``tensor_data_dict`` (a map from tensor name to ``Tensor``), and list of non-``Tensor`` attributes, returns a new instance of the subclassed tensor + + ``_apply_fn_to_data``: takes a function (``Tensor -> Tensor``), applies function to all tensor data and recreate a new subclassed Tensor with the transformed tensor data + + ``__repr__``: the string representation of the subclassed tensor instance + + ``_same_metadata``: returns whether the metadata is the same between two instances of cls + + ``__setstate__``: when loading a serialized tensor subclass checkpoints, it sets the new optional tensor and tensor attribute that is saved in the old checkpoint to None, to maintain BC of old checkpoints when we add new optional tensor data or attributes to the tensor subclass + + torch function supported (``__torch_function__``): ``torch.Tensor.contiguous`` + + aten ops supported (``__torch_dispatch__``): ``aten.detach.default``, ``aten.clone.default``, ``aten.alias,default``, ``aten.contiguous.default``, ``aten.copy_.default``, ``aten._to_copy.default`` (enables ``t.to``) + + Note: + **Subclassing and Op Inheritance** + + Subclasses of ``TorchAOBaseTensor`` automatically inherit aten op (``__torch_dispatch__``) + and torch function (``__torch_function__``) implementations from their parent classes. + Each subclass gets its own independent dispatch tables, so registering a new op on a child + does not affect the parent, and vice versa. + + A child class can override an inherited op by registering its own implementation with + ``@ChildClass.implements(...)``. If no override is provided, the parent's implementation + is used automatically. + + For multiple inheritance (e.g., ``class C(B, A)``), ops are inherited from all parents + following Python's MRO (Method Resolution Order), with later bases taking priority. + + Example:: + + class Parent(TorchAOBaseTensor): + tensor_data_names = ["qdata"] + tensor_attribute_names = ["attr"] + + def __new__(cls, qdata, attr): + r = torch.Tensor._make_wrapper_subclass(cls, qdata.shape) + r.qdata = qdata + r.attr = attr + return r + + def __init__(self, qdata, attr): + pass + + @Parent.implements([torch.ops.aten.cat.default]) + def parent_cat(func, types, args, kwargs): + # parent implementation + ... + + # Child inherits Parent's aten.cat implementation automatically + class Child(Parent): + tensor_data_names = ["qdata"] + tensor_attribute_names = ["attr"] + + # Optionally override an inherited op: + @Child.implements([torch.ops.aten.cat.default]) + def child_cat(func, types, args, kwargs): + # child-specific implementation + ... + + Note: + **Safetensors Support** + + ``TorchAOBaseTensor`` subclasses can be serialized to and loaded from the + `safetensors `_ format. Since safetensors + only stores plain ``torch.Tensor`` objects, the serialization layer (in + ``torchao.prototype.safetensors``) decomposes each tensor subclass into its + constituent plain tensors (from ``tensor_data_names``/``optional_tensor_data_names``) + plus JSON metadata (from ``tensor_attribute_names``/``optional_tensor_attribute_names``), + and reconstructs the subclass on load. + + To add safetensors support for a new ``TorchAOBaseTensor`` subclass: + + 1. Define ``tensor_data_names``, ``tensor_attribute_names`` (and optionally + ``optional_tensor_data_names``, ``optional_tensor_attribute_names``) on the subclass, + which is already required for the other utility functions above. + + 2. Register the subclass in ``torchao/prototype/safetensors/safetensors_utils.py``: + + - Add the class name string to ``ALLOWED_TENSORS_SUBCLASSES``. + - Add a ``"ClassName": ClassName`` entry to ``ALLOWED_CLASSES``. + - If the subclass has non-Tensor attributes with custom types (dataclasses, enums, + named tuples), add those types to ``ALLOWED_CLASSES`` as well. + + Once registered, Hugging Face Transformers users can use ``save_pretrained`` and + ``push_to_hub`` with the default ``safe_serialization=True`` option. See + https://docs.pytorch.org/ao/main/eager_tutorials/torchao_hf_integration.html#saving-the-model + for a full end-to-end example. + + Examples:: + + class MyTensor(TorchAOBaseTensor): + tensor_data_names = ["a", "b"] + tensor_attribute_names = ["c", "d"] + optional_tensor_data_names = ["e", "f"] + optional_tensor_attribute_names = ["g", "h"] + + + def __new__( + cls, + a: Tensor, + b: Tensor, + c: int, + d: str, + e: Optional[Tensor] = None, + f: Optional[Tensor] = None, + g: Optional[int] = None, + h: Optional[int] = None, + ): + pass + + def __init__( + self, + a: Tensor, + b: Tensor, + c: int, + d: str, + e: Optional[Tensor] = None, + f: Optional[Tensor] = None, + g: Optional[int] = None, + h: Optional[int] = None, + ): + pass + + """ + + @classmethod + def __init_subclass__(cls, **kwargs): + if "_ATEN_OP_TABLE" not in cls.__dict__: + cls._ATEN_OP_TABLE = {} + if "_TORCH_FN_TABLE" not in cls.__dict__: + cls._TORCH_FN_TABLE = {} + if cls not in cls._ATEN_OP_TABLE: + cls._ATEN_OP_TABLE[cls] = {} + if cls not in cls._TORCH_FN_TABLE: + cls._TORCH_FN_TABLE[cls] = {} + + # define the common ops and __set_state__ for BC + # if the tensor_data_names and tensor_attribute_names are defined + if hasattr(cls, "tensor_data_names") and hasattr(cls, "tensor_attribute_names"): + cls._implements_common_tensor_ops() + cls.__setstate__ = _torchao_base_tensor__setstate__ + + # inherit the torch function and dispatch implementations from direct parent classes + # e.g. for `class C(B, A)`, C.__bases__ == (B, A) + for parent in cls.__bases__: + parent_aten_table = getattr(parent, "_ATEN_OP_TABLE", None) + if parent_aten_table and parent in parent_aten_table: + # shallow-copy parent's per-class op mapping into child's per-class mapping + cls._ATEN_OP_TABLE[cls].update(parent_aten_table[parent]) + + parent_torch_table = getattr(parent, "_TORCH_FN_TABLE", None) + if parent_torch_table and parent in parent_torch_table: + cls._TORCH_FN_TABLE[cls].update(parent_torch_table[parent]) + + implements = classmethod(_implements) + implements_torch_function = classmethod(_implements_torch_function) + _implements_common_tensor_ops = classmethod(_implements_common_tensor_ops) + __torch_dispatch__ = classmethod(_dispatch__torch_dispatch__) + __torch_function__ = classmethod(_dispatch__torch_function__) + _get_to_kwargs = _get_to_kwargs + + # deprecated, will be removed later + register_layout = classmethod(_register_layout) + get_tensor_impl_constructor = classmethod(_get_tensor_impl_constructor) + + def __init__(self, *args, **kwargs): + torch._C._log_api_usage_once(str(type(self))) + + def __tensor_flatten__(self): + if hasattr(self, "tensor_data_names") and hasattr( + self, "tensor_attribute_names" + ): + tensor_data_names = self.tensor_data_names.copy() + if hasattr(self, "optional_tensor_data_names"): + for tensor_data_name in self.optional_tensor_data_names: + maybe_tensor = getattr(self, tensor_data_name) + if maybe_tensor is not None: + tensor_data_names.append(tensor_data_name) + + attr_dict = { + attr: getattr(self, attr) for attr in self.tensor_attribute_names + } + if hasattr(self, "optional_tensor_attribute_names"): + attr_dict = attr_dict | { + attr: getattr(self, attr) + for attr in self.optional_tensor_attribute_names + } + + return tensor_data_names, attr_dict + + raise NotImplementedError( + "Subclasses should implement __tensor_flatten__ or specify `tensor_data_names` and `tensor_attribute_names` for tensor class before using it" + ) + + @classmethod + def __tensor_unflatten__( + cls, tensor_data_dict, tensor_attributes, outer_size, outer_stride + ): + if hasattr(cls, "tensor_data_names") and hasattr(cls, "tensor_attribute_names"): + required_tensors = [ + tensor_data_dict[name] for name in cls.tensor_data_names + ] + optional_tensor_dict = {} + if hasattr(cls, "optional_tensor_data_names"): + optional_tensor_dict = { + tensor_data_name: tensor_data_dict.get(tensor_data_name, None) + for tensor_data_name in cls.optional_tensor_data_names + } + + required_attributes = [ + tensor_attributes[name] for name in cls.tensor_attribute_names + ] + optional_attribute_dict = {} + if hasattr(cls, "optional_tensor_attribute_names"): + optional_attribute_dict = { + name: tensor_attributes[name] + for name in cls.optional_tensor_attribute_names + } + + return cls( + *required_tensors, + *required_attributes, + **optional_tensor_dict, + **optional_attribute_dict, + ) + + raise NotImplementedError( + "Subclasses should implement __tensor_unflatten__ or specify `tensor_data_names` and `tensor_attribute_names` for tensor class before using it" + ) + + def _apply_fn_to_data(self, fn): + if hasattr(self, "tensor_data_names") and hasattr( + self, "tensor_attribute_names" + ): + required_tensors = [ + fn(getattr(self, attr)) for attr in self.tensor_data_names + ] + optional_tensor_dict = {} + if hasattr(self, "optional_tensor_data_names"): + for tensor_data_name in self.optional_tensor_data_names: + maybe_tensor = getattr(self, tensor_data_name) + if maybe_tensor is not None: + optional_tensor_dict[tensor_data_name] = fn(maybe_tensor) + else: + optional_tensor_dict[tensor_data_name] = None + + required_attributes = [ + getattr(self, attr) for attr in self.tensor_attribute_names + ] + optional_attribute_dict = {} + if hasattr(self, "optional_tensor_attribute_names"): + optional_attribute_dict = { + attr_name: getattr(self, attr_name) + for attr_name in self.optional_tensor_attribute_names + } + + return self.__class__( + *required_tensors, + *required_attributes, + **optional_tensor_dict, + **optional_attribute_dict, + ) + + raise NotImplementedError( + "Subclasses should implement _apply_fn_to_data or specify `tensor_data_names` and `tensor_attribute_names` for tensor class or tensor instance before using it" + ) + + def __repr__(self): + if hasattr(self, "tensor_data_names") and hasattr( + self, "tensor_attribute_names" + ): + repr_str = "" + # required tensor data + repr_str += f"{self.tensor_data_names[0]}={getattr(self, self.tensor_data_names[0])}" + for tensor_data_name in self.tensor_data_names[1:]: + repr_str += f", {tensor_data_name}={getattr(self, tensor_data_name)}" + + # required attributes + for tensor_attribute_name in self.tensor_attribute_names: + repr_str += ( + f", {tensor_attribute_name}={getattr(self, tensor_attribute_name)}" + ) + + # optional tensor data + if hasattr(self, "optional_tensor_data_names"): + for tensor_data_name in self.optional_tensor_data_names: + repr_str += ( + f", {tensor_data_name}={getattr(self, tensor_data_name)}" + ) + + # optional tensor attributes + if hasattr(self, "optional_tensor_attribute_names"): + for tensor_attribute_name in self.optional_tensor_attribute_names: + repr_str += f", {tensor_attribute_name}={getattr(self, tensor_attribute_name)}" + + return f"{self.__class__.__name__}({repr_str})" + + raise NotImplementedError( + "Subclasses must implement __repr__ or specify `tensor_data_names` and `tensor_attribute_names` for tensor class or tensor instance before using it" + ) + + def get_layout(self): + """ + .. deprecated:: 0.15.1 + This method is deprecated as of version 0.15.1 since it's + part of the older tensor subclass development stack, + for information about new dev stack, please check + https://docs.pytorch.org/ao/main/quantization_overview.html + and https://docs.pytorch.org/ao/main/contributor_guide.html + """ + if not hasattr(self, "_layout"): + return None + return self._layout + + +def fill_defaults(args, n, defaults_tail): + """ + __torch_dispatch__ doesn't guarantee the number of arguments you are + passed (e.g., defaulted arguments are not passed); but usually it is + convenient to pad out the arguments list with defaults. This function + helps you do that. + Args: + args: the list of positional arguments passed to __torch_dispatch__ + n: the number of arguments you are expecting to get + defaults_tail: default values for the arguments, starting from the + end of the list + Example: + >>> fill_defaults([1, 2, 3], 5, [3, 4, 5]) + [1, 2, 3, 4, 5] + >>> fill_defaults([1, 2, 3], 5, [None, None, None]) + [1, 2, 3, None, None]] + """ + if n - len(defaults_tail) > len(args): + raise RuntimeError("not enough defaults to fill arguments") + r = list(args) + for i in range(len(args), n): + r.append(defaults_tail[i - n + len(defaults_tail)]) + return r + + +# Supported AMD GPU Models and their LLVM gfx Codes: +# +# | AMD GPU Model | LLVM gfx Code | +# |---------------|------------------------| +# | Navi4 | gfx1200, gfx1201 | +# | MI300X | gfx940, gfx941, gfx942 | +# | MI350 | gfx950 | + + +def is_ROCM(): + return torch.cuda.is_available() and torch.version.hip is not None + + +def is_MI300(): + if is_ROCM(): + mxArchName = ["gfx940", "gfx941", "gfx942"] + archName = torch.cuda.get_device_properties(0).gcnArchName + for arch in mxArchName: + if arch in archName: + return True + return False + + +def is_MI350(): + if is_ROCM(): + archName = torch.cuda.get_device_properties(0).gcnArchName + if "gfx950" in archName: + return True + return False + + +def is_Navi4(): + if is_ROCM(): + archName = torch.cuda.get_device_properties(0).gcnArchName + if "gfx1200" or "gfx1201" in archName: + return True + return False + + +def is_sm_version(major: int, minor: int) -> bool: + """Check if the CUDA version is exactly major.minor""" + is_cuda = torch.cuda.is_available() and torch.version.cuda + return torch.cuda.get_device_capability() == (major, minor) if is_cuda else False + + +def is_sm_at_least_89(): + return ( + torch.cuda.is_available() + and torch.version.cuda + and torch.cuda.get_device_capability() >= (8, 9) + ) + + +def is_sm_at_least_90(): + return ( + torch.cuda.is_available() + and torch.version.cuda + and torch.cuda.get_device_capability() >= (9, 0) + ) + + +# TODO(future PR): rename to 8_9, 9_0, 10_0 instead of 89, 10, 100 +def is_sm_at_least_100(): + return ( + torch.cuda.is_available() + and torch.version.cuda + and torch.cuda.get_device_capability() >= (10, 0) + ) + + +def is_cuda_version_at_least(major: int, minor: int) -> bool: + if not torch.cuda.is_available(): + return False + cuda_version = torch.version.cuda + if cuda_version is None: + return False + cuda_major, cuda_minor = map(int, cuda_version.split(".")[:2]) + return (cuda_major, cuda_minor) >= (major, minor) + + +def check_cpu_version(device, version="2.6.0"): + if isinstance(device, torch.device): + device = device.type + return device == "cpu" and torch_version_at_least(version) + + +def check_xpu_version(device, version="2.8.0"): + if isinstance(device, torch.device): + device = device.type + return device == "xpu" and torch_version_at_least(version) + + +def ceil_div(a, b): + return (a + b - 1) // b + + +def round_up(a: int, b: int) -> int: + return ceil_div(a, b) * b + + +def is_package_at_least(package_name: str, min_version: str): + package_exists = importlib.util.find_spec(package_name) is not None + if not package_exists: + return False + + return version(package_name) >= min_version + + +def _is_mslk_available(): + has_mslk = importlib.util.find_spec("mslk") is not None or is_fbcode() + if not has_mslk: + return False + + import mslk # noqa: F401 + + return True + + +def _is_flashinfer_available(): + return ( + # flashinfer-python + importlib.util.find_spec("flashinfer") is not None + # apache-tvm-ffi + and importlib.util.find_spec("tvm_ffi") is not None + # nvidia-ml-py + and importlib.util.find_spec("pynvml") is not None + ) or is_fbcode() + + +class DummyModule(torch.nn.Module): + """This is used because the TorchAO quantization functions tend to operate on modules so to apply the transform to a tensor, we can load a + DummyModule with the target tensor and then apply the transformation to the module and then extract the transformed tensor. + """ + + def __init__(self, weight: torch.Tensor, bias: Optional[torch.Tensor] = None): + super().__init__() + self.weight = weight + self.bias = bias diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2d5dbf0667a022caa07ec30bb10db5b4f83159dd --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/__init__.py @@ -0,0 +1,10 @@ +"""torchgen + +This module contains codegeneration utilities for PyTorch. It is used to +build PyTorch from source, but may also be used for out-of-tree projects +that extend PyTorch. + +Note well that we provide no BC guarantees for torchgen. If you're interested +in using torchgen and want the PyTorch team to be aware, please reach out +on GitHub. +""" diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/code_template.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/code_template.py new file mode 100644 index 0000000000000000000000000000000000000000..bafe1fa7568ec2b0625e23407cc3d815aaf29838 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/code_template.py @@ -0,0 +1,108 @@ +from __future__ import annotations + +import itertools +import re +import textwrap +from typing import TYPE_CHECKING + + +if TYPE_CHECKING: + from collections.abc import Mapping, Sequence + + +# match $identifier or ${identifier} and replace with value in env +# If this identifier is at the beginning of whitespace on a line +# and its value is a list then it is treated as +# block substitution by indenting to that depth and putting each element +# of the list on its own line +# if the identifier is on a line starting with non-whitespace and a list +# then it is comma separated ${,foo} will insert a comma before the list +# if this list is not empty and ${foo,} will insert one after. + + +class CodeTemplate: + substitution_str = r"(^[^\n\S]*)?\$([^\d\W]\w*|\{,?[^\d\W]\w*\,?})" + substitution = re.compile(substitution_str, re.MULTILINE) + + pattern: str + filename: str + + @staticmethod + def from_file(filename: str) -> CodeTemplate: + with open(filename) as f: + return CodeTemplate(f.read(), filename) + + def __init__(self, pattern: str, filename: str = "") -> None: + self.pattern = pattern + self.filename = filename + + def substitute( + self, env: Mapping[str, object] | None = None, **kwargs: object + ) -> str: + if env is None: + env = {} + + def lookup(v: str) -> object: + assert env is not None + return kwargs[v] if v in kwargs else env[v] + + def indent_lines(indent: str, v: Sequence[object]) -> str: + content = "\n".join( + itertools.chain.from_iterable(str(e).splitlines() for e in v) + ) + content = textwrap.indent(content, prefix=indent) + # Remove trailing whitespace on each line + return "\n".join(map(str.rstrip, content.splitlines())).rstrip() + + def replace(match: re.Match[str]) -> str: + indent = match.group(1) + key = match.group(2) + comma_before = "" + comma_after = "" + if key[0] == "{": + key = key[1:-1] + if key[0] == ",": + comma_before = ", " + key = key[1:] + if key[-1] == ",": + comma_after = ", " + key = key[:-1] + v = lookup(key) + if indent is not None: + if not isinstance(v, list): + v = [v] + return indent_lines(indent, v) + elif isinstance(v, list): + middle = ", ".join([str(x) for x in v]) + if len(v) == 0: + return middle + return comma_before + middle + comma_after + else: + return str(v) + + return self.substitution.sub(replace, self.pattern) + + +if __name__ == "__main__": + c = CodeTemplate( + """\ + int foo($args) { + + $bar + $bar + $a+$b + } + int commatest(int a${,stuff}) + int notest(int a${,empty,}) + """ + ) + print( + c.substitute( + args=["hi", 8], + bar=["what", 7], + a=3, + b=4, + stuff=["things...", "others"], + empty=[], + ) + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/context.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/context.py new file mode 100644 index 0000000000000000000000000000000000000000..a482a59eeb707750242554fdbddf5250d95c3bcc --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/context.py @@ -0,0 +1,134 @@ +from __future__ import annotations + +import contextlib +import functools +from typing import Any, Callable, Optional, TYPE_CHECKING, TypeVar, Union + +import torchgen.local as local +from torchgen.model import ( + BackendIndex, + DispatchKey, + NativeFunction, + NativeFunctionsGroup, + NativeFunctionsViewGroup, +) +from torchgen.utils import context, S, T + + +if TYPE_CHECKING: + from collections.abc import Iterator + + +# Helper functions for defining generators on things in the model + +F = TypeVar( + "F", + NativeFunction, + NativeFunctionsGroup, + NativeFunctionsViewGroup, + Union[NativeFunction, NativeFunctionsGroup], + Union[NativeFunction, NativeFunctionsViewGroup], +) + +F2 = TypeVar( + "F2", + NativeFunction, + NativeFunctionsGroup, + Optional[NativeFunction], + bool, + str, +) + +F3 = TypeVar("F3", tuple[NativeFunction, Any], list[NativeFunction]) + + +@contextlib.contextmanager +def native_function_manager( + g: NativeFunctionsGroup | NativeFunctionsViewGroup | NativeFunction, +) -> Iterator[None]: + if isinstance(g, NativeFunctionsGroup): + # By default, we associate all errors with structured native functions + # with the out variant. In some cases, it might be better to have + # a more specific place to hang things; if so, use + # native_function_manager again on the inside + f = g.out + elif isinstance(g, NativeFunctionsViewGroup): + # We associate errors with the view operator + f = g.view + else: + f = g + with context(lambda: f"in native_functions.yaml line {f.loc}:\n {f.func}"): + with local.parametrize( + use_const_ref_for_mutable_tensors=f.use_const_ref_for_mutable_tensors, + use_ilistref_for_tensor_lists=f.part_of_structured_group, + ): + yield + + +# Given a function that operates on NativeFunction, wrap it into a new function +# that sets some appropriate context managers for that native function. +# YOU MUST WRAP FUNCTIONS IN THIS for calls to api modules to be sound +# (you will get an error if we try to access the local variables without having +# set them). +def with_native_function(func: Callable[[F], T]) -> Callable[[F], T]: + @functools.wraps(func) + def wrapper(f: F) -> T: + with native_function_manager(f): + return func(f) + + return wrapper + + +def with_native_function_and(func: Callable[[F, F2], T]) -> Callable[[F, F2], T]: + @functools.wraps(func) + def wrapper(f: F, f2: F2) -> T: + # The first native_function is assumed to be the one with the appropriate context. + with native_function_manager(f): + return func(f, f2) + + return wrapper + + +def method_with_native_function(func: Callable[[S, F], T]) -> Callable[[S, F], T]: + @functools.wraps(func) + def wrapper(slf: S, f: F) -> T: + with native_function_manager(f): + return func(slf, f) + + return wrapper + + +def method_with_nested_native_function( + func: Callable[[S, F3], T], +) -> Callable[[S, F3], T]: + @functools.wraps(func) + def wrapper(slf: S, f: F3) -> T: + with native_function_manager(f[0]): + return func(slf, f) + + return wrapper + + +# Convenience decorator for functions that explicitly take in a BackendIndex, +# instead of indirectly taking one in as a closure +def with_native_function_and_index( + func: Callable[[F, BackendIndex], T], +) -> Callable[[F, BackendIndex], T]: + @functools.wraps(func) + def wrapper(f: F, backend_index: BackendIndex) -> T: + with native_function_manager(f): + return func(f, backend_index) + + return wrapper + + +# Convenience decorator for functions that explicitly take in a Dict of BackendIndices +def with_native_function_and_indices( + func: Callable[[F, dict[DispatchKey, BackendIndex]], T], +) -> Callable[[F, dict[DispatchKey, BackendIndex]], T]: + @functools.wraps(func) + def wrapper(f: F, backend_indices: dict[DispatchKey, BackendIndex]) -> T: + with native_function_manager(f): + return func(f, backend_indices) + + return wrapper diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/gen.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/gen.py new file mode 100644 index 0000000000000000000000000000000000000000..e5186620e8a4739bbeb1aede783e8d2b1fc55ee2 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/gen.py @@ -0,0 +1,3003 @@ +from __future__ import annotations + +import argparse +import functools +import json +import keyword +import os +from collections import defaultdict, namedtuple, OrderedDict +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Callable, Literal, TYPE_CHECKING, TypeVar +from typing_extensions import assert_never + +import yaml + +import torchgen.api.dispatcher as dispatcher +import torchgen.api.meta as meta +import torchgen.api.native as native +import torchgen.api.structured as structured +import torchgen.dest as dest +from torchgen.api import cpp +from torchgen.api.translate import translate +from torchgen.api.types import ( + Binding, + CppSignature, + CppSignatureGroup, + DispatcherSignature, + NamedCType, + NativeSignature, + SpecialArgName, +) +from torchgen.context import ( + method_with_native_function, + native_function_manager, + with_native_function, + with_native_function_and_indices, +) +from torchgen.gen_aoti_c_shim import ( + gen_aoti_c_shim_files, + gen_static_dispatch_backend_call_signature, +) +from torchgen.gen_functionalization_type import ( + gen_functionalization_definition, + gen_functionalization_registration, + gen_functionalization_view_inverse_declaration, + GenCompositeViewCopyKernel, +) +from torchgen.gen_vmap_plumbing import gen_all_vmap_plumbing +from torchgen.model import ( + Argument, + BackendIndex, + BackendMetadata, + BaseOperatorName, + DEFAULT_KERNEL_NAMESPACE, + dispatch_device_map, + DispatchKey, + FRAGMENT_NAMESPACES, + FunctionSchema, + is_cuda_dispatch_key, + is_generic_dispatch_key, + is_ufunc_dispatch_key, + is_xpu_dispatch_key, + Location, + NativeFunction, + NativeFunctionsGroup, + NativeFunctionsViewGroup, + OperatorName, + OptionalType, + SchemaKind, + SelfArgument, + STRUCTURED_DISPATCH_KEYS, + TensorOptionsArguments, + Type, + Variant, + ViewSchemaKind, +) +from torchgen.native_function_generation import ( + add_generated_native_functions, + gen_composite_functional_kernel, + gen_composite_out_kernel, + pre_group_native_functions, +) +from torchgen.selective_build.selector import SelectiveBuilder +from torchgen.utils import ( + concatMap, + context, + FileManager, + make_file_manager, + mapMaybe, + NamespaceHelper, + Target, +) +from torchgen.yaml_utils import YamlDumper, YamlLoader + + +if TYPE_CHECKING: + from collections.abc import Sequence + + +T = TypeVar("T") + +# Welcome to the ATen code generator v2! The ATen code generator is +# responsible for parsing native_functions.yaml and then generating +# various generated files (e.g., TypeDefault.cpp) based on the operators +# defined in this file. This means that the code generator knows how to +# parse function schema, and then translate this into various C++ types +# and boilerplate code. +# +# Some things to know about this file when you modify it: +# +# - This file has STRICT mypy typechecking. Typecheck it with +# `mypy --config mypy-strict.ini` in the root source directory +# +# - Most of the heavy lifting lives in external modules: +# - 'model' has the data model for native_functions.yaml. The classes +# in those file represent what you see when you look at +# a native_functions.yaml +# - 'api' has conversions for how to translate JIT schema into +# the various C++ APIs that the codegen interacts with. There +# are in fact THREE different C++ APIs: the public C++ API, +# the dispatcher API, and the legacy dispatcher API. See each +# of these respective files for more information + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# +# HELPER FUNCTIONS +# +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +# A custom loader for YAML to let us also keep track of line numbers +# of each entry in the YAML file +class LineLoader(YamlLoader): + def construct_mapping(self, node, deep=False): # type: ignore[no-untyped-def] + mapping = super().construct_mapping(node, deep=deep) # type: ignore[no-untyped-call] + # Add 1 so line numbering starts at 1 + mapping["__line__"] = node.start_mark.line + 1 + return mapping + + +# Parse native_functions.yaml into a sequence of NativeFunctions and Backend Indices. +ParsedYaml = namedtuple("ParsedYaml", ["native_functions", "backend_indices"]) + + +_GLOBAL_PARSE_NATIVE_YAML_CACHE: dict[str, ParsedYaml] = {} +_GLOBAL_PARSE_TAGS_YAML_CACHE: dict[str, set[str]] = {} + + +def file_manager_from_dispatch_key( + dispatch_key: DispatchKey, + device_fms: dict[str, FileManager], + default_fm: FileManager, +) -> FileManager: + fm = device_fms.get( + next( + ( + device + for check, device in dispatch_device_map.items() + if check(dispatch_key) + ), + "", + ), + default_fm, + ) + return fm + + +def parse_native_yaml_struct( + es: object, + valid_tags: set[str], + ignore_keys: set[DispatchKey] | None = None, + path: str = "", + skip_native_fns_gen: bool = False, +) -> ParsedYaml: + assert isinstance(es, list) + rs: list[NativeFunction] = [] + bs: dict[DispatchKey, dict[OperatorName, BackendMetadata]] = defaultdict(dict) + for e in es: + assert isinstance(e, dict), f"expected to be dict: {e}" + assert isinstance(e.get("__line__"), int), e + loc = Location(path, e["__line__"]) + funcs = e.get("func") + assert funcs is not None, f"missed 'func' in {e}" + with context(lambda: f"in {loc}:\n {funcs}"): + func, m = NativeFunction.from_yaml(e, loc, valid_tags, ignore_keys) + rs.append(func) + BackendIndex.grow_index(bs, m) + error_check_native_functions(rs) + # Default dict is to prevent the codegen from barfing when we have a dispatch key that has no kernels yet. + indices: dict[DispatchKey, BackendIndex] = defaultdict( + lambda: BackendIndex( + dispatch_key=DispatchKey.Undefined, + use_out_as_primary=True, + external=False, + device_guard=False, + # I'm actually not sure about this; undefined could be hit on + # empty TensorList, hypothetically that could have sizes in it + index={}, + ) + ) + if not skip_native_fns_gen: + add_generated_native_functions(rs, bs) + for k, v in bs.items(): + # All structured in-tree operators are implemented in terms of their out operator. + indices[k] = BackendIndex( + dispatch_key=k, + use_out_as_primary=True, + external=False, + # Only cuda-like devices in tree require device guards + device_guard=is_cuda_dispatch_key(k) or is_xpu_dispatch_key(k), + index=v, + ) + return ParsedYaml(rs, indices) + + +def parse_tags_yaml_struct(es: object, path: str = "") -> set[str]: + assert isinstance(es, list) + rs: set[str] = set() + for e in es: + assert isinstance(e.get("__line__"), int), e + loc = Location(path, e["__line__"]) + tags = e.get("tag") + with context(lambda: f"in {loc}:\n {tags}"): + e_i = e.copy() + name = e_i.pop("tag") + desc = e_i.pop("desc", "") + # ensure that each tag has a non-empty description + assert desc != "" + rs.add(name) + return rs + + +@functools.cache +def parse_tags_yaml(path: str) -> set[str]: + global _GLOBAL_PARSE_TAGS_YAML_CACHE + if path not in _GLOBAL_PARSE_TAGS_YAML_CACHE: + with open(path) as f: + es = yaml.load(f, Loader=LineLoader) + _GLOBAL_PARSE_TAGS_YAML_CACHE[path] = parse_tags_yaml_struct(es, path=path) + + return _GLOBAL_PARSE_TAGS_YAML_CACHE[path] + + +def parse_native_yaml( + path: str, + tags_yaml_path: str, + ignore_keys: set[DispatchKey] | None = None, + *, + skip_native_fns_gen: bool = False, + loaded_yaml: object | None = None, +) -> ParsedYaml: + global _GLOBAL_PARSE_NATIVE_YAML_CACHE + if path not in _GLOBAL_PARSE_NATIVE_YAML_CACHE: + valid_tags = parse_tags_yaml(tags_yaml_path) + + # if a loaded yaml is provided, use that instead of reading from path + if loaded_yaml is None: + with open(path) as f: + es = yaml.load(f, Loader=LineLoader) + else: + es = loaded_yaml + + _GLOBAL_PARSE_NATIVE_YAML_CACHE[path] = parse_native_yaml_struct( + es, + valid_tags, + ignore_keys, + path=path, + skip_native_fns_gen=skip_native_fns_gen, + ) + + return _GLOBAL_PARSE_NATIVE_YAML_CACHE[path] + + +# Some assertions are already performed during parsing, but those are only within a single NativeFunction. +# Assertions here are meant to be performed across NativeFunctions. +def error_check_native_functions(funcs: Sequence[NativeFunction]) -> None: + func_map: dict[OperatorName, NativeFunction] = {} + base_func_map: dict[BaseOperatorName, list[NativeFunction]] = defaultdict(list) + for f in funcs: + func_map[f.func.name] = f + base_func_map[f.func.name.name].append(f) + for f in funcs: + if f.structured_delegate is not None: + delegate_func = func_map.get(f.structured_delegate) + assert delegate_func is not None, ( + f"{f.func.name} is marked as a structured_delegate pointing to " + f"{f.structured_delegate}, but {f.structured_delegate} is missing." + ) + assert delegate_func.structured, ( + f"{f.func.name} is marked as a structured_delegate pointing to " + f"{f.structured_delegate}, but {f.structured_delegate} is not marked as structured. " + f"Consider adding 'structured=True' to the delegated operator" + ) + + # Check for reserved Python keywords + PYTHON_RESERVED_KEYWORDS = set(keyword.kwlist) + # List of pre-existing operators that are known to have reserved keywords + # Exclusion list is used to suppress the assertion for these operators + EXCLUSION_LIST = { + ("_has_compatible_shallow_copy_type", "from"), + ("random_.from", "from"), + ("uniform_", "from"), + } + + for arg in f.func.arguments.flat_all: + if arg.name in PYTHON_RESERVED_KEYWORDS: + if (str(f.func.name), arg.name) not in EXCLUSION_LIST: + raise AssertionError( + f"Argument name '{arg.name}' in function '{f.func.name}' is a reserved Python keyword." + ) + # See Note [resize_ in Functionalization] + # resize_() is technically an inplace view op (and therefore needs the tag), + # but it would be overkill to add a true "view" variant of resize. + # Instead, resize_() gets special treatment in functionalization, + # and we have a resize() op that is non-aliasing + functional. + if ( + "inplace_view" in f.tags + and str(f.func.name) != "resize_" + and str(f.func.name) != "resize_as_" + and str(f.func.name.name) != "set_" + ): + base_name = f.func.name.name + assert base_name.inplace, ( + f"{f.func.name} is marked with tag: inplace_view, but it doesn't follow the naming " + "convention for inplace ops - the codegen expects the base name to have a trailing underscore. " + ) + out_of_place_base_name = BaseOperatorName( + base_name.base, False, base_name.dunder_method + ) + assert len(base_func_map[out_of_place_base_name]) > 0, ( + f"{f.func.name} is marked with tag: inplace_view. The codegen expects there to be a corresponding " + f"out-of-place view op with the name '{base_name}' and matching schema, but it didn't find one. " + ) + + +def cpp_string(s: str) -> str: + """Convert a python string into a c++ string literal""" + s = s.replace("\\", "\\\\") + s = s.replace('"', '\\"') + s = s.replace("\a", "\\a") + s = s.replace("\b", "\\b") + s = s.replace("\f", "\\f") + s = s.replace("\n", "\\n") + s = s.replace("\v", "\\v") + s = s.replace("\t", "\\t") + return f'"{s}"' + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# +# C++ CODE GENERATION +# +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + +# Most functions in this section are curried: they consist of a function +# that takes some parameters (e.g., what is to be generated) which itself +# returns a function that actually maps NativeFunction to the code +# to be generated. This pattern makes it convenient to use map, concatMap +# and similar functional combinators. + + +def static_dispatch_keys(backends: list[BackendIndex]) -> list[DispatchKey]: + if len(backends) == 0: + return [] + else: + return [backend.dispatch_key for backend in backends] + [ + DispatchKey.CompositeImplicitAutograd, + DispatchKey.CompositeImplicitAutogradNestedTensor, + DispatchKey.CompositeExplicitAutograd, + DispatchKey.CompositeExplicitAutogradNonFunctional, + ] + + +def get_static_dispatch_backend( + f: NativeFunction, backend_index: BackendIndex +) -> DispatchKey | None: + if f.structured_delegate is not None or backend_index.has_kernel(f): + # TODO: for ops with structured_delegate it should check the dispatch table of + # the out variant instead. For now, these structured ops all have CPU/CUDA kernels + # so we always dispatch to the `backend`, but this could be wrong when we + # migrate math/default_backend ops to use structured delegate. + return backend_index.dispatch_key + elif f.has_composite_explicit_autograd_kernel: + return DispatchKey.CompositeExplicitAutograd + elif f.has_composite_explicit_autograd_non_functional_kernel: + return DispatchKey.CompositeExplicitAutogradNonFunctional + elif f.has_composite_implicit_autograd_kernel: + return DispatchKey.CompositeImplicitAutograd + elif f.has_composite_implicit_autograd_nested_tensor_kernel: + return DispatchKey.CompositeImplicitAutogradNestedTensor + return None + + +def static_dispatch_ops_header( + f: NativeFunction, backend_index: list[BackendIndex] +) -> str | None: + if backend_index is None or f.manual_kernel_registration: + return None + + output = [] + for index in backend_index: + dispatch_key = get_static_dispatch_backend(f, index) + if dispatch_key is not None: + output.append( + f"#include " + ) + return "\n".join(output) + + +def static_dispatch_extra_headers(backends: list[BackendIndex]) -> list[str]: + return [ + f"#include " + for dispatch_key in static_dispatch_keys(backends) + ] + + +# Translates arguments of `sig` to CppSignature bindings. +# Note that we have a special case for `memory_format` argument and this case is not covered by +# tools.codegen.api.translate() yet as its application is limited to static dispatch. +def translate_args( + sig: CppSignature | DispatcherSignature, + cpp_sig: CppSignature, +) -> str: + # Adds SpecialArgName.possibly_redundant_memory_format NamedCType for memory_format bindings + def add_spl_memory_format_binding(input_bindings: list[Binding]) -> list[Binding]: + output_bindings: list[Binding] = [] + for binding in input_bindings: + if binding.name == "memory_format": + spl_mem_format_binding = Binding( + nctype=NamedCType( + SpecialArgName.possibly_redundant_memory_format, + binding.nctype.type, + ), + name=binding.name, + default=binding.default, + argument=binding.argument, + ) + output_bindings.append(spl_mem_format_binding) + else: + output_bindings.append(binding) + return output_bindings + + src_bindings = list(sig.arguments()) + goal_bindings = list(cpp_sig.arguments()) + # When last argument of CPP signature has SpecialArgName.possibly_redundant_memory_format NCType, + # get memory_format bindings of dispatcher signature to have the same NCType as well + for arg in goal_bindings: + if arg.nctype.name == SpecialArgName.possibly_redundant_memory_format: + src_bindings = add_spl_memory_format_binding(src_bindings) + break + exprs = translate(src_bindings, goal_bindings) + return ", ".join(a.expr for a in exprs) + + +def generate_static_dispatch_backend_call( + sig: CppSignature | DispatcherSignature, + f: NativeFunction, + backend_index: BackendIndex, +) -> str: + cpp_sig = gen_static_dispatch_backend_call_signature(sig, f) + name = cpp_sig.name() + exprs = translate_args(sig, cpp_sig) + backend_metadata = backend_index.get_kernel(f) + kernel_ns = ( + backend_metadata.cpp_namespace + if backend_metadata and backend_metadata.cpp_namespace + else DEFAULT_KERNEL_NAMESPACE + ) + ns = kernel_ns.replace("::native", "") + return f"return {ns}::{backend_index.dispatch_key.lower()}::{name}({exprs});" + + +def generate_static_dispatch_fallback_call( + sig: CppSignature | DispatcherSignature, + f: NativeFunction, + backend_indices: list[BackendIndex], +) -> str: + cpp_sigs = CppSignatureGroup.from_native_function( + f, method=False, fallback_binding=False + ) + if sig.symint and f.func.has_symint(): + cpp_sig = cpp_sigs.symint_signature + else: + cpp_sig = cpp_sigs.signature + assert cpp_sig is not None + name = cpp_sig.name() + exprs = translate_args(sig, cpp_sig) + ns = DEFAULT_KERNEL_NAMESPACE.replace("::native", "") + if f.has_composite_explicit_autograd_kernel: + return f"return {ns}::{DispatchKey.CompositeExplicitAutograd.lower()}::{name}({exprs});" + elif f.has_composite_explicit_autograd_non_functional_kernel: + return f"return {ns}::{DispatchKey.CompositeExplicitAutogradNonFunctional.lower()}::{name}({exprs});" + elif f.has_composite_implicit_autograd_kernel: + return f"return {ns}::{DispatchKey.CompositeImplicitAutograd.lower()}::{name}({exprs});" + elif f.has_composite_implicit_autograd_nested_tensor_kernel: + return f"return {ns}::{DispatchKey.CompositeImplicitAutogradNestedTensor.lower()}::{name}({exprs});" + else: + return f"""TORCH_CHECK(false, "Static dispatch does not support {name} for\ +{", ".join([str(index.dispatch_key) for index in backend_indices])} ");""" + + +def static_dispatch( + sig: CppSignature | DispatcherSignature, + f: NativeFunction, + backend_indices: list[BackendIndex], +) -> str: + """ + For a given `NativeFunction`, find out the corresponding backend and dispatch to it. If more than one + backends exist, fallback to static dispatch by determining dispatch key from inputs. + Arguments: + sig: A CppSignature or DispatcherSignature for this native function we want to use. + f: NativeFunction to generate static dispatch. + backend_indices: All available backends. + Return: + C++ code to call backend-specific functions, e.g., "return at::cpu::add(self, other, scale);" + """ + if len(backend_indices) == 0 or f.manual_kernel_registration: + return "" + + keys = [ + b + for b in backend_indices + if b.has_kernel(f) + or ( + f.structured_delegate is not None + and b.dispatch_key in STRUCTURED_DISPATCH_KEYS + ) + ] + if len(keys) == 1: + return generate_static_dispatch_backend_call(sig, f, keys[0]) + elif len(keys) == 0: + return generate_static_dispatch_fallback_call(sig, f, backend_indices) + + native_tensor_args = [ + a.name + for a in sig.arguments() + if isinstance(a.argument, SelfArgument) + or isinstance(a.argument, Argument) + and a.argument.type.is_tensor_like() + ] + tensor_args = ", ".join(native_tensor_args) + tensor_opts = f.func.arguments.tensor_options + + stmts = [] + subexprs: list[str] = [] + if tensor_opts is not None: + subexprs.append( + "DispatchKeySet(c10::computeDispatchKey(dtype, layout, device))" + ) + if tensor_args != "": + subexprs.append(f"c10::detail::multi_dispatch_key_set({tensor_args})") + stmts.append(f"""DispatchKeySet _dk_set = {" | ".join(subexprs)};""") + stmts.append("DispatchKey _dk = c10::highestPriorityBackendTypeId(_dk_set);") + + dispatch_code = [] + for index in keys: + dispatch_code.append(f"""case DispatchKey::{index.dispatch_key}:""") + dispatch_code.append( + f"""\t{generate_static_dispatch_backend_call(sig, f, index)};""" + ) + + fallback = generate_static_dispatch_fallback_call(sig, f, backend_indices) + connector = "\n\t\t" + + return f""" + {connector.join(stmts)} + switch (_dk) {{ + {connector.join(dispatch_code)} + default: + {fallback} + }} + """ + + +# Generates RegisterSchema.cpp. Depending on the selector, either +# all schemas are registered, or only some are (in the case of +# selective build) +@dataclass(frozen=True) +class RegisterSchema: + selector: SelectiveBuilder + known_tags: dict[str, int] = field(default_factory=dict) + + @method_with_native_function + def __call__(self, f: NativeFunction) -> str | None: + if not self.selector.is_native_function_selected(f): + return None + tags = "{" + ", ".join(f"at::Tag::{tag}" for tag in sorted(f.tags)) + "}" + if tags == "{}": + return f"m.def({cpp_string(str(f.func))}, {{}});\n" + maybe_tags = "" + if tags not in self.known_tags: + idx = len(self.known_tags) + self.known_tags[tags] = idx + maybe_tags = f"const std::vector tags_{idx} = {tags};\n" + return f"{maybe_tags}m.def({cpp_string(str(f.func))}, tags_{self.known_tags[tags]});\n" + + +# Generates Operators.h and Operators.cpp. +# These provide macros that, given an operator and overload name, allow users +# to access an "un-overloaded" function version of the operator. This +# is useful for extension writers who want to (1) want to decltype the operator +# and (2) don't want to worry about method-only operators. +@dataclass(frozen=True) +class ComputeOperators: + target: Literal[Target.DECLARATION, Target.DEFINITION] + static_dispatch_backend_indices: list[BackendIndex] + + @method_with_native_function + def __call__(self, f: NativeFunction) -> str: + sig = DispatcherSignature.from_schema(f.func) + name = f.func.name.unambiguous_name() + + if self.target is Target.DECLARATION: + # Note [The ATen Operators API] + # The ATen Operators API lives in the at::_ops namespace, and contains compile-time + # metadata about each operator + entry points into the Dispatcher. + # The C++ function, method, and redispatch API's are all implemented as wrappers + # into various bits of the structs defined here. + # + # Important characteristics about the Operators API: + # (1) It follows the Dispatcher API. + # This is kind of necessary to avoid overhead. + # For example: if it followed the C++ API, then all of the faithful C++ factory functions + # would need to wrap their arguments into TensorOptions only to unwrap them again. + # (2) Overload names are disambiguated. + # This is helpful for pytorch extenders who would like to decltype() an aten operator, + # that has overloads, e.g. decltype(at::_ops::mul_Tensor::call) + # (3) No argument defaulting is allowed. + # This is more of an implementation detail to avoid #include cycles, + # since TensorBody.h (which defines the Tensor class) needs to include this file. + # (4) manual_cpp_bindings and faithful names are not included in the API. + # This applies to stuff like __dispatch__is_complex(), and add_outf(). + # These aren't "real aten ops", they're just additional functions provided by the C++ API. + # They're implemented as wrappers in Functions.h that call into the actual operators + # defined here, i.e. at::_ops::is_complex::call() and at::_ops::add_out::call(). + # This means that ATEN_OP(is_complex) will not fastpath, and will go through the dispatcher. + return f""" +struct TORCH_API {name} {{ + using schema = {sig.type()}; + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::{f.func.name.name}"; + static constexpr const char* overload_name = "{f.func.name.overload_name}"; + static constexpr const char* schema_str = {cpp_string(str(f.func))}; + static {sig.defn(name="call", is_redispatching_fn=False)}; + static {sig.defn(name="redispatch", is_redispatching_fn=True)}; +}};""" + + elif self.target is Target.DEFINITION: + defns = f""" +// aten::{f.func} +static C10_NOINLINE c10::TypedOperatorHandle<{name}::schema> create_{name}_typed_handle() {{ + return c10::Dispatcher::singleton() + .findSchemaOrThrow({name}::name, {name}::overload_name) + .typed<{name}::schema>(); +}} +""" + for is_redispatching_fn in [False, True]: + if is_redispatching_fn: + dispatcher_exprs_str = ", ".join( + ["dispatchKeySet"] + [a.name for a in sig.arguments()] + ) + method_base = "redispatch" + else: + dispatcher_exprs_str = ", ".join([a.name for a in sig.arguments()]) + method_base = "call" + + dispatcher_call = method_base + method_name = f"{name}::{method_base}" + + fn_body = f""" + static auto op = create_{name}_typed_handle(); + return op.{dispatcher_call}({dispatcher_exprs_str});""" + + if ( + not is_redispatching_fn + and len(self.static_dispatch_backend_indices) > 0 + ): + # call() should go through static dispatch + fn_body = static_dispatch( + sig, f, backend_indices=self.static_dispatch_backend_indices + ) + defns += f""" +// aten::{f.func} +{sig.defn(name=method_name, is_redispatching_fn=is_redispatching_fn)} {{ + {fn_body} +}} +""" + return defns + else: + assert_never(self.target) + + +# Generates Functions.h, which provides the functional public C++ API, +# and the scaffolding to call into the dispatcher from these functions. +@dataclass(frozen=True) +class ComputeFunction: + @method_with_native_function + def __call__(self, f: NativeFunction) -> str | None: + sig_group = CppSignatureGroup.from_native_function( + f, method=False, fallback_binding=f.manual_cpp_binding + ) + has_symint = f.func.has_symint() + + result = "" + for sig in sig_group.signatures(): + # See Note [The ATen Operators API] + target_sig = DispatcherSignature.from_schema(f.func) + exprs = translate(sig.arguments(), target_sig.arguments()) + exprs_str = ", ".join([e.expr for e in exprs]) + + if sig.symint: + intlike_t = "c10::SymInt" + else: + intlike_t = "int64_t" + + if Variant.function in f.variants: + result += f""" +// aten::{f.func} +inline {sig.decl()} {{ + return at::_ops::{f.func.name.unambiguous_name()}::call({exprs_str}); +}}""" + + # The template function can be used from template situations + # where you want to switch between the symint or not version + # depending on a template argument + # + # NB: we ALWAYS generate this even for methods. But we put it in + # this header so it can take advantage of per-op headers + if has_symint: + result += f""" +namespace symint {{ + template >> + {sig.decl(suppress_symint_suffix=True)} {{ + return at::_ops::{f.func.name.unambiguous_name()}::call({exprs_str}); + }} +}} +""" + return result + + +# Generates TensorBody.h. This file provides the object-oriented (method-based) +# public C++ API, and the scaffolding to call into the dispatcher from these functions. +@dataclass(frozen=True) +class ComputeTensorMethod: + target: Literal[Target.DECLARATION, Target.DEFINITION] + static_dispatch_backend_indices: list[BackendIndex] + + @method_with_native_function + def __call__(self, f: NativeFunction) -> str | None: + if Variant.method not in f.variants: + return None + + assert not f.func.is_out_fn() + assert f.func.arguments.self_arg is not None + + sig_group = CppSignatureGroup.from_native_function( + f, method=True, fallback_binding=f.manual_cpp_binding + ) + + if self.target is Target.DECLARATION: + result = "" + for sig in sig_group.signatures(): + result += f"{sig.decl()} const;\n" + return result + + if self.target is not Target.DEFINITION: + assert_never(self.target) + + result = "" + + for sig in sig_group.signatures(): + target_sig = DispatcherSignature.from_schema(f.func) + exprs = translate(sig.arguments(), target_sig.arguments(), method=True) + exprs_str = ", ".join([e.expr for e in exprs]) + + result += f""" +// aten::{f.func} +inline {sig.defn(prefix="Tensor::")} const {{ + return at::_ops::{f.func.name.unambiguous_name()}::call({exprs_str}); +}} +""" + + return result + + +# Generates RedispatchFunctions.h. +# This is similar to the C++ API defined in Functions.h, but provides access +# to the dispatcher's redispatch API. +@dataclass(frozen=True) +class ComputeRedispatchFunction: + @method_with_native_function + def __call__(self, f: NativeFunction) -> str | None: + # We unconditionally generate function variants of the redispatch API. + # This is mainly because we can namespace functions separately, but not methods, + sig_group = CppSignatureGroup.from_native_function( + f, method=False, fallback_binding=f.manual_cpp_binding + ) + + result = "" + for sig in sig_group.signatures(): + target_sig = DispatcherSignature.from_schema(f.func) + exprs = translate(sig.arguments(), target_sig.arguments()) + exprs_str = ", ".join(["dispatchKeySet"] + [a.expr for a in exprs]) + + result += f""" +// aten::{f.func} +inline {sig.decl(is_redispatching_fn=True)} {{ + return at::_ops::{f.func.name.unambiguous_name()}::redispatch({exprs_str}); +}} +""" + + return result + + +# Generates ATenOpList.cpp, a runtime accessible list of all aten +# operators. +# TODO: This was historically used to help some JIT interop code +# figure out whether or not to treat aten namespace'd operators +# one way or another, we should reevaluate if this is actually needed. +@with_native_function +def compute_aten_op(f: NativeFunction) -> str: + return f'{{"aten::{f.func.name.name}", "{f.func.name.overload_name}"}},' + + +# Generates MetaFunctions.h +def compute_meta_function_declaration(g: NativeFunctionsGroup) -> str | None: + if not g.structured: + return None + with native_function_manager(g.out): + name = meta.name(g) + args = structured.meta_arguments(g) + args_str = ", ".join(a.decl() for a in args) + parent_class = g.out.structured_inherits + if parent_class is None: + parent_class = "at::impl::MetaBase" + meta_return = "void" + precomputed = g.out.precomputed if g.structured else None + + if precomputed: + # Generate the template declaration with one bool parameter for each + # precomputed element. Each parameter is true if the corresponding (in + # terms of position) precomputed element has been set. + precomputed_values = [*precomputed.replace.values(), precomputed.add] + precomputed_elements = [ + elem for replace_list in precomputed_values for elem in replace_list + ] + precomputed_template_parameters = [ + elem.name.upper() for elem in precomputed_elements + ] + precomputed_template_params_str = ", ".join( + f"bool {param} = false" for param in precomputed_template_parameters + ) + precompute_template_decl = f"template <{precomputed_template_params_str}>" + + # Generate a string containing declarations of all precomputed elements. + precomputed_elements_with_cpp_types = [ + structured.argument_type(elem, binds=elem.name) + for elem in precomputed_elements + ] + + precomputed_elements_decl = ";\n".join( + f"{elem.cpp_type(strip_ref=True)} {elem.name}" + for elem in precomputed_elements_with_cpp_types + ) + + # Generate "setter" methods for each precomputed element. Each method will return + # a new instance of precompute_out with the template parameter that corresponds to + # the member set by the method to true (to indicate that it has been set). + setter_methods = [] + for i, elem in enumerate(precomputed_elements): + # Generate the signature. The return type will be the same + # as the type of `this` but with the template parameter + # corresponding to the element set by this method set to true. + # The assert generated below will ensure that this template + # parameter is false on the type of `this`. + return_ty_templates = ", ".join( + precomputed_template_parameters[:i] + + ["true"] + + precomputed_template_parameters[i + 1 :] + ) + return_ty = f"precompute_out<{return_ty_templates}>" + elem_cpp_ty = precomputed_elements_with_cpp_types[i].cpp_type( + strip_ref=True + ) + signature = f"{return_ty} set_{elem.name}({elem_cpp_ty} value)" + + # Generate an assert which checks that the + # template parameter corresponding to the precomputed + # element that is set by this method is false on the + # class corresponding to the object that `this` points to. + # This ensures that each element can be set only once. + assert_msg = f'"{elem.name} already set"' + assert_stmt = f"static_assert({precomputed_template_parameters[i]} == false, {assert_msg});" + + # Generate the new object construction block. All state + # except the element that this method sets is copied from the + # object that `this` points to. The value for the element that + # the method sets is taken from a method parameter. + construction_stmts = [] + construction_stmts.append(f"{return_ty} ret;") + + for j, elem in enumerate(precomputed_elements): + if i == j: + construction_stmts.append(f"ret.{elem.name} = value;") + else: + construction_stmts.append( + f"ret.{elem.name} = this->{elem.name};" + ) + + construction_stmts.append("return ret;") + construction_block = "\n".join(construction_stmts) + + setter_methods.append( + f""" + {signature} {{ + {assert_stmt} + {construction_block} + }} + """ + ) + setter_methods_decl = "\n".join(setter_methods) + + # Meta should return an instance of the struct containing the precomputed elements. + meta_return_template_params = ", ".join( + ["true"] * len(precomputed_template_parameters) + ) + # This typedef (actually a using statement) is needed so that TORCH_META_FUNC can reuse the return + # type (which has a variable number of template parameters). + meta_return_typedef = f"using meta_return_ty = precompute_out <{meta_return_template_params}>;" + meta_return = "meta_return_ty" + precomputed_decl = f""" + {precompute_template_decl} + struct TORCH_API precompute_out {{ + {setter_methods_decl} + {precomputed_elements_decl}; + }};""" + else: + meta_return_typedef = "" + precomputed_decl = "" + + return f"""\ +struct TORCH_API structured_{name} : public {parent_class} {{ + {precomputed_decl} + {meta_return_typedef} + {meta_return} meta({args_str}); +}}; +""" + + +def needs_backend_select(f: NativeFunction, selector: SelectiveBuilder) -> bool: + name = str(f.func.name.name) + if name.endswith("_like") or name.startswith("new_"): + return False + if f.func.arguments.tensor_options is None: + return False + return selector.is_native_function_selected(f) + + +# Generates RegisterBackendSelect.cpp, a series of kernels which provide +# specialized computation of dispatch key for operator signatures which cannot +# be easily done automatically using templating. +@dataclass(frozen=True) +class ComputeBackendSelect: + target: Literal[Target.DEFINITION, Target.REGISTRATION] + + # Selector object to determine which operators to generate + # registration code for. + selector: SelectiveBuilder + + @method_with_native_function + def __call__(self, f: NativeFunction) -> str | None: + if not needs_backend_select(f, self.selector): + return None + + name = native.name(f.func) + # BackendSelect can go to Meta, so it must preserve symints + native_sig = NativeSignature(f.func, symint=True) + + native_tensor_args = [ + a + for a in native_sig.arguments() + if isinstance(a.argument, Argument) and a.argument.type.is_tensor_like() + ] + + dispatcher_sig = DispatcherSignature.from_schema(f.func) + + sig: NativeSignature | DispatcherSignature + sig = dispatcher_sig + dispatcher_exprs = dispatcher_sig.exprs() + dispatch_key = "c10::computeDispatchKey(dtype, layout, device)" + + if self.target is Target.DEFINITION: + # I don't think there's actually a good reason to generate + # these two cases differently + # The first case could probably be improved though- it calls computeDispatchKeySet(), + # which looks at TLS dispatch keys- there should not be any by the time we reach backend select. + if native_tensor_args: + assert f.func.arguments.has_tensor_arg() + tensor_args = ", ".join(a.name for a in native_tensor_args) + compute_dk = f"""\ +DispatchKeySet _dk_set = c10::DispatchKeySet({dispatch_key}) | c10::detail::multi_dispatch_key_set({tensor_args}); +DispatchKeySet _dk_mask = c10::DispatchKeySet(DispatchKeySet::FULL_AFTER, DispatchKey::BackendSelect); +DispatchKeySet _dk = c10::impl::computeDispatchKeySet(_dk_set, _dk_mask);""" + else: + assert not f.func.arguments.has_tensor_arg() + compute_dk = ( + f"DispatchKeySet _dk = c10::DispatchKeySet({dispatch_key});" + ) + return f"""\ +// aten::{f.func} +C10_ALWAYS_INLINE +{sig.defn(name)} {{ + {compute_dk} + return at::_ops::{f.func.name.unambiguous_name()}::redispatch( + _dk, {", ".join(a.expr for a in dispatcher_exprs)}); +}} +""" + elif self.target is Target.REGISTRATION: + return f"""m.impl("aten::{f.func.name}", TORCH_FN({name}));""" + else: + assert_never(self.target) + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# +# YAML CODE GENERATION +# +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +def format_yaml(data: object) -> str: + # Ignore alias in Dumper + YamlDumper.ignore_aliases = lambda self, data: True # type: ignore[assignment] + + # Support serializing OrderedDict + def dict_representer(dumper: Any, data: Any) -> Any: + return dumper.represent_dict(data.items()) + + YamlDumper.add_representer(OrderedDict, dict_representer) # type: ignore[no-untyped-call] + # Some yaml parsers (e.g. Haskell's) don't understand line breaks. + # width=1e9 turns off optional line breaks and improves + # the portability of the outputted yaml. + return yaml.dump(data, default_flow_style=False, Dumper=YamlDumper, width=1e9) # type: ignore[no-any-return, call-overload] + + +# For some reason, some defaults we write to YAML are written as native +# YAML objects, rather than doing them uniformly as strings. This +# function detects those cases and converts them into native Python +# objects. +def pythonify_default(s: str) -> object: + if s == "true": + return True + elif s == "false": + return False + + try: + return int(s) + except ValueError: + try: + return float(s) + except ValueError: + return s + + +# What is a dynamic type? Over time, the semantic meaning of +# dynamic type has degraded to meaninglessness (in the old days, +# it captured dtype-ness of types, but that has gone away with +# the removal of TH). These days, it's mostly the same thing as +# the C++ API argument type, except that Tensor and Tensor? +# arguments simply present as Tensor. +# +# TODO: Get rid of dynamic_type, after getting tools/autograd +# to use the new codegen framework +def dynamic_type(t: Type) -> str: + if isinstance(t, OptionalType): + return dynamic_type(t.elem) + # Note we don't use t.is_tensor_like() here because it would + # also include Tensor[] + if str(t) == "Tensor": + return "at::Tensor" + # This is a legacy concept, so never report SymInt + return cpp.argumenttype_type( + t, mutable=False, binds="__placeholder__", symint=False + ).cpp_type() + + +def compute_method_of_yaml(variants: set[Variant]) -> list[str]: + # This is written out explicitly to ensure that Tensor and + # namespace are put into the list in the right order + method_of = ["Type"] + if Variant.method in variants: + method_of.append("Tensor") + if Variant.function in variants: + method_of.append("namespace") + return method_of + + +def compute_returns_yaml( + f: NativeFunction, +) -> tuple[list[dict[str, str]], dict[str, str]]: + # Note [name and field_name] + # ~~~~~~~~~~~~~~~~~~~~~~~~~~ + # To understand name_to_field_name, we must first talk about this + # schema: + # + # lstsq.X(Tensor self, Tensor A, *, Tensor(a!) X, Tensor(b!) qr) -> (Tensor(a!) solution, Tensor(b!) QR) + # + # There is something very odd about this schema: it is an out + # variant of the function (that is to say, it will convert into + # at::lstsq_out() in the C++ API), but the names of the output + # return arguments don't match the keyword argument names of + # the inputs. It TURNS OUT that in this situation, the historical + # Declarations.yaml we want to output is this (abbreviated to + # only show relevant fields): + # + # arguments: + # ... + # - field_name: solution + # name: X + # - field_name: QR + # name: qr + # ... + # + # returns: + # - field_name: solution + # name: X + # - field_name: QR + # name: qr + # + # The name of the return fields is stored in 'field_name', and the + # name of the arguments is stored in 'name'. So when we process + # arguments, we need a way to get at the corresponding return. At + # the moment, this is most conveniently done by constructing a + # mapping from name (the argument concept) to field_name (the + # return concept) while processing return arguments, since we don't + # directly maintain this correspondence in the modeling of function + # schema itself. + # + # See also https://github.com/pytorch/pytorch/issues/43114 + name_to_field_name: dict[str, str] = {} + + # Compute the returns field of the YAML entry + names = cpp.return_names(f) + returns = [] + for i, (r, name) in enumerate(zip(f.func.returns, names)): + ret = { + "dynamic_type": dynamic_type(r.type), + "name": name, + # legacy, report ints + "type": cpp.return_type(r, symint=False).cpp_type(), + } + + if r.name: + # See Note [name and field_name] + ret["field_name"] = r.name + if f.func.is_out_fn(): + name_to_field_name[f.func.arguments.out[i].name] = r.name + + returns.append(ret) + + return returns, name_to_field_name + + +# arguments in yaml roughly corresponds to the public C++ API +def compute_cpp_argument_yaml( + cpp_a: Binding, + *, + schema_order: bool, + kwarg_only_set: set[str], + out_arg_set: set[str], + name_to_field_name: dict[str, str], +) -> object: + if isinstance(cpp_a.argument, TensorOptionsArguments): + arg: dict[str, object] = { + "annotation": None, + "dynamic_type": "at::TensorOptions", + "is_nullable": False, + "name": cpp_a.name, + "type": cpp_a.type, + "kwarg_only": True, + } + if cpp_a.default is not None: + arg["default"] = cpp_a.default + return arg + elif isinstance(cpp_a.argument, SelfArgument): + raise AssertionError + elif isinstance(cpp_a.argument, Argument): + return compute_argument_yaml( + cpp_a.argument, + schema_order=schema_order, + kwarg_only_set=kwarg_only_set, + out_arg_set=out_arg_set, + name_to_field_name=name_to_field_name, + ) + + +def compute_argument_yaml( + a: Argument, + *, + schema_order: bool, + kwarg_only_set: set[str], + out_arg_set: set[str], + name_to_field_name: dict[str, str], +) -> object: + arg: dict[str, object] = { + "annotation": str(a.annotation) if a.annotation else None, + "dynamic_type": dynamic_type(a.type), + "is_nullable": a.type.is_nullable(), + "name": a.name, + # legacy, report ints + "type": cpp.argument_type(a, binds="__placeholder__", symint=False).cpp_type(), + } + if a.default is not None: + arg["default"] = pythonify_default( + cpp.default_expr(a.default, a.type, symint=False) + ) + if a.name in kwarg_only_set: + arg["kwarg_only"] = True + if a.name in out_arg_set: + arg["output"] = True + arg["allocate"] = True + # See Note [name and field_name] + if a.name in name_to_field_name: + arg["field_name"] = name_to_field_name[a.name] + # Historically, booleans don't get their size recorded, because it + # is already built into the cpp type (e.g., std::array) + l = a.type.is_list_like() + if l is not None and l.size is not None and str(l.elem) != "bool": + arg["size"] = l.size + return arg + + +@with_native_function +def compute_declaration_yaml(f: NativeFunction) -> object: + returns, name_to_field_name = compute_returns_yaml(f) + + # These sets are used to conveniently test if an argument is a + # kwarg-only or out argument + kwarg_only_set = {a.name for a in f.func.arguments.flat_kwarg_only} + out_arg_set = {a.name for a in f.func.arguments.out} + + sig_group = CppSignatureGroup.from_native_function( + f, method=False, fallback_binding=False + ) + cpp_args = sig_group.signature.arguments() + arguments = [ + compute_cpp_argument_yaml( + cpp_a, + schema_order=False, + kwarg_only_set=kwarg_only_set, + out_arg_set=out_arg_set, + name_to_field_name=name_to_field_name, + ) + for cpp_a in cpp_args + ] + + schema_order_jit_arguments = list(f.func.schema_order_arguments()) + + schema_order_arguments = [ + compute_argument_yaml( + a, + schema_order=True, + kwarg_only_set=kwarg_only_set, + out_arg_set=out_arg_set, + name_to_field_name=name_to_field_name, + ) + for a in schema_order_jit_arguments + ] + + cpp_schema_order_types = [ + # NB: method here doesn't matter + r.type + for a in schema_order_jit_arguments + for r in cpp.argument( + a, + method=False, + cpp_no_default_args=set(), + faithful=False, + symint=False, + has_tensor_options=False, + ) + ] + + # legacy, report ints + cpp_returns = cpp.returns_type(f.func.returns, symint=False).cpp_type() + schema_order_cpp_signature = f"{cpp_returns} ({', '.join(cpp_schema_order_types)})" + + is_factory_method = ( + any(isinstance(a.argument, TensorOptionsArguments) for a in cpp_args) + and Variant.method not in f.variants + ) + + return OrderedDict( + [ + ("name", cpp.name(f.func)), + ("operator_name", str(f.func.name.name)), + ("overload_name", str(f.func.name.overload_name)), + ("manual_kernel_registration", f.manual_kernel_registration), + ( + "category_override", + f.category_override if f.category_override is not None else "", + ), + ("schema_string", f"aten::{f.func}"), + ("arguments", arguments), + ("schema_order_cpp_signature", schema_order_cpp_signature), + ("schema_order_arguments", schema_order_arguments), + ("method_of", compute_method_of_yaml(f.variants)), + ("mode", "native"), + ("python_module", "" if f.python_module is None else f.python_module), + ("returns", returns), + ("inplace", f.func.name.name.inplace), + ("is_factory_method", is_factory_method), + ("abstract", f.is_abstract), + ("device_guard", f.device_guard), + ("with_gil", False), + ("deprecated", False), + ("has_math_kernel", f.has_composite_implicit_autograd_kernel), + ] + ) + + +# See Note [Auto generated composite kernels] +def has_autogenerated_composite_kernel(f: NativeFunction) -> bool: + return (f.structured or f.structured_delegate is not None) and ( + f.func.kind() == SchemaKind.functional or f.func.kind() == SchemaKind.inplace + ) + + +@with_native_function_and_indices +def compute_registration_declarations( + f: NativeFunction, backend_indices: dict[DispatchKey, BackendIndex] +) -> str: + name = dispatcher.name(f.func) + returns_type = dispatcher.returns_type(f.func.returns).cpp_type() + args = dispatcher.arguments(f.func) + args_str = ", ".join(a.no_default().decl() for a in args) + comment_data: dict[str, str] = { + "schema": f"aten::{f.func}", + # TODO: What exactly is the semantics of the 'dispatch' field? + "dispatch": str( + {k for k, v in backend_indices.items() if v.has_kernel(f)} + != {DispatchKey.CompositeImplicitAutograd} + and {k for k, v in backend_indices.items() if v.has_kernel(f)} + != { + DispatchKey.CompositeImplicitAutograd, + DispatchKey.CompositeImplicitAutogradNestedTensor, + } + ), + "default": str(f.has_composite_kernel or has_autogenerated_composite_kernel(f)), + } + return f"""{returns_type} {name}({args_str}); // {json.dumps(comment_data)} +""" + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# +# RUN IT ALL +# +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +def get_custom_build_selector( + provided_op_registration_allowlist: list[str] | None, + op_selection_yaml_path: str | None, +) -> SelectiveBuilder: + assert not ( + provided_op_registration_allowlist is not None + and op_selection_yaml_path is not None + ), ( + "Both provided_op_registration_allowlist and " + + "op_selection_yaml_path can NOT be provided at the " + + "same time." + ) + + op_registration_allowlist: set[str] | None = None + if provided_op_registration_allowlist is not None: + op_registration_allowlist = set(provided_op_registration_allowlist) + + if op_registration_allowlist is not None: + selector = SelectiveBuilder.from_legacy_op_registration_allow_list( + op_registration_allowlist, + True, + False, + ) + elif op_selection_yaml_path is not None: + selector = SelectiveBuilder.from_yaml_path(op_selection_yaml_path) + else: + selector = SelectiveBuilder.get_nop_selector() + + return selector + + +def get_grouped_by_view_native_functions( + native_functions: Sequence[NativeFunction], +) -> Sequence[NativeFunction | NativeFunctionsViewGroup]: + def maybe_create_view_group( + d: dict[ViewSchemaKind | SchemaKind, NativeFunction], + ) -> list[NativeFunction | NativeFunctionsViewGroup]: + funcs: list[NativeFunction | NativeFunctionsViewGroup] = [] + if ViewSchemaKind.aliasing in d: + view = d.pop(ViewSchemaKind.aliasing) + view_inplace = d.pop(ViewSchemaKind.aliasing_inplace, None) + view_copy = d.pop(SchemaKind.functional, None) + + funcs.append( + NativeFunctionsViewGroup( + view=view, + view_copy=view_copy, + view_inplace=view_inplace, + ) + ) + # Take the remaining functions that weren't part of the view group + # and emit them separately + funcs.extend(d.values()) + return funcs + + grouped_by_views: dict[ + FunctionSchema, dict[SchemaKind | ViewSchemaKind, NativeFunction] + ] = defaultdict(dict) + for f in native_functions: + schema = f.func.view_signature() + view_kind: ViewSchemaKind = f.view_schema_kind + # We need to group up ops relevant to the same "view", consisting of: + # view op (ViewSchemaKind.aliasing) + # view_inplace op (ViewSchemaKind.aliasing_inplace) + # view_copy op (SchemaKind.functional) + if view_kind == ViewSchemaKind.non_aliasing: + kind = f.func.kind() + assert kind not in grouped_by_views[schema] + grouped_by_views[schema][kind] = f + else: + assert view_kind not in grouped_by_views[schema], ( + f"{view_kind} already in {grouped_by_views[schema].keys()}" + ) + grouped_by_views[schema][view_kind] = f + + return list(concatMap(maybe_create_view_group, grouped_by_views.values())) + + +def get_grouped_native_functions( + native_functions: Sequence[NativeFunction], +) -> Sequence[NativeFunction | NativeFunctionsGroup]: + def flatten_pre_group( + d: dict[SchemaKind, NativeFunction], + ) -> Sequence[NativeFunction | NativeFunctionsGroup]: + r = NativeFunctionsGroup.from_dict(d) + if r is None: + # Invariant: any NativeFunctions that are code-generated + # should have been grouped into NativeFunctionsGroup objects + assert not any("generated" in f.tags for f in d.values()) + return list(d.values()) + else: + return [r] + + # TODO: how come ValuesView isn't a Sequence lol + pre_grouped_native_functions = pre_group_native_functions(native_functions) + return list( + concatMap(flatten_pre_group, list(pre_grouped_native_functions.values())) + ) + + +def get_ns_grouped_kernels( + *, + grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup], + backend_indices: dict[DispatchKey, BackendIndex], + native_function_decl_gen: Callable[ + [NativeFunctionsGroup | NativeFunction, BackendIndex], list[str] + ] = dest.compute_native_function_declaration, +) -> dict[str, list[str]]: + ns_grouped_kernels: dict[str, list[str]] = defaultdict(list) + for f in grouped_native_functions: + native_function_namespaces = set() + dispatch_keys = set() + for dispatch_key, backend_idx in backend_indices.items(): + backend_metadata = backend_idx.get_kernel(f) + if backend_metadata: + namespace = backend_metadata.cpp_namespace + dispatch_keys.add(dispatch_key) + native_function_namespaces.add(namespace) + else: + namespace = DEFAULT_KERNEL_NAMESPACE + assert len(native_function_namespaces) <= 1, ( + f"Codegen only supports one namespace per operator, got {native_function_namespaces} from {dispatch_keys}" + ) + ns_grouped_kernels[namespace].extend( + native_function_decl_gen(f, backend_idx) + ) + return ns_grouped_kernels + + +def get_native_function_declarations_from_ns_grouped_kernels( + *, + ns_grouped_kernels: dict[str, list[str]], +) -> list[str]: + declarations: list[str] = [] + newline = "\n" + for namespace, kernels in ns_grouped_kernels.items(): + ns_helper = NamespaceHelper( + namespace_str=namespace, + entity_name="", + max_level=4, + ) + # Convert to a set first to remove duplicate kernel names. Backends are + # allowed to repeat kernel names; only generate the declaration once! + ordered_kernels = list(OrderedDict.fromkeys(kernels)) + declarations.extend( + f""" +{ns_helper.prologue} +{newline.join(ordered_kernels)} +{ns_helper.epilogue} + """.split(newline) + ) + return declarations + + +# Return native function declarations grouped by their namespaces. +def get_native_function_declarations( + *, + grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup], + backend_indices: dict[DispatchKey, BackendIndex], + native_function_decl_gen: Callable[ + [NativeFunctionsGroup | NativeFunction, BackendIndex], list[str] + ] = dest.compute_native_function_declaration, +) -> list[str]: + """ + Generate kernel declarations, in `NativeFunction(s).h`. + :param grouped_native_functions: a sequence of `NativeFunction` or `NativeFunctionGroup`. + :param backend_indices: kernel collections grouped by dispatch key. + :param native_function_decl_gen: callable to generate kernel declaration for each `NativeFunction`. + :return: a list of string, from the string with all declarations, grouped by namespaces, split by newline. + """ + + ns_grouped_kernels = get_ns_grouped_kernels( + grouped_native_functions=grouped_native_functions, + backend_indices=backend_indices, + native_function_decl_gen=native_function_decl_gen, + ) + return get_native_function_declarations_from_ns_grouped_kernels( + ns_grouped_kernels=ns_grouped_kernels + ) + + +def get_kernel_namespace( + *, f: NativeFunction | NativeFunctionsGroup, backend_idx: BackendIndex +) -> str: + backend_metadata = backend_idx.get_kernel(f) + assert not backend_metadata or "::native" in backend_metadata.cpp_namespace, ( + f"The kernel for function {f.func.name if isinstance(f, NativeFunction) else f.functional.func.name} " + f"with dispatch key {backend_idx.dispatch_key}" + f" has a namespace {backend_metadata.cpp_namespace} and it's not ending with '::native'." + ) + return ( + backend_metadata.cpp_namespace if backend_metadata else DEFAULT_KERNEL_NAMESPACE + ) + + +# Return native function definitions grouped by dispatch key and custom namespace. +# Used in RegisterDispatchKey.cpp and etc. +def get_native_function_definitions( + *, + fm: FileManager, + grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup], + dispatch_key: DispatchKey, + backend_idx: BackendIndex, + selector: SelectiveBuilder, + rocm: bool, + symint: bool, + skip_dispatcher_op_registration: bool, + gen_dispatch_helpers: bool, +) -> list[str]: + definitions: list[str] = [] + ns_definitions: dict[str, list[str]] = defaultdict(list) + anonymous_definitions: dict[str, list[str]] = defaultdict(list) + registrations: dict[str, dict[str, list[str]]] = defaultdict(dict) + newline = "\n" + ns_gen = dest.RegisterDispatchKey( + backend_idx, + Target.NAMESPACED_DEFINITION, + selector, + rocm=rocm, + symint=symint, + class_method_name=None, + skip_dispatcher_op_registration=skip_dispatcher_op_registration, + ) + anonymous_gen = dest.RegisterDispatchKey( + backend_idx, + Target.ANONYMOUS_DEFINITION, + selector, + rocm=rocm, + symint=symint, + class_method_name=None, + skip_dispatcher_op_registration=skip_dispatcher_op_registration, + ) + reg_gen = dest.RegisterDispatchKey( + backend_idx, + Target.REGISTRATION, + selector, + rocm=rocm, + symint=symint, + class_method_name=None, + skip_dispatcher_op_registration=skip_dispatcher_op_registration, + ) + for f in grouped_native_functions: + kernel_namespace = get_kernel_namespace(f=f, backend_idx=backend_idx).replace( + "::native", "" + ) + + ns_definitions[kernel_namespace].extend( + ns_gen(f), + ) + anonymous_definitions[kernel_namespace].extend( + anonymous_gen(f), + ) + namespace = ( + f.namespace if isinstance(f, NativeFunction) else f.functional.namespace + ) + if namespace not in registrations[kernel_namespace]: + registrations[kernel_namespace] = defaultdict(list) + registrations[kernel_namespace][namespace].extend( + reg_gen(f), + ) + + for kernel_namespace in ns_definitions: + if len(ns_definitions[kernel_namespace]) == 0: + continue + ns_helper = NamespaceHelper(namespace_str=kernel_namespace) + registration_body = "" + for namespace in registrations[kernel_namespace]: + if not registrations[kernel_namespace][namespace]: + continue + registration_body += f""" +TORCH_LIBRARY_IMPL({namespace}, {dispatch_key}, m) {{ + {newline.join(registrations[kernel_namespace][namespace])} +}}""" + definitions.extend( + fm.substitute_with_template( + "RegisterDispatchDefinitions.ini", + lambda: { + "ns_prologue": ns_helper.prologue, + "ns_epilogue": ns_helper.epilogue, + "dispatch_anonymous_definitions": anonymous_definitions[ + kernel_namespace + ], + "static_init_dispatch_registrations": "" + if skip_dispatcher_op_registration + else registration_body, + "deferred_dispatch_registrations": "", + "dispatch_namespace": dispatch_key.lower(), + "dispatch_namespaced_definitions": ns_definitions[kernel_namespace], + }, + ).split(newline) + ) + + return definitions + + +# Return native function declarations grouped by dispatch key and custom namespace. +# Used in CPUFunctions_inl.h and etc. +def get_namespaced_declaration( + *, + grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup], + dispatch_key: DispatchKey, + backend_idx: BackendIndex, + selector: SelectiveBuilder, + rocm: bool, + symint: bool, +) -> list[str]: + declarations: list[str] = [] + ns_grouped_kernels: dict[str, list[str]] = defaultdict(list) + newline = "\n" + func = dest.RegisterDispatchKey( + backend_idx, + Target.NAMESPACED_DECLARATION, + selector, + rocm=rocm, + class_method_name=None, + skip_dispatcher_op_registration=False, + symint=symint, + ) + for f in grouped_native_functions: + namespace = get_kernel_namespace(f=f, backend_idx=backend_idx).replace( + "native", dispatch_key.lower() + ) + + ns_grouped_kernels[namespace].extend( + func(f), + ) + + for namespace, kernels in ns_grouped_kernels.items(): + if len(kernels) == 0: + continue + ns_helper = NamespaceHelper( + namespace_str=namespace, entity_name="", max_level=3 + ) + ordered_kernels = list(OrderedDict.fromkeys(kernels)) + declarations.extend( + f""" +{ns_helper.prologue} +{newline.join(ordered_kernels)} +{ns_helper.epilogue} + """.split(newline) + ) + return declarations + + +# Return native function schema registration code for aten and other namespaces. +def get_native_function_schema_registrations( + *, + native_functions: Sequence[NativeFunction], + schema_selector: SelectiveBuilder, +) -> tuple[list[str], str]: + ns_native_functions: dict[str, list[NativeFunction]] = defaultdict(list) + for native_function in native_functions: + ns_native_functions[native_function.namespace].append(native_function) + schema_registrations = "" + aten_schema_registrations = [] + custom_namespace = None + for namespace, funcs in ns_native_functions.items(): + schema_registrations_body = list( + mapMaybe(RegisterSchema(schema_selector), funcs) + ) + # NB: we have to separate aten namespace registration from other namespaces, + # because in the template we hardcoded an operator for ATen already. + if namespace == "aten": + aten_schema_registrations = schema_registrations_body + else: + custom_namespace = namespace + tab = "\t" + # if the namespace is predefined, we should use define a library fragment + # instead of a new library + torch_library_macro = ( + "TORCH_LIBRARY_FRAGMENT" + if namespace in FRAGMENT_NAMESPACES + else "TORCH_LIBRARY" + ) + schema_registrations += f""" +{torch_library_macro}({custom_namespace}, m) {{ + {tab.join(schema_registrations_body)} +}};""" + return (aten_schema_registrations, schema_registrations) + + +def gen_aggregated_headers( + *, + native_functions: Sequence[NativeFunction], + grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup], + structured_native_functions: Sequence[NativeFunctionsGroup], + static_dispatch_idx: list[BackendIndex], + selector: SelectiveBuilder, + backend_indices: dict[DispatchKey, BackendIndex], + cpu_fm: FileManager, + device_fms: dict[str, FileManager], + functions_keys: set[DispatchKey], + dispatch_keys: Sequence[DispatchKey], + rocm: bool, +) -> None: + # Buck doesn't support dynamic output files, so we aggregate all operator + # headers into a single file + cpu_fm.write( + "NativeMetaFunctions.h", + lambda: { + "NativeMetaFunctions_includes": [], + "NativeMetaFunctions_declarations": list( + mapMaybe(compute_meta_function_declaration, structured_native_functions) + ), + }, + ) + method_native_functions = [ + fn for fn in native_functions if Variant.method in fn.variants + ] + non_method_native_functions = [ + fn for fn in native_functions if fn not in method_native_functions + ] + cpu_fm.write( + "MethodOperators.h", + lambda: { + "MethodOperators_includes": [], + "MethodOperators_declarations": list( + mapMaybe( + ComputeOperators( + Target.DECLARATION, + static_dispatch_backend_indices=static_dispatch_idx, + ), + method_native_functions, + ) + ), + }, + ) + cpu_fm.write( + "Operators.h", + lambda: { + "Operators_includes": ["#include "], + "Operators_declarations": list( + mapMaybe( + ComputeOperators( + Target.DECLARATION, + static_dispatch_backend_indices=static_dispatch_idx, + ), + non_method_native_functions, + ) + ), + }, + ) + cpu_fm.write( + "Functions.h", + lambda: { + "static_dispatch_extra_headers": static_dispatch_extra_headers( + static_dispatch_idx + ), + "Functions_includes": ["#include "], + "Functions_declarations": list( + mapMaybe( + ComputeFunction(), + native_functions, + ) + ), + }, + ) + declarations = get_native_function_declarations( + grouped_native_functions=grouped_native_functions, + backend_indices=backend_indices, + ) + cpu_fm.write( + "NativeFunctions.h", + lambda: { + "NativeFunctions_includes": ["#include "], + "NativeFunctions_declarations": declarations, + }, + ) + + for dispatch_key in dispatch_keys: + fm = file_manager_from_dispatch_key(dispatch_key, device_fms, cpu_fm) + if dispatch_key in functions_keys: + inl_headers = f"#include " + + fm.write_with_template( + f"{dispatch_key}Functions.h", + "DispatchKeyFunctions.h", + lambda: { + "dispatch_key": str(dispatch_key), + "inline_headers": inl_headers, + }, + ) + fm.write_with_template( + f"{dispatch_key}Functions_inl.h", + "DispatchKeyFunctions_inl.h", + lambda: { + "DispatchKeyFunctions_inl_includes": [], + "dispatch_namespace": dispatch_key.lower(), + "dispatch_namespaced_declarations": get_namespaced_declaration( + grouped_native_functions=grouped_native_functions, + dispatch_key=dispatch_key, + backend_idx=backend_indices[dispatch_key], + selector=selector, + rocm=rocm, + symint=True, + ), + }, + ) + + del fm + + +def gen_per_operator_headers( + *, + native_functions: Sequence[NativeFunction], + grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup], + static_dispatch_idx: list[BackendIndex], + selector: SelectiveBuilder, + backend_indices: dict[DispatchKey, BackendIndex], + cpu_fm: FileManager, + device_fms: dict[str, FileManager], + ops_fm: FileManager, + functions_keys: set[DispatchKey], + dispatch_keys: Sequence[DispatchKey], + rocm: bool, +) -> None: + # For CMake builds, split operator declarations into separate headers in + # the ATen/ops folder to split up header dependencies + functions_by_root_name: dict[str, list[NativeFunction]] = defaultdict(list) + for fn in native_functions: + functions_by_root_name[fn.root_name].append(fn) + + grouped_functions_by_root_name: dict[ + str, list[NativeFunction | NativeFunctionsGroup] + ] = defaultdict(list) + for group in grouped_native_functions: + name = group.root_name + grouped_functions_by_root_name[name].append(group) + + for name, functions in functions_by_root_name.items(): + ops_fm.write_with_template( + f"{name}_ops.h", + "Operator.h", + lambda: { + "declarations": list( + mapMaybe( + ComputeOperators( + Target.DECLARATION, + static_dispatch_backend_indices=static_dispatch_idx, + ), + functions, + ) + ), + }, + ) + + ops_fm.write_with_template( + f"{name}.h", + "Function.h", + lambda: { + "static_dispatch_ops_headers": list( + mapMaybe( + lambda fn: static_dispatch_ops_header( + fn, backend_index=static_dispatch_idx + ), + functions, + ) + ), + "operator_includes": f"#include ", + "function_definitions": list( + mapMaybe( + ComputeFunction(), + functions, + ) + ), + }, + ) + + grouped_functions = grouped_functions_by_root_name.get(name, []) + structured_functions = [ + fn + for fn in grouped_functions + if isinstance(fn, NativeFunctionsGroup) and fn.structured + ] + is_structured = len(structured_functions) > 0 + + if is_structured: + ops_fm.write_with_template( + f"{name}_meta.h", + "NativeMetaFunction.h", + lambda: { + "meta_function_declarations": list( + mapMaybe( + compute_meta_function_declaration, structured_functions + ) + ), + }, + ) + declarations = get_native_function_declarations( + grouped_native_functions=grouped_functions, + backend_indices=backend_indices, + native_function_decl_gen=dest.compute_native_function_declaration, + ) + ops_fm.write_with_template( + f"{name}_native.h", + "NativeFunction.h", + lambda: { + "extra_includes": ( + f"#include " if is_structured else [] + ), + "native_function_declarations": declarations, + }, + ) + + for category, suffix in [ + ("Functions", ""), + ("Operators", "_ops"), + ("NativeMetaFunctions", "_meta"), + ("NativeFunctions", "_native"), + ]: + cpu_fm.write( + f"{category}.h", + lambda: { + f"{category}_includes": [ + f"#include " + for name in sorted(functions_by_root_name.keys()) + ], + f"{category}_declarations": [], + }, + ) + + for dispatch_key in dispatch_keys: + if dispatch_key not in functions_keys: + continue + + dispatch_namespace = dispatch_key.lower() + dispatch_names = [] + + for name, functions in functions_by_root_name.items(): + grouped_functions = grouped_functions_by_root_name.get(name, []) + declarations = list( + concatMap( + dest.RegisterDispatchKey( + backend_indices[dispatch_key], + Target.NAMESPACED_DECLARATION, + selector, + rocm=rocm, + symint=True, + class_method_name=None, + skip_dispatcher_op_registration=False, + ), + grouped_functions, + ) + ) + + if len(declarations) == 0: + continue + + dispatch_names.append(name) + ops_fm.write_with_template( + f"{name}_{dispatch_namespace}_dispatch.h", + "DispatchKeyFunction.h", + lambda: { + "dispatch_namespace": dispatch_namespace, + "dispatch_namespaced_declarations": declarations, + }, + ) + + fm = file_manager_from_dispatch_key(dispatch_key, device_fms, cpu_fm) + inl_headers = f"#include " + + fm.write_with_template( + f"{dispatch_key}Functions.h", + "DispatchKeyFunctions.h", + lambda: { + "dispatch_key": str(dispatch_key), + "inline_headers": inl_headers, + }, + ) + fm.write_with_template( + f"{dispatch_key}Functions_inl.h", + "DispatchKeyFunctions_inl.h", + lambda: { + "dispatch_namespace": dispatch_namespace, + "DispatchKeyFunctions_inl_includes": [ + f"#include " + for name in sorted(dispatch_names) + ], + "dispatch_namespaced_declarations": [], + }, + ) + del fm + + cpu_fm.write( + "MethodOperators.h", + lambda: { + "MethodOperators_includes": sorted( + f"#include " + for name, functions in functions_by_root_name.items() + if any(Variant.method in fn.variants for fn in functions) + ), + "MethodOperators_declarations": [], + }, + ) + + +def gen_headers( + *, + native_functions: Sequence[NativeFunction], + valid_tags: set[str], + grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup], + structured_native_functions: Sequence[NativeFunctionsGroup], + static_dispatch_idx: list[BackendIndex], + selector: SelectiveBuilder, + backend_indices: dict[DispatchKey, BackendIndex], + core_fm: FileManager, + cpu_fm: FileManager, + device_fms: dict[str, FileManager], + ops_fm: FileManager, + dispatch_keys: Sequence[DispatchKey], + functions_keys: set[DispatchKey], + rocm: bool, + per_operator_headers: bool, +) -> None: + if per_operator_headers: + gen_per_operator_headers( + native_functions=native_functions, + grouped_native_functions=grouped_native_functions, + static_dispatch_idx=static_dispatch_idx, + selector=selector, + backend_indices=backend_indices, + cpu_fm=cpu_fm, + device_fms=device_fms, + ops_fm=ops_fm, + dispatch_keys=dispatch_keys, + functions_keys=functions_keys, + rocm=rocm, + ) + else: + gen_aggregated_headers( + native_functions=native_functions, + grouped_native_functions=grouped_native_functions, + structured_native_functions=structured_native_functions, + static_dispatch_idx=static_dispatch_idx, + selector=selector, + backend_indices=backend_indices, + cpu_fm=cpu_fm, + device_fms=device_fms, + dispatch_keys=dispatch_keys, + functions_keys=functions_keys, + rocm=rocm, + ) + + core_fm.write( + "TensorBody.h", + lambda: { + "tensor_method_declarations": list( + mapMaybe( + ComputeTensorMethod( + target=Target.DECLARATION, + static_dispatch_backend_indices=static_dispatch_idx, + ), + native_functions, + ) + ), + "tensor_method_definitions": list( + mapMaybe( + ComputeTensorMethod( + target=Target.DEFINITION, + static_dispatch_backend_indices=static_dispatch_idx, + ), + native_functions, + ) + ), + }, + ) + + cpu_fm.write( + "RedispatchFunctions.h", + lambda: { + "function_redispatch_definitions": list( + mapMaybe(ComputeRedispatchFunction(), native_functions) + ), + }, + ) + + cpu_fm.write( + "RegistrationDeclarations.h", + lambda: { + "registration_declarations": [ + compute_registration_declarations(f, backend_indices) + for f in native_functions + ], + }, + ) + + cpu_fm.write( + "VmapGeneratedPlumbing.h", lambda: gen_all_vmap_plumbing(native_functions) + ) + + def gen_aten_interned_strings() -> dict[str, str]: + attrs: set[str] = set() # All function argument names + names = set() # All ATen function names + for func in native_functions: + names.add(str(func.func.name.name)) + # Some operators don't have a functional variant but we still create a + # symbol without the underscore + names.add(func.func.name.name.base) + + attrs.update(arg.name for arg in func.func.schema_order_arguments()) + + # These are keywords in C++, so aren't valid symbol names + # https://en.cppreference.com/w/cpp/language/operator_alternative + names -= { + "and", + "and_eq", + "bitand", + "bitor", + "compl", + "not", + "not_eq", + "or", + "or_eq", + "xor", + "xor_eq", + } + + return { + "aten_symbols": " \\\n".join( + [f"_(aten, {name})" for name in sorted(names)] + ), + "attr_symbols": " \\\n".join( + [f"_(attr, {name})" for name in sorted(attrs)] + ), + } + + core_fm.write("aten_interned_strings.h", gen_aten_interned_strings) + + def gen_tags_enum() -> dict[str, str]: + return {"enum_of_valid_tags": (",\n".join(sorted(valid_tags)))} + + core_fm.write("enum_tag.h", gen_tags_enum) + + +def gen_source_files( + *, + native_functions: Sequence[NativeFunction], + grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup], + structured_native_functions: Sequence[NativeFunctionsGroup], + view_groups: Sequence[NativeFunctionsViewGroup], + selector: SelectiveBuilder, + static_dispatch_idx: list[BackendIndex], + backend_indices: dict[DispatchKey, BackendIndex], + aoti_fm: FileManager, + core_fm: FileManager, + cpu_vec_fm: FileManager, + cpu_fm: FileManager, + device_fms: dict[str, FileManager], + dispatch_keys: Sequence[DispatchKey], + functions_keys: set[DispatchKey], + rocm: bool, + force_schema_registration: bool, + per_operator_headers: bool, + skip_dispatcher_op_registration: bool, + update_aoti_c_shim: bool, + aoti_backends: set[DispatchKey], + extend_aoti_c_shim: bool, +) -> None: + extra_cuda_headers = """\ +#include +#include +#include +#include """ + if rocm: + extra_cuda_headers = """\ +#include +#include +#include +#include """ + + for dispatch_key in dispatch_keys: + fm = file_manager_from_dispatch_key(dispatch_key, device_fms, cpu_fm) + if per_operator_headers: + + def operator_headers() -> list[str]: + headers = [] + for g in grouped_native_functions: + is_registered = False + if backend_index.has_kernel(g): + is_registered = True + # The above has_kernel test on a group will only test for + # the existence of out dispatch, because that's how + # structured kernels work. But sometimes functions can be + # grouped but not be structured, and then you need to check + # each individual piece, as they may have manual dispatch + # entries. + elif isinstance(g, NativeFunctionsGroup) and any( + backend_index.has_kernel(fn) for fn in g.functions() + ): + is_registered = True + # TODO: this condition is a bit questionable + # (It has to do with the fact that structured kernels get generated kernels + # to the Meta + CompositeExplicitAutogradNonFunctional keys). + elif g.structured and dispatch_key in ( + DispatchKey.Meta, + DispatchKey.CompositeExplicitAutogradNonFunctional, + ): + is_registered = True + if not is_registered: + continue + + headers.append(f"#include ") + if ( + dispatch_key + == DispatchKey.CompositeExplicitAutogradNonFunctional + ): + headers.append(f"#include ") + if dispatch_key in functions_keys: + headers.append( + f"#include " + ) + + return sorted(set(headers)) + + else: + + def operator_headers() -> list[str]: + headers = ["#include "] + if dispatch_key == DispatchKey.CompositeExplicitAutogradNonFunctional: + headers.append("#include ") + if dispatch_key in functions_keys: + headers.append(f"#include ") + return headers + + backend_index = backend_indices[dispatch_key] + ns_grouped_native_functions = defaultdict(list) + for grouped_native_function in grouped_native_functions: + namespace = ( + grouped_native_function.namespace + if isinstance(grouped_native_function, NativeFunction) + else grouped_native_function.functional.namespace + ) + ns_grouped_native_functions[namespace].append(grouped_native_function) + + dispatch_namespace = str(dispatch_key).lower() + + # CompositeImplicitAutogradNestdTensor does not currently user the helpers generated + # compilation will fail when `-Werror=unused-function` flag is set + gen_dispatch_helpers: bool = ( + dispatch_key != DispatchKey.CompositeImplicitAutogradNestedTensor + ) + + register_dispatch_key_base_env = { + "extra_cuda_headers": extra_cuda_headers + if is_cuda_dispatch_key(dispatch_key) + else "", + "external_backend_headers": "", + "dispatch_headers": dest.gen_registration_headers( + backend_index, per_operator_headers, rocm + ), + # ops_headers *could* be sharded, but doesn't seem necessary? + "ops_headers": operator_headers(), + "dispatch_helpers": ( + dest.gen_registration_helpers(backend_index) + if gen_dispatch_helpers + else [] + ), + } + + def register_dispatch_key_env_callable( + gnf: NativeFunction | NativeFunctionsGroup, + ) -> dict[str, list[str]]: + return { + "dispatch_definitions": get_native_function_definitions( + fm=fm, # noqa: F821 + grouped_native_functions=[gnf], + dispatch_key=dispatch_key, + backend_idx=backend_index, + selector=selector, + rocm=rocm, + symint=True, + skip_dispatcher_op_registration=skip_dispatcher_op_registration, + gen_dispatch_helpers=gen_dispatch_helpers, + ) + } + + fm.write_sharded_with_template( + f"Register{dispatch_key}.cpp", + "RegisterDispatchKey.cpp", + grouped_native_functions, + key_fn=lambda x: x.root_name, + env_callable=register_dispatch_key_env_callable, + num_shards=4 if dispatch_key == DispatchKey.CPU else 1, + base_env=register_dispatch_key_base_env, + sharded_keys={"dispatch_definitions"}, + ) + + for g in structured_native_functions: + if not g.out.ufunc_inner_loop or not is_ufunc_dispatch_key(dispatch_key): + continue + name = g.functional.func.name.name + if dispatch_key is DispatchKey.CPU: + assert fm is cpu_fm + fm.write_with_template( + f"UfuncCPU_{name}.cpp", + "UfuncCPU.cpp", + lambda: { + "meta_declaration": compute_meta_function_declaration(g), + "native_declaration": dest.compute_native_function_declaration( + g, backend_indices[dispatch_key] + ), + "native_definitions": dest.compute_ufunc_cpu(g), + }, + ) + cpu_vec_fm.write_with_template( + f"UfuncCPUKernel_{name}.cpp", + "UfuncCPUKernel.cpp", + lambda: { + "name": name, + "native_definitions": dest.compute_ufunc_cpu_kernel(g), + }, + ) + elif dispatch_key is DispatchKey.CUDA: + cuda_headers = "#include " + if rocm: + cuda_headers = "#include " + fm.write_with_template( + f"UfuncCUDA_{name}.cu", + "UfuncCUDA.cu", + lambda: { + "name": name, + "cuda_headers": cuda_headers, + "meta_declaration": compute_meta_function_declaration(g), + "native_declaration": dest.compute_native_function_declaration( + g, backend_indices[dispatch_key] + ), + "native_definitions": dest.compute_ufunc_cuda(g), + }, + ) + else: + raise AssertionError(f"unrecognized {dispatch_key} for ufunc") + + del fm + + gen_aoti_c_shim_files( + aoti_fm=aoti_fm, + aoti_backends=aoti_backends, + native_functions=native_functions, + backend_indices=backend_indices, + structured_native_functions=structured_native_functions, + extra_cuda_headers=extra_cuda_headers, + update_aoti_c_shim=update_aoti_c_shim, + extend_aoti_c_shim=extend_aoti_c_shim, + ) + + # BackendSelect is generated specially + def gen_backend_select() -> dict[str, list[str]]: + relevant_fns = [ + fn for fn in native_functions if needs_backend_select(fn, selector) + ] + return { + "ops_headers": [ + f"#include " for fn in relevant_fns + ], + "backend_select_method_definitions": list( + mapMaybe( + ComputeBackendSelect(Target.DEFINITION, selector), relevant_fns + ) + ), + "backend_select_function_registrations": list( + mapMaybe( + ComputeBackendSelect(Target.REGISTRATION, selector), relevant_fns + ) + ), + } + + cpu_fm.write("RegisterBackendSelect.cpp", gen_backend_select) + + schema_selector = selector + if force_schema_registration: + schema_selector = SelectiveBuilder.get_nop_selector() + + ( + aten_schema_registrations, + schema_registrations, + ) = get_native_function_schema_registrations( + native_functions=native_functions, schema_selector=schema_selector + ) + cpu_fm.write( + "RegisterSchema.cpp", + lambda: { + "aten_schema_registrations": [] + if skip_dispatcher_op_registration + else aten_schema_registrations, + "schema_registrations": [] + if skip_dispatcher_op_registration + else schema_registrations, + }, + ) + + def key_func( + fn: NativeFunction | NativeFunctionsGroup | NativeFunctionsViewGroup, + ) -> str: + return fn.root_name + + cpu_fm.write_sharded( + "Operators.cpp", + native_functions, + key_fn=key_func, + env_callable=lambda fn: { + "operator_headers": [f"#include "], + "definitions": [ + ComputeOperators( + Target.DEFINITION, + static_dispatch_backend_indices=static_dispatch_idx, + )(fn) + ], + }, + base_env={ + "static_dispatch_extra_headers": static_dispatch_extra_headers( + static_dispatch_idx + ), + }, + num_shards=5, + sharded_keys={ + "operator_headers", + "definitions", + "static_dispatch_extra_headers", + }, + ) + + cpu_fm.write("Functions.cpp", dict) + + core_fm.write("TensorMethods.cpp", dict) + + core_fm.write( + "ATenOpList.cpp", + lambda: { + "aten_ops": list(mapMaybe(compute_aten_op, native_functions)), + }, + ) + + def functionalization_env_callable( + g: NativeFunction | NativeFunctionsGroup | NativeFunctionsViewGroup, + ) -> dict[str, list[str]]: + def gen_op_headers( + g: NativeFunction | NativeFunctionsGroup | NativeFunctionsViewGroup, + ) -> list[str]: + if isinstance(g, NativeFunctionsViewGroup): + # view ops always get a functionalization kernel + headers = [ + f"#include ", + f"#include ", + ] + if g.view_copy is not None: + headers += [ + f"#include ", + f"#include ", + ] + return headers + elif isinstance(g, NativeFunctionsGroup): + headers = [ + f"#include ", + f"#include ", + f"#include ", + f"#include ", + ] + if g.inplace is not None: + headers += [ + f"#include ", + f"#include ", + ] + if g.mutable is not None: + headers += [ + f"#include ", + f"#include ", + ] + return headers + else: + return [ + f"#include ", + f"#include ", + ] + + return { + "ops_headers": gen_op_headers(g), + "func_definitions": gen_functionalization_definition( + selector, + g, + ), + "func_registrations": gen_functionalization_registration( + selector, + g, + backend_indices[DispatchKey.CompositeImplicitAutograd], + ), + } + + all_groups: list[ + NativeFunction | NativeFunctionsGroup | NativeFunctionsViewGroup + ] = list(structured_native_functions) + list( + view_groups # type: ignore[assignment, arg-type, operator] + ) + # Note: all operators that functionalization needs to handle (mutable and aliasing ops) should be grouped properly. + # The only reason we really need to deal with direct NativeFunctions here (instead of the groups) is because: + # (1) We can provide better error checking (error out if someone introduces a mutable op that doesn't obey the grouping logic) + # (2) functionalization needs to manually register CompositeImplicitAutograd kernels, which might not be grouped. + # Although this could go away long-term if we add a dedicated dispatch key for decompositions. + structured_map: dict[OperatorName, NativeFunction] = { + f.func.name: f + for f in concatMap(lambda g: list(g.functions()), structured_native_functions) + } + view_map: dict[OperatorName, NativeFunction] = { + f.func.name: f for f in concatMap(lambda g: list(g.functions()), view_groups) + } + all_groups.extend( + f + for f in native_functions + if f.func.name not in structured_map and f.func.name not in view_map + ) + + cpu_fm.write_sharded( + "RegisterFunctionalization.cpp", + all_groups, + key_fn=key_func, + env_callable=functionalization_env_callable, + num_shards=4, + sharded_keys={ + "ops_headers", + "func_definitions", + "func_registrations", + "func_add_back_views_definitions", + "func_add_back_views_registrations", + }, + ) + + cpu_fm.write( + "FunctionalInverses.h", + lambda: { + "view_inverse_declarations": list( + mapMaybe( + lambda g: gen_functionalization_view_inverse_declaration( + selector, g + ), + view_groups, + ) + ) + }, + ) + + # Note [view_copy NativeFunctions] + # Every view operator in native_functions.yaml that is not CompositeImplicitAutograd + # needs to have a corresponding non-aliasing {view}_copy variant. + # Backends that use functionalization and don't know how to handle aliasing ops + # are expected to implement kernels for these {view}_copy kernels instead. + # The code for {view}_copy operators in core is pretty boilerplate-heavy however, + # so we codegen the following: + # (1) A CompositeExplicitAutogradNonFunctional kernel for every {view}_copy operator. + # These are never explicitly invoked by the functionalization pass, + # but they could theoretically be called from user code (I added these kernels for completeness, + # since the ops are part of the public API). + # (2) A derivative formula for every {view}_copy operator + # {view}_copy operators can reuse the same derivative formulas as their {view} op counterparts, + # so rather than stamping all of the entries out in derivatives.yaml, + # we codegen them in. + # This is similar to how autograd codegen doesn't require inplace ops to have a derivatives.yaml entry. + cpu_fm.write( + "CompositeViewCopyKernels.cpp", + lambda: { + "ops_headers": [ + "\n".join( + f"#include \n" + # NB: this include is important as it ensures we + # set the visibility on generated view_copy kernels + # correctly + f"#include " + for f in ( + [g.view] if g.view_copy is None else [g.view, g.view_copy] + ) + ) + for g in view_groups + ] + + [ + "\n".join( + f"#include \n" + # NB: this include is also important for correct visibility + f"#include " + for f in [g.inplace, g.mutable, g.functional] + if f is not None and "generated" not in f.tags + ) + for g in structured_native_functions + ], + "CompositeViewCopyKernel_Definitions": list( + mapMaybe( + GenCompositeViewCopyKernel( + backend_indices[ + DispatchKey.CompositeExplicitAutogradNonFunctional + ] + ), + view_groups, + ) + ), + "GeneratedCompositeFunctional_Definitions": list( + mapMaybe( + gen_composite_functional_kernel, + structured_native_functions, + ) + ), + "GeneratedCompositeOut_Definitions": list( + mapMaybe( + gen_composite_out_kernel, + structured_native_functions, + ) + ), + }, + ) + + +def gen_declarations_yaml( + cpu_fm: FileManager, native_functions: Sequence[NativeFunction] +) -> None: + cpu_fm.write( + "Declarations.yaml", + lambda: format_yaml([compute_declaration_yaml(f) for f in native_functions]), + ) + + +def get_torchgen_root() -> Path: + """ + If you're depending on torchgen out-of-tree, you can use the root to figure + out the path to native_functions.yaml + """ + return Path(__file__).parent.resolve() + + +def main() -> None: + parser = argparse.ArgumentParser(description="Generate ATen source files") + parser.add_argument( + "-s", + "--source-path", + help="path to source directory for ATen", + default="aten/src/ATen", + ) + parser.add_argument( + "-o", + "--output-dependencies", + help="output a list of dependencies into the given file and exit", + ) + parser.add_argument( + "--dry-run", + action="store_true", + help="run without writing any files (still updates outputs)", + ) + parser.add_argument( + "--per-operator-headers", + action="store_true", + help="generate separate headers per operator in ATen/ops", + ) + parser.add_argument( + "-d", + "--install-dir", + "--install_dir", + help="output directory", + default="build/aten/src/ATen", + ) + parser.add_argument( + "--aoti-install-dir", + "--aoti_install_dir", + help="output directory for AOTInductor shim", + default="torch/csrc/inductor/aoti_torch/generated", + ) + parser.add_argument( + "--rocm", + action="store_true", + help="reinterpret CUDA as ROCm/HIP and adjust filepaths accordingly", + ) + parser.add_argument( + "--mps", + action="store_true", + help="Generate MPS registration code when set", + ) + parser.add_argument( + "--xpu", + action="store_true", + help="Generate XPU registration code when set", + ) + parser.add_argument( + "--mtia", + action="store_true", + help="Generate MTIA registration code when set", + ) + + # TODO: --op-registration-whitelist will be removed when all call-sites + # for gen.py are moved over to using the operator YAML file for mobile + # custom build. + parser.add_argument( + "--op-registration-whitelist", + "--op_registration_whitelist", + nargs="*", + help="filter op registrations by the whitelist (if set); " + "each item is `namespace`::`operator name` without overload name; " + "e.g.: aten::empty aten::conv2d ...", + ) + parser.add_argument( + "--op-selection-yaml-path", + "--op_selection_yaml_path", + help="Provide a path to the operator selection (for custom build) YAML " + "that contains the information about the set of selected operators " + "and their categories (training, ...). Each operator is either a " + "full operator name with overload or just a bare operator name. " + "The operator names also contain the namespace prefix (e.g. aten::)", + ) + parser.add_argument( + "--backend-whitelist", + "--backend_whitelist", + nargs="*", + help="filter dispatch backend by the whitelist (if set), " + "e.g.: CPU CUDA QuantizedCPU ...", + ) + parser.add_argument( + "--static-dispatch-backend", + "--static_dispatch_backend", + nargs="*", + help="generate static dispatch code for the specific backend (if set)", + ) + parser.add_argument( + "--skip-dispatcher-op-registration", + "--skip_dispatcher_op_registration", + action="store_true", + help="Avoid registering operators into the dispatcher.", + ) + parser.add_argument( + "--force-schema-registration", + "--force_schema_registration", + action="store_true", + help="force it to generate schema-only registrations for all ops, including" + "those that are not listed on --op-registration-whitelist", + ) + parser.add_argument( + "--generate", + type=str, + nargs="*", + choices=["headers", "sources", "declarations_yaml"], + default=["headers", "sources", "declarations_yaml"], + help="Generate only a subset of files", + ) + parser.add_argument( + "--update-aoti-c-shim", + action="store_true", + help="Update AOTInductor C shim after adding an entry to inductor_fallback_ops in torchgen/aoti/fallback_ops.py. " + "WARNING: Do not use this unless you are sure what you are doing!!!", + ) + parser.add_argument( + "--extend-aoti-c-shim", + action="store_true", + help="This Flag indicates the generation of c shims for out-of-tree ATen ops," + "which is an extension to the In-tree ATen op c shims. This flag needs to be combined with" + "---source-path=" + "--aoti-install-dir=/extend" + " default is torch/csrc/inductor/aoti_torch/generated/extend" + "WARNING: Do not use this unless you are sure what you are doing!!!", + ) + + options = parser.parse_args() + + selector = get_custom_build_selector( + options.op_registration_whitelist, + options.op_selection_yaml_path, + ) + + native_yaml_path = os.path.join(options.source_path, "native/native_functions.yaml") + tags_yaml_path = os.path.join(options.source_path, "native/tags.yaml") + + from torchgen.model import dispatch_keys + + # Only a limited set of dispatch keys get CPUFunctions.h headers generated + # for them; this is the set + functions_keys = { + DispatchKey.CPU, + DispatchKey.CUDA, + DispatchKey.CompositeImplicitAutograd, + DispatchKey.CompositeImplicitAutogradNestedTensor, + DispatchKey.CompositeExplicitAutograd, + DispatchKey.CompositeExplicitAutogradNonFunctional, + DispatchKey.Meta, + DispatchKey.MTIA, + } + + aoti_backends = { + DispatchKey.CPU, + DispatchKey.CUDA, + } + + # TODO: stop generating CUDA kernels for non-CUDA builds + ignore_keys = set() + + if options.mps or options.update_aoti_c_shim: + functions_keys.add(DispatchKey.MPS) + aoti_backends.add(DispatchKey.MPS) + else: + ignore_keys.add(DispatchKey.MPS) + + if DispatchKey.MPS in dispatch_keys: + del dispatch_keys[dispatch_keys.index(DispatchKey.MPS)] + + if options.xpu or options.update_aoti_c_shim: + functions_keys.add(DispatchKey.XPU) + aoti_backends.add(DispatchKey.XPU) + else: + ignore_keys.add(DispatchKey.XPU) + + if DispatchKey.XPU in dispatch_keys: + del dispatch_keys[dispatch_keys.index(DispatchKey.XPU)] + + if not options.mtia: + ignore_keys.add(DispatchKey.MTIA) + + if DispatchKey.MTIA in dispatch_keys: + del dispatch_keys[dispatch_keys.index(DispatchKey.MTIA)] + + if options.backend_whitelist: + dispatch_keys = [ + k + for k in dispatch_keys + if is_generic_dispatch_key(k) or str(k) in options.backend_whitelist + ] + + parsed_yaml = parse_native_yaml(native_yaml_path, tags_yaml_path, ignore_keys) + valid_tags = _GLOBAL_PARSE_TAGS_YAML_CACHE[tags_yaml_path] + native_functions, backend_indices = ( + parsed_yaml.native_functions, + parsed_yaml.backend_indices, + ) + + grouped_native_functions = get_grouped_native_functions(native_functions) + + structured_native_functions = [ + g for g in grouped_native_functions if isinstance(g, NativeFunctionsGroup) + ] + native_functions_with_view_groups = get_grouped_by_view_native_functions( + native_functions + ) + view_groups = [ + g + for g in native_functions_with_view_groups + if isinstance(g, NativeFunctionsViewGroup) + ] + + # NB: It is mandatory to NOT use os.path.join here, as the install directory + # will eventually be ingested by cmake, which does not respect Windows style + # path slashes. If you switch this to use os.path.join, you'll get an error + # like: + # + # Syntax error in cmake code when parsing string + # + # C:/Jenkins/workspace/pytorch-builds/pytorch-win-ws2016-cuda9-cudnn7-py3-build/build/aten/src/ATen\core/TensorMethods.h + # + # Invalid character escape '\c'. + core_install_dir = f"{options.install_dir}/core" + Path(core_install_dir).mkdir(parents=True, exist_ok=True) + ops_install_dir = f"{options.install_dir}/ops" + Path(ops_install_dir).mkdir(parents=True, exist_ok=True) + + aoti_install_dir = f"{options.aoti_install_dir}" + Path(aoti_install_dir).mkdir(parents=True, exist_ok=True) + + core_fm = make_file_manager(options=options, install_dir=core_install_dir) + cpu_fm = make_file_manager(options=options) + cpu_vec_fm = make_file_manager(options=options) + cuda_fm = make_file_manager(options=options) + ops_fm = make_file_manager(options=options, install_dir=ops_install_dir) + aoti_fm = make_file_manager(options=options, install_dir=aoti_install_dir) + device_fms = {"cuda": cuda_fm} + if options.xpu: + device_fms["xpu"] = make_file_manager(options=options) + + static_dispatch_idx: list[BackendIndex] = [] + if options.static_dispatch_backend: + static_dispatch_idx = [ + backend_indices[DispatchKey.parse(key)] + for key in options.static_dispatch_backend + ] + for key in options.static_dispatch_backend: + dp_key = DispatchKey.parse(key) + if dp_key not in functions_keys: + functions_keys.add(dp_key) + + if "sources" in options.generate: + gen_source_files( + native_functions=native_functions, + grouped_native_functions=grouped_native_functions, + structured_native_functions=structured_native_functions, + view_groups=view_groups, + selector=selector, + static_dispatch_idx=static_dispatch_idx, + backend_indices=backend_indices, + aoti_fm=aoti_fm, + core_fm=core_fm, + cpu_vec_fm=cpu_vec_fm, + cpu_fm=cpu_fm, + device_fms=device_fms, + dispatch_keys=dispatch_keys, + functions_keys=functions_keys, + rocm=options.rocm, + force_schema_registration=options.force_schema_registration, + per_operator_headers=options.per_operator_headers, + skip_dispatcher_op_registration=options.skip_dispatcher_op_registration, + update_aoti_c_shim=options.update_aoti_c_shim, + aoti_backends=aoti_backends, + extend_aoti_c_shim=options.extend_aoti_c_shim, + ) + + if "headers" in options.generate: + gen_headers( + native_functions=native_functions, + valid_tags=valid_tags, + grouped_native_functions=grouped_native_functions, + structured_native_functions=structured_native_functions, + static_dispatch_idx=static_dispatch_idx, + selector=selector, + backend_indices=backend_indices, + core_fm=core_fm, + cpu_fm=cpu_fm, + device_fms=device_fms, + ops_fm=ops_fm, + dispatch_keys=dispatch_keys, + functions_keys=functions_keys, + rocm=options.rocm, + per_operator_headers=options.per_operator_headers, + ) + + if "declarations_yaml" in options.generate: + gen_declarations_yaml(native_functions=native_functions, cpu_fm=cpu_fm) + + if options.output_dependencies: + depfile_path = Path(options.output_dependencies).resolve() + depfile_name = depfile_path.name + depfile_stem = depfile_path.stem + + for fm, prefix in [ + (cpu_fm, ""), + (cpu_vec_fm, "cpu_vec_"), + (core_fm, "core_"), + (ops_fm, "ops_"), + ] + [(device_fm, f"{device}_") for device, device_fm in device_fms.items()]: + varname = prefix + depfile_stem + path = depfile_path.parent / (prefix + depfile_name) + fm.write_outputs(varname, str(path)) + + +if __name__ == "__main__": + main() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/gen_aoti_c_shim.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/gen_aoti_c_shim.py new file mode 100644 index 0000000000000000000000000000000000000000..965ae8d268911df40cc53fa41636ad6b8ba942fe --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/gen_aoti_c_shim.py @@ -0,0 +1,715 @@ +from __future__ import annotations + +import difflib +import os +import textwrap +from dataclasses import dataclass +from typing import TYPE_CHECKING + +from torchgen.aoti.fallback_ops import inductor_fallback_ops +from torchgen.api.types import DispatcherSignature +from torchgen.api.types.signatures import CppSignature, CppSignatureGroup +from torchgen.context import method_with_native_function +from torchgen.model import ( + Argument, + BackendIndex, + BaseTy, + BaseType, + DispatchKey, + FunctionSchema, + is_cuda_dispatch_key, + ListType, + NativeFunction, + NativeFunctionsGroup, + OperatorName, + OptionalType, + Type, +) +from torchgen.utils import FileManager, mapMaybe + + +if TYPE_CHECKING: + from collections.abc import Sequence + + +base_type_to_c_type = { + BaseTy.Tensor: "AtenTensorHandle", + BaseTy.bool: "int32_t", # Use int to pass bool + BaseTy.int: "int64_t", + BaseTy.SymInt: "int64_t", # Inductor-generated code won't see a SymInt + BaseTy.Scalar: "double", # Use double to pass both integer and floating point + BaseTy.float: "double", # TODO: how about other floating point types? + BaseTy.str: "const char*", + BaseTy.DeviceIndex: "int32_t", + BaseTy.Layout: "int32_t", # Represent enum as int + BaseTy.MemoryFormat: "int32_t", # Represent enum as int + BaseTy.ScalarType: "int32_t", # Represent enum as int + BaseTy.Generator: "AtenGeneratorHandle", +} + +base_type_to_aten_type = { + BaseTy.Tensor: "at::Tensor", + BaseTy.bool: "bool", + BaseTy.int: "int64_t", + BaseTy.SymInt: "c10::SymInt", + BaseTy.Scalar: "c10::Scalar", + BaseTy.float: "double", + BaseTy.str: "::std::string_view", + BaseTy.DeviceIndex: "c10::DeviceIndex", + BaseTy.Layout: "c10::Layout", + BaseTy.MemoryFormat: "c10::MemoryFormat", + BaseTy.ScalarType: "c10::ScalarType", + BaseTy.Generator: "at::Generator", +} + +base_type_to_callsite_expr = { + BaseTy.Tensor: "resolve_tensor_dispatch_flags", + BaseTy.bool: "", + BaseTy.int: "", + BaseTy.SymInt: "", + BaseTy.Scalar: "", + BaseTy.float: "", + BaseTy.str: "", + BaseTy.DeviceIndex: "static_cast", + BaseTy.Layout: "static_cast", + BaseTy.MemoryFormat: "static_cast", + BaseTy.ScalarType: "static_cast", + BaseTy.Generator: "*generator_handle_to_generator_pointer", +} + + +# convert args to C types, names in declarations, and expressions in function bodies +def convert_arg_type_and_name( + typ: Type, + name: str, + is_write: bool = False, +) -> tuple[list[str], list[str], list[str], list[str]]: + if isinstance(typ, BaseType): + if typ.name in base_type_to_c_type: + if typ.name == BaseTy.Tensor and is_write: + # For output tensors, our normal call to resolve_tensor_dispatch_flags + # results in an rvalue tensor, which can't be passed to at::Tensor&. + # Override this case specifically. + callsite_expr = [f"*tensor_handle_to_tensor_pointer({name})"] + else: + callsite_expr = [ + f"{base_type_to_callsite_expr[typ.name]}({name})" + if base_type_to_callsite_expr[typ.name] + else name + ] + + return ( + [base_type_to_c_type[typ.name]], + [name], + [base_type_to_aten_type[typ.name]], + callsite_expr, + ) + elif typ.name == BaseTy.Device: + return ( + ["int32_t", "int32_t"], + [name, name + "_index_"], + ["c10::Device"], + [ + f"c10::Device(static_cast({name}), static_cast({name}_index_))" + ], + ) + else: + # TODO: BaseTy.Dimname, etc. + raise NotImplementedError(f"TODO: add support for arg type {repr(typ)}") + elif isinstance(typ, OptionalType): + c_types, names, aten_types, callsite_exprs = convert_arg_type_and_name( + typ.elem, name + ) + j = 0 # index for names + new_aten_types = [] + new_callsite_exprs = [] + for aten_type in aten_types: + # Use pointer to denote optional type + c_types[j] = c_types[j] + "*" + if aten_type.startswith("c10::ArrayRef<"): + # ArrayRef is passed as pointer + size, but no need to add "*" to the size argument + new_aten_types.append(f"::std::optional<{aten_type}>") + base_type = aten_type[len("c10::ArrayRef<") : -1] + new_callsite_exprs.append( + f"pointer_to_optional_list<{base_type}>({names[j]}, {names[j + 1]})" + ) + j += 2 + elif aten_type == "c10::Device": + # Device is passed as device_type + device_index + new_aten_types.append("::std::optional") + new_callsite_exprs.append( + f"pointer_to_optional_device({names[j]}, {names[j + 1]})" + ) + j += 2 + elif aten_type == "at::Tensor": + new_aten_types.append(f"::std::optional<{aten_type}>") + new_callsite_exprs.append(f"resolve_tensor_dispatch_flags({names[j]})") + j += 1 + else: + new_aten_types.append(f"::std::optional<{aten_type}>") + new_callsite_exprs.append( + f"pointer_to_optional<{aten_type}>({names[j]})" + ) + j += 1 + + return ( + c_types, + names, + new_aten_types, + new_callsite_exprs, + ) + elif isinstance(typ, ListType): + # Need to explicitly pass the list as pointer + length + c_types, names, aten_types, _ = convert_arg_type_and_name(typ.elem, name) + assert len(c_types) == 1, "ListType with unsupported element type " + repr(typ) + + # The list content should never be modified + c_types[0] = f"const {c_types[0]}*" + c_types.append("int64_t") + name = names[0] + names.append(name + "_len_") + + atype = aten_types[0] + callsite_exprs = [] + if atype == "bool": + # no converter from std::vector to c10::ArrayRef + # construct std::array instead + assert typ.size is not None + callsite_exprs.append(f"pointer_to_list<{typ.size}>({name})") + elif atype == "at::Tensor" and not is_write: + callsite_exprs.append( + f"resolve_tensor_list_dispatch_flags({name}, {name}_len_)" + ) + elif atype == "::std::optional": + # convert from std::vector<::std::optional> to c10::List<::std::optional> + callsite_exprs.append( + f"c10::List<{atype}>(c10::ArrayRef<{atype}>(resolve_tensor_list_dispatch_flags({name}, {name}_len_)))" + ) + else: + callsite_exprs.append(f"pointer_to_list<{atype}>({name}, {name}_len_)") + + aten_types = [f"c10::ArrayRef<{t}>" for t in aten_types] + return ( + c_types, + names, + aten_types, + callsite_exprs, + ) + raise NotImplementedError(f"Argument type {repr(typ)} not supported!") + + +def zip_type_and_name(types: list[str], names: list[str]) -> list[str]: + return [typ + " " + name for typ, name in zip(types, names)] + + +# Generate argument declarations and callsite expressions +def gen_arguments( + flat_arguments: Sequence[Argument], skipped_args: set[str] +) -> tuple[list[str], list[str]]: + types: list[str] = [] + new_names: list[str] = [] + callsite_exprs: list[str] = [] + for arg in flat_arguments: + if arg.name in skipped_args: + callsite_exprs.append("std::nullopt") + continue + new_types, names, _, new_callsite_exprs = convert_arg_type_and_name( + arg.type, arg.name, arg.is_write + ) + types.extend(new_types) + new_names.extend(names) + callsite_exprs.extend(new_callsite_exprs) + return zip_type_and_name(types, new_names), callsite_exprs + + +# Return values are passed out as pointer arguments because all the C shim functions +# are expected to return AOTITorchError. +# Generate returns as declarations and callsite expressions +def gen_returns(schema: FunctionSchema) -> tuple[list[str], list[str]]: + types = [] + names = [] + for idx, ret in enumerate(schema.returns): + names.append(f"ret{idx}") + if isinstance(ret.type, BaseType) and ret.type.name in base_type_to_c_type: + types.append(base_type_to_c_type[ret.type.name] + "*") + else: + raise NotImplementedError( + f"TODO: add support for return type {repr(ret.type)}" + ) + + def convert_return(typ: BaseType, val: str) -> str: + if typ.name == BaseTy.Tensor: + return f"new_tensor_handle(std::move({val}))" + elif typ.name == BaseTy.SymInt: + return f"{val}.expect_int()" + elif typ.name == BaseTy.Scalar: + return f"{val}.toDouble()" + else: + return val + + ret_pointer_can_be_null = False + unambiguous_name = schema.name.unambiguous_name() + for name in [ + "_scaled_dot_product_flash_attention", + "_scaled_dot_product_efficient_attention", + "_scaled_dot_product_cudnn_attention", + "_scaled_dot_product_fused_attention_overrideable", + "convolution_backward", + ]: + if name in unambiguous_name: + ret_pointer_can_be_null = True + break + + callsite_exprs: list[str] = [] + for idx, ret in enumerate(schema.returns): + tmp = "tmp_result" if len(names) == 1 else f"std::get<{idx}>(tmp_result)" + assert isinstance(ret.type, BaseType) + rval = convert_return(ret.type, tmp) + if ret_pointer_can_be_null: + callsite_exprs.append(f"if ({names[idx]}) {{ *{names[idx]} = {rval}; }}") + else: + callsite_exprs.append(f"*{names[idx]} = {rval};") + + return zip_type_and_name(types, names), callsite_exprs + + +# gen.py generates header first and then src, so caching the result here to avoid duplicate work +declaration_definition_cache: dict[tuple[str, str, str], tuple[str, str]] = {} + + +def gen_declaration_and_definition( + schema: FunctionSchema, + device: str, + backend_call: str, + version_info: dict[str, list[str]], +) -> tuple[str, str]: + base_name = schema.name.unambiguous_name() + + global declaration_definition_cache + if (base_name, device, backend_call) in declaration_definition_cache: + return declaration_definition_cache[(base_name, device, backend_call)] + + # Check the validity of version_info. The format should look like + # {"v2" : ["new_arg1"], "v3": ["new_arg2, new_arg3"]}. + indexed_version_info: dict[int, list[str]] = {1: []} + for ver_str, new_args in sorted(version_info.items()): + assert ver_str.startswith("v"), ( + f"Version number for {base_name} is {ver_str}, not starting with 'v'" + ) + try: + ver_id = int(ver_str[1:]) + except ValueError as e: + raise AssertionError( + f"Version number for {base_name} is {ver_str}, not a valid integer after 'v'" + ) from e + assert ver_id not in indexed_version_info, ( + f"{ver_str} for {base_name} has already been defined" + ) + indexed_version_info[ver_id] = new_args + + declarations: list[str] = [] + definitions: list[str] = [] + skipped_args: set[str] = set() + + for ver_id, new_args in sorted(indexed_version_info.items(), reverse=True): + # Iterate in the reverse order, so the latest version of an op will get generated first + # with all the arguments included, while a set of to-be-trimmed args is carried down + # to generate earlier version of the op. + func_name = base_name if ver_id == 1 else f"{base_name}_v{ver_id}" + if schema.is_out_fn(): + # out_variant has out arguments in the front, and it's ok to ignore return values + # because C shim functions only return AOTITorchError + args, callsite_exprs = gen_arguments( + [*schema.arguments.out, *schema.arguments.flat_non_out], skipped_args + ) + ret_assignments: list[str] = [] + else: + args, callsite_exprs = gen_arguments( + schema.arguments.flat_all, skipped_args + ) + # ignore return values for inplace ops + ret_declarations, ret_assignments = ( + ([], []) if schema.name.name.inplace else gen_returns(schema) + ) + args.extend(ret_declarations) + + declaration = textwrap.dedent( + f"AOTITorchError aoti_torch_{device}_{func_name}({', '.join(args)})" + ) + + tmp_result = "auto tmp_result = " if ret_assignments else "" + indent = "\t\t" + ret_assignments_str = ( + "\n".join(indent + r for r in ret_assignments) if ret_assignments else "" + ) + definition = ( + textwrap.dedent(f""" + {declaration} {{ + AOTI_TORCH_CONVERT_EXCEPTION_TO_ERROR_CODE({{ + {tmp_result}{backend_call}( + {", ".join(callsite_exprs)} + ); + """) + + ret_assignments_str + + textwrap.dedent(""" + }); + } + """) + ) + skipped_args.update(new_args) + declarations.append(f"AOTI_TORCH_EXPORT {declaration};") + definitions.append(definition) + + declaration_definition_cache[(base_name, device, backend_call)] = ( + "\n".join(declarations), + "\n".join(definitions), + ) + return declaration_definition_cache[(base_name, device, backend_call)] + + +def gen_static_dispatch_backend_call_signature( + sig: CppSignature | DispatcherSignature, + f: NativeFunction, +) -> CppSignature: + sig = DispatcherSignature.from_schema(f.func) + cpp_sigs = CppSignatureGroup.from_native_function( + f, method=False, fallback_binding=False + ) + if sig.symint and f.func.has_symint(): + cpp_sig = cpp_sigs.symint_signature + else: + cpp_sig = cpp_sigs.signature + assert cpp_sig is not None + return cpp_sig + + +def gen_static_dispatch_backend_call( + f: NativeFunction, + backend_index: BackendIndex, +) -> str: + sig = DispatcherSignature.from_schema(f.func) + cpp_sig = gen_static_dispatch_backend_call_signature(sig, f) + return f"at::{backend_index.dispatch_key.lower()}::{cpp_sig.name()}" + + +def get_backend_index_for_aoti( + func: NativeFunction, + func_group_mapping: dict[OperatorName, NativeFunctionsGroup], + dispatch_key: DispatchKey, + backend_indices: dict[DispatchKey, BackendIndex], + extend_aoti_c_shim: bool, +) -> BackendIndex | None: + backend_index = None + if backend_indices[dispatch_key].has_kernel(func) or ( + func.structured_delegate is not None + and func.structured_delegate in func_group_mapping + and backend_indices[dispatch_key].has_kernel( + func_group_mapping[func.structured_delegate] + ) + ): + backend_index = backend_indices[dispatch_key] + else: + # for the extend out-of-tree kernels, we don't need to + # duplicatly create C shim wrappers for other dispatch keys + if extend_aoti_c_shim: + return backend_index + + elif backend_indices[DispatchKey.CompositeExplicitAutograd].has_kernel(func): + # We need to create C shim wrappers for CompositeExplicitAutograd kernels + backend_index = backend_indices[DispatchKey.CompositeExplicitAutograd] + elif backend_indices[ + DispatchKey.CompositeExplicitAutogradNonFunctional + ].has_kernel(func): + # We need to create C shim wrappers for CompositeExplicitAutogradNonFunctional kernels + backend_index = backend_indices[ + DispatchKey.CompositeExplicitAutogradNonFunctional + ] + elif backend_indices[DispatchKey.CompositeImplicitAutograd].has_kernel(func): + backend_index = backend_indices[DispatchKey.CompositeImplicitAutograd] + + return backend_index + + +def get_header_for_aoti( + func: NativeFunction, + func_group_mapping: dict[OperatorName, NativeFunctionsGroup], + dispatch_key: DispatchKey, + backend_indices: dict[DispatchKey, BackendIndex], + extend_aoti_c_shim: bool, +) -> str | None: + backend_index = get_backend_index_for_aoti( + func, func_group_mapping, dispatch_key, backend_indices, extend_aoti_c_shim + ) + return ( + None + if backend_index is None + else f"#include " + ) + + +def get_fallback_op_name(func: NativeFunction) -> str: + return ( + f"{func.namespace}.{func.func.name.name}.{func.func.name.overload_name}" + if func.func.name.overload_name + else f"{func.namespace}.{func.func.name.name}.default" + ) + + +def gen_c_shim( + func: NativeFunction, + version_info: dict[str, list[str]], + func_group_mapping: dict[OperatorName, NativeFunctionsGroup], + dispatch_key: DispatchKey, + backend_indices: dict[DispatchKey, BackendIndex], + header: bool, + extend_aoti_c_shim: bool, +) -> str | None: + backend_index = get_backend_index_for_aoti( + func, func_group_mapping, dispatch_key, backend_indices, extend_aoti_c_shim + ) + if backend_index is None: + return None + + schema = func.func + device = dispatch_key.lower() + backend_call = gen_static_dispatch_backend_call( + func, + backend_index, + ) + + try: + if header: + declaration, _ = gen_declaration_and_definition( + schema, device, backend_call, version_info + ) + return declaration + else: + _, definition = gen_declaration_and_definition( + schema, device, backend_call, version_info + ) + return definition + + except NotImplementedError: + return None + + +@dataclass(frozen=True) +class ShimGenerator: + inductor_fallback_ops: dict[str, dict[str, list[str]]] + func_group_mapping: dict[OperatorName, NativeFunctionsGroup] + dispatch_key: DispatchKey + backend_indices: dict[DispatchKey, BackendIndex] + header: bool # True to generate .h and False to generate .cpp + extend_aoti_c_shim: bool + + @method_with_native_function + def __call__( + self, + func: NativeFunction, + ) -> str | None: + version_info = self.inductor_fallback_ops[get_fallback_op_name(func)] + result = gen_c_shim( + func, + version_info, + self.func_group_mapping, + self.dispatch_key, + self.backend_indices, + self.header, + self.extend_aoti_c_shim, + ) + return result + + +def gen_aoti_c_shim( + native_functions: Sequence[NativeFunction], + inductor_fallback_ops: dict[str, dict[str, list[str]]], + func_group_mapping: dict[OperatorName, NativeFunctionsGroup], + dispatch_key: DispatchKey, + backend_indices: dict[DispatchKey, BackendIndex], + header: bool, + extend_aoti_c_shim: bool, + includes: str = "", +) -> str: + body = "\n".join( + list( + mapMaybe( + ShimGenerator( + inductor_fallback_ops, + func_group_mapping, + dispatch_key, + backend_indices, + header, + extend_aoti_c_shim, + ), + native_functions, + ) + ) + ) + device = dispatch_key.lower() + warning = """ + +// WARNING: THIS FILE IS AUTOGENERATED BY torchgen. DO NOT MODIFY BY HAND. +// See https://github.com/pytorch/pytorch/blob/7e86a7c0155295539996e0cf422883571126073e/torchgen/gen.py#L2424-L2436 for details""" + + if header: + return ( + warning + + textwrap.dedent(""" + + #pragma once + + #include + + #ifdef __cplusplus + extern "C" { + #endif + + """) + + body + + textwrap.dedent(""" + + #ifdef __cplusplus + } // extern "C" + #endif + """) + ) + else: + return ( + warning + + textwrap.dedent(f""" + + #include + #include + + #ifndef AT_PER_OPERATOR_HEADERS + #include + #include + #include + #include + #else + """) + + includes + + textwrap.dedent(""" + #endif // AT_PER_OPERATOR_HEADERS + + using namespace torch::aot_inductor; + + """) + + body + ) + + +def gen_aoti_c_shim_files( + aoti_fm: FileManager, + aoti_backends: set[DispatchKey], + native_functions: Sequence[NativeFunction], + backend_indices: dict[DispatchKey, BackendIndex], + structured_native_functions: Sequence[NativeFunctionsGroup], + extra_cuda_headers: str, + extend_aoti_c_shim: bool, + update_aoti_c_shim: bool, +) -> None: + structured_func_group_dict = {} + for func_group in structured_native_functions: + for func in func_group.functions(): + if func.structured_delegate is not None: + structured_func_group_dict[func.structured_delegate] = func_group + break + + for dispatch_key in aoti_backends: + fallbacks = {} + for func in native_functions: + op_name = get_fallback_op_name(func) + if op_name in inductor_fallback_ops: + fallbacks[op_name] = func + fallback_native_functions = tuple( + value for _, value in sorted(fallbacks.items()) + ) + + # header files were checked in for ABI-compatiblilty checking + header_file_name = f"c_shim_{dispatch_key.lower()}.h" + new_header = gen_aoti_c_shim( + fallback_native_functions, + inductor_fallback_ops, + structured_func_group_dict, + dispatch_key, + backend_indices, + header=True, + extend_aoti_c_shim=extend_aoti_c_shim, + includes="", + ) + if update_aoti_c_shim: + aoti_fm.write( + header_file_name, + lambda: new_header, + ) + else: + try: + with open( + os.path.join(aoti_fm.install_dir, header_file_name) + ) as old_file: + old_header = old_file.read() + + if old_header != new_header: + diff = "\n".join( + difflib.unified_diff( + old_header.splitlines(), + new_header.splitlines(), + fromfile="expected", + tofile="actual", + lineterm="", + ) + ) + + raise RuntimeError(f""" +The generated AOTInductor C shim header files have unexpectedly changed. This +indicates an AOTInductor fallback operator ABI backward compatibility breakage!!! +Only in a limited number of situations, this is allowed: + +1. You added a fallback op to the inductor_fallback_ops list in torchgen/aoti/fallback_ops.py. +If that's the case, run `python torchgen/gen.py --update-aoti-c-shim` to add a new entry to +existing C shim header files. + +2. You added a new default argument to an existing fallback op. This is clearly a BC breaking +change in the AOTInductor land. You need to annotate the new default argument in +torchgen/aoti/fallback_ops.py, and then run `python torchgen/gen.py --update-aoti-c-shim` to +update the C shim header files by creating different versions of the fallback op. See +https://github.com/pytorch/pytorch/pull/154848 as an example. + +{diff} + """) + except FileNotFoundError: + print( + f"{os.path.join(aoti_fm.install_dir, header_file_name)} not found" + ) + + # cpp files are always generated on-the-fly + def headers_for_aoti() -> str: + headers = [] + for func in fallback_native_functions: + header = get_header_for_aoti( + func, + structured_func_group_dict, + dispatch_key, + backend_indices, + extend_aoti_c_shim=extend_aoti_c_shim, + ) + if header is not None: + headers.append(header) + return "\n".join(sorted(set(headers))) + + extra_headers = extra_cuda_headers if is_cuda_dispatch_key(dispatch_key) else "" + + aoti_fm.write( + f"c_shim_{dispatch_key.lower()}.cpp", + lambda: gen_aoti_c_shim( + fallback_native_functions, + inductor_fallback_ops, + structured_func_group_dict, + dispatch_key, + backend_indices, + header=False, + extend_aoti_c_shim=extend_aoti_c_shim, + includes=headers_for_aoti() + "\n" + extra_headers, + ), + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/gen_backend_stubs.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/gen_backend_stubs.py new file mode 100644 index 0000000000000000000000000000000000000000..07097010f8f28f8eaba72064d2fe0338510ad84c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/gen_backend_stubs.py @@ -0,0 +1,615 @@ +from __future__ import annotations + +import argparse +import os +import re +from collections import Counter, defaultdict, namedtuple +from pathlib import Path +from typing import TYPE_CHECKING + +import yaml + +import torchgen.api.dispatcher as dispatcher +import torchgen.dest as dest +from torchgen.api.types import DispatcherSignature +from torchgen.code_template import CodeTemplate +from torchgen.context import native_function_manager +from torchgen.gen import get_grouped_native_functions, parse_native_yaml +from torchgen.model import ( + BackendIndex, + BackendMetadata, + DispatchKey, + NativeFunction, + NativeFunctionsGroup, + OperatorName, +) +from torchgen.selective_build.selector import SelectiveBuilder +from torchgen.utils import concatMap, context, FileManager, NamespaceHelper, Target +from torchgen.yaml_utils import YamlLoader + + +if TYPE_CHECKING: + from collections.abc import Sequence + + +# Parses the external backend's yaml, and adds a new BackendIndex for the backend's dispatch key. +# Returns a Tuple of (backend_key, autograd_key, cpp_namespace, updated BackendIndex mapping) +ParsedExternalYaml = namedtuple( + "ParsedExternalYaml", + ["backend_key", "autograd_key", "class_name", "cpp_namespace", "backend_indices"], +) + + +def parse_backend_yaml( + backend_yaml_path: str, + grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup], + backend_indices: dict[DispatchKey, BackendIndex], +) -> ParsedExternalYaml: + native_functions_map: dict[OperatorName, NativeFunction] = { + f.func.name: f + for f in concatMap( + lambda f: [f] if isinstance(f, NativeFunction) else list(f.functions()), + grouped_native_functions, + ) + } + + with open(backend_yaml_path) as f: + yaml_values = yaml.load(f, Loader=YamlLoader) + assert isinstance(yaml_values, dict) + + valid_keys = [ + "backend", + "class_name", + "cpp_namespace", + "extra_headers", + "supported", + "autograd", + "full_codegen", + "non_native", + "ir_gen", + "symint", + ] + + backend = yaml_values.pop("backend", None) + assert backend is not None, 'You must provide a value for "backend"' + + class_name = yaml_values.pop("class_name", None) + + cpp_namespace = yaml_values.pop("cpp_namespace", None) + assert cpp_namespace is not None, 'You must provide a value for "cpp_namespace"' + + # Mostly just defaulting to false to stick with LazyTensor convention. + use_out_as_primary = yaml_values.pop("use_out_as_primary", False) + assert isinstance(use_out_as_primary, bool), ( + f"You must provide either True or False for use_out_as_primary. Provided: {use_out_as_primary}" + ) + + use_device_guard = yaml_values.pop("device_guard", False) + assert isinstance(use_device_guard, bool), ( + f"You must provide either True or False for device_guard. Provided: {use_device_guard}" + ) + + supported = yaml_values.pop("supported", []) + if supported is None: + supported = [] # Allow an empty list of supported ops + assert isinstance(supported, list), ( + f'expected "supported" to be a list, but got: {supported} (of type {type(supported)})' + ) + + symint = yaml_values.pop("symint", []) + if symint is None: + symint = [] # Allow an empty list of symint ops + assert isinstance(symint, list), ( + f'expected "symint" to be a list, but got: {supported} (of type {type(supported)})' + ) + symint_set = set(symint) + + supported_autograd = yaml_values.pop("autograd", []) + assert isinstance(supported_autograd, list), ( + f'expected "autograd" to be a list, but got: {supported_autograd}' + ) + + # full_codegen is ignored by parse_backend_yaml, and re-parsed in gen_lazy_tensor.py + full_codegen = yaml_values.pop("full_codegen", []) + supported.extend(full_codegen) + + # non_native is ignored by parse_backend_yaml, and re-parsed in gen_lazy_tensor.py + yaml_values.pop("non_native", {}) + + # ir_gen is ignored by parse_backend_yaml, and re-parsed in gen_lazy_tensor.py + yaml_values.pop("ir_gen", {}) + + assert len(yaml_values.keys()) == 0, ( + f"{backend_yaml_path} contains unexpected keys: {', '.join(yaml_values.keys())}. " + f"Only the following keys are supported: {', '.join(valid_keys)}" + ) + + def create_backend_index( + backend_ops: list[str], + symint_ops: set[str], + dispatch_key: DispatchKey, + *, + use_out_as_primary: bool, + use_device_guard: bool, + ) -> BackendIndex: + metadata: dict[OperatorName, BackendMetadata] = {} + for op in backend_ops: + op_name = OperatorName.parse(op) + assert op_name in native_functions_map, ( + f"Found an invalid operator name: {op_name}" + ) + # See Note [External Backends Follow Dispatcher API] + kernel_name = dispatcher.name(native_functions_map[op_name].func) + if op in symint_ops: + kernel_name += "_symint" + # TODO: allow structured external backends later. + m = BackendMetadata( + kernel=kernel_name, structured=False, cpp_namespace=cpp_namespace + ) + metadata[op_name] = m + return BackendIndex( + dispatch_key=dispatch_key, + use_out_as_primary=use_out_as_primary, + external=True, + device_guard=use_device_guard, + index=metadata, + ) + + backend_key: DispatchKey | None = None + if len(supported) > 0: + with context( + lambda: f'The provided value for "backend" must be a valid DispatchKey, but got {backend}.' + ): + backend_key = DispatchKey.parse(backend) + + backend_idx = create_backend_index( + supported, + symint_set, + backend_key, + use_out_as_primary=use_out_as_primary, + use_device_guard=use_device_guard, + ) + assert backend_key not in backend_indices + backend_indices[backend_key] = backend_idx + + autograd_key: DispatchKey | None = None + if len(supported_autograd) > 0: + with context( + lambda: f'The "autograd" key was specified, which indicates that you would like to override \ +the behavior of autograd for some operators on your backend. However "Autograd{backend}" is not a valid DispatchKey.' + ): + autograd_key = DispatchKey.parse(f"Autograd{backend}") + + autograd_idx = create_backend_index( + supported_autograd, + symint_set, + autograd_key, + use_out_as_primary=use_out_as_primary, + use_device_guard=use_device_guard, + ) + assert autograd_key not in backend_indices + backend_indices[autograd_key] = autograd_idx + + for g in grouped_native_functions: + if isinstance(g, NativeFunction): + forward_kernels = ( + [] + if backend_key is None + else [ + m + for m in [backend_indices[backend_key].get_kernel(g)] + if m is not None + ] + ) + backward_kernels = ( + [] + if autograd_key is None + else [ + m + for m in [backend_indices[autograd_key].get_kernel(g)] + if m is not None + ] + ) + else: + forward_kernels = ( + [] + if backend_key is None + else [ + m + for m in [ + backend_indices[backend_key].get_kernel(f) + for f in g.functions() + ] + if m is not None + ] + ) + backward_kernels = ( + [] + if autograd_key is None + else [ + m + for m in [ + backend_indices[autograd_key].get_kernel(f) + for f in g.functions() + ] + if m is not None + ] + ) + + forward_kernels = [f for f in forward_kernels if f is not None] + backward_kernels = [f for f in backward_kernels if f is not None] + assert len(forward_kernels) == 0 or len(backward_kernels) == 0, ( + f'Currently, all variants of an op must either be registered to a backend key, or to a backend\'s \ +autograd key. They cannot be mix and matched. If this is something you need, feel free to create an issue! \ +{forward_kernels[0].kernel} is listed under "supported", but {backward_kernels[0].kernel} is listed under "autograd".' + ) + + return ParsedExternalYaml( + backend_key, autograd_key, class_name, cpp_namespace, backend_indices + ) + + +def error_on_missing_kernels( + native_functions: Sequence[NativeFunction], + backend_indices: dict[DispatchKey, BackendIndex], + backend_key: DispatchKey, + autograd_key: DispatchKey | None, + class_name: str, + kernel_defn_file_path: str, + full_codegen: list[OperatorName] | None = None, +) -> None: + try: + with open(kernel_defn_file_path) as f: + backend_defns = f.read() + except OSError as e: + raise AssertionError( + f"Unable to read from the specified impl_path file: {kernel_defn_file_path}" + ) from e + + if full_codegen is None: + full_codegen = [] + + indices = [backend_indices[backend_key].index] + ( + [] if autograd_key is None else [backend_indices[autograd_key].index] + ) + # Quick mapping from each OperatorName used by the external backend + # to its backend kernel name + expected_backend_op_names: dict[OperatorName, str] = dict( + list( + concatMap( + lambda index: [ + (op_name, metadata.kernel) for op_name, metadata in index.items() + ], + indices, + ) + ) + ) + expected_backend_native_funcs: list[NativeFunction] = [ + f + for f in native_functions + if f.func.name in expected_backend_op_names.keys() + and f.func.name not in full_codegen + ] + expected_backend_kernel_name_counts: dict[str, list[NativeFunction]] = defaultdict( + list + ) + for native_f in expected_backend_native_funcs: + expected_backend_kernel_name_counts[ + expected_backend_op_names[native_f.func.name] + ].append(native_f) + + # This just looks for lines containing "foo(", and assumes that the kernel foo has been implemented. + # It might cause false negatives (we won't catch all cases), but that's ok - if we catch a missing kernel + # here, then we get a nicer error message. If we miss it, you get a linker error. + kernel_defn_regex = rf"(.*){class_name}::\s*([\w\d]*)\(" + actual_backend_kernel_name_counts = Counter( + # A bit unwieldy (this could probably be moved into regex), + # but we don't want to include kernel names that come from function calls, + # like "return torch_xla::XLANativeFunctions::empty_strided_symint(...)". + # Easy check is to ignore any lines with colons before the class name. + [ + y + for (x, y) in re.findall(kernel_defn_regex, backend_defns) + if not x.endswith(":") + ] + ) + + missing_kernels_err_msg = "" + for expected_name, funcs in expected_backend_kernel_name_counts.items(): + expected_overload_count = len(funcs) + actual_overload_count = actual_backend_kernel_name_counts[expected_name] + if expected_overload_count != actual_overload_count: + + def create_decl(f: NativeFunction) -> str: + with native_function_manager(f): + return DispatcherSignature.from_schema(f.func).decl() + + expected_schemas_str = "\n".join([create_decl(f) for f in funcs]) + missing_kernels_err_msg += f""" +{class_name} is missing a kernel definition for {expected_name}. We found {actual_overload_count} kernel(s) with that name, +but expected {expected_overload_count} kernel(s). The expected function schemas for the missing operator are: +{expected_schemas_str} + +""" + assert missing_kernels_err_msg == "", missing_kernels_err_msg + + +def main() -> None: + parser = argparse.ArgumentParser(description="Generate backend stub files") + parser.add_argument( + "-s", + "--source-yaml", + "--source_yaml", + help="path to source yaml file containing operator external definitions", + ) + parser.add_argument("-o", "--output-dir", "--output_dir", help="output directory") + parser.add_argument( + "--dry-run", "--dry_run", type=bool, default=False, help="output directory" + ) + parser.add_argument( + "--impl-path", + "--impl_path", + type=str, + default=None, + help="path to the source C++ file containing kernel definitions", + ) + options = parser.parse_args() + + run(options.source_yaml, options.output_dir, options.dry_run, options.impl_path) + + +def gen_dispatchkey_nativefunc_headers( + fm: FileManager, + class_name: str, + cpp_namespace: str, + backend_indices: dict[DispatchKey, BackendIndex], + grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup], + backend_dispatch_key: DispatchKey, + autograd_dispatch_key: DispatchKey | None, + backend_name: str = "", +) -> None: + assert class_name is not None + generated_comment = ( + "Autogenerated file by gen_backend_stubs.py. Do not edit directly!" + ) + + # Convert to a set first to remove duplicate kernel names. + # Backends are allowed to repeat kernel names; only generate the declaration once! + # Sort for deterministic output. + backend_declarations = sorted( + set( + concatMap( + lambda f: dest.compute_native_function_declaration( + f, backend_indices[backend_dispatch_key] + ), + grouped_native_functions, + ) + ) + ) + autograd_declarations = sorted( + set( + concatMap( + lambda f: [] + if autograd_dispatch_key is None + else dest.compute_native_function_declaration( + f, backend_indices[autograd_dispatch_key] + ), + grouped_native_functions, + ) + ) + ) + + ns_helper = NamespaceHelper(cpp_namespace) + fm.write_with_template( + f"{backend_dispatch_key}NativeFunctions.h", + "DispatchKeyNativeFunctions.h", + lambda: { + "generated_comment": generated_comment, + "namespace_prologue": ns_helper.prologue, + "class_name": class_name, + "namespace_epilogue": ns_helper.epilogue, + "dispatch_declarations": backend_declarations + autograd_declarations, + "BackendName": backend_name, + "DispatchKey": backend_dispatch_key, + }, + ) + + +def gen_dispatcher_registrations( + fm: FileManager, + output_dir: str, + class_name: str, + backend_indices: dict[DispatchKey, BackendIndex], + grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup], + backend_dispatch_key: DispatchKey, + dispatch_key: DispatchKey, + selector: SelectiveBuilder, + # build_in_tree is true for lazy TS backend and affects include paths, not used for external backends + build_in_tree: bool = False, + per_operator_headers: bool = False, + backend_name: str = "", + eager_registration: bool = True, +) -> None: + headers = [ + f"{output_dir}/{backend_dispatch_key}NativeFunctions.h", + ] + if build_in_tree: + external_backend_headers_str = "\n".join(f"#include <{h}>" for h in headers) + else: + external_backend_headers_str = "\n".join(f'#include "{h}"' for h in headers) + + assert class_name is not None + backend_index = backend_indices[dispatch_key] + + dispatch_registrations_body = list( + concatMap( + dest.RegisterDispatchKey( + backend_index, + Target.REGISTRATION, + selector, + rocm=False, + symint=True, + class_method_name=f"{class_name}", + skip_dispatcher_op_registration=False, + ), + grouped_native_functions, + ) + ) + newline = "\n" + ns_helper = NamespaceHelper(namespace_str="at") + deferred_dispatch_registrations = "" + static_init_dispatch_registrations = "" + if eager_registration: + static_template = CodeTemplate( + """\ +TORCH_LIBRARY_IMPL(aten, $dispatch_key, m) { + $dispatch_registrations_body +}""" + ) + static_init_dispatch_registrations = static_template.substitute( + dispatch_key=dispatch_key, + dispatch_registrations_body=dispatch_registrations_body, + ) + else: + deferred_template = CodeTemplate( + """\ +TORCH_API void Register${backend_name}${dispatch_key}NativeFunctions(); +TORCH_API void Register${backend_name}${dispatch_key}NativeFunctions() { + static auto m = MAKE_TORCH_LIBRARY_IMPL(aten, $dispatch_key); + $dispatch_registrations_body +}""" + ) + deferred_dispatch_registrations = deferred_template.substitute( + backend_name=backend_name, + dispatch_key=dispatch_key, + dispatch_registrations_body=dispatch_registrations_body, + ) + + fm.write_with_template( + f"Register{dispatch_key}.cpp", + "RegisterDispatchKey.cpp", + lambda: { + "extra_cuda_headers": "", + "external_backend_headers": external_backend_headers_str, + "ops_headers": "#include " + if not per_operator_headers + else "", + "DispatchKey": dispatch_key, + "dispatch_namespace": dispatch_key.lower(), + "dispatch_headers": dest.gen_registration_headers( + backend_index, per_operator_headers=per_operator_headers, rocm=False + ), + "dispatch_helpers": dest.gen_registration_helpers(backend_index), + "dispatch_definitions": fm.substitute_with_template( + "RegisterDispatchDefinitions.ini", + lambda: { + "ns_prologue": ns_helper.prologue, + "ns_epilogue": ns_helper.epilogue, + "static_init_dispatch_registrations": static_init_dispatch_registrations, + "deferred_dispatch_registrations": deferred_dispatch_registrations, + "dispatch_namespace": dispatch_key.lower(), + "dispatch_namespaced_definitions": "", + "dispatch_anonymous_definitions": list( + concatMap( + dest.RegisterDispatchKey( + backend_index, + Target.ANONYMOUS_DEFINITION, + selector, + rocm=False, + symint=True, + class_method_name=f"{class_name}", + skip_dispatcher_op_registration=False, + ), + grouped_native_functions, + ) + ), + }, + ).split(newline), + }, + ) + + +def run( + source_yaml: str, output_dir: str, dry_run: bool, impl_path: str | None = None +) -> None: + # Assumes that this file lives at PYTORCH_ROOT/torchgen/gen_backend_stubs.py + pytorch_root = Path(__file__).absolute().parent.parent + template_dir = os.path.join(pytorch_root, "aten/src/ATen/templates") + + def make_file_manager(install_dir: str) -> FileManager: + return FileManager( + install_dir=install_dir, template_dir=template_dir, dry_run=dry_run + ) + + fm = make_file_manager(output_dir) + + native_yaml_path = os.path.join( + pytorch_root, "aten/src/ATen/native/native_functions.yaml" + ) + tags_yaml_path = os.path.join(pytorch_root, "aten/src/ATen/native/tags.yaml") + parsed_yaml = parse_native_yaml(native_yaml_path, tags_yaml_path) + native_functions, backend_indices = ( + parsed_yaml.native_functions, + parsed_yaml.backend_indices, + ) + grouped_native_functions = get_grouped_native_functions(native_functions) + parsed_backend_yaml = parse_backend_yaml( + source_yaml, grouped_native_functions, backend_indices + ) + backend_key = parsed_backend_yaml.backend_key + autograd_key = parsed_backend_yaml.autograd_key + cpp_namespace = parsed_backend_yaml.cpp_namespace + class_name = parsed_backend_yaml.class_name + backend_indices = parsed_backend_yaml.backend_indices + + selector = SelectiveBuilder.get_nop_selector() + + if backend_key is None: + # This could be useful if a backend wants to quickly set up a noop yaml file but doesn't have any kernels ready yet. + return + + if class_name is None: + # class_name is an optional argument to backend yaml file. + # if specified it allows an external backend to override + # the name of the class that all generated kernel definitions live under. + # if not specified, its value is given as native_function_class_name. + class_name = backend_indices[backend_key].native_function_class_name() + assert class_name is not None + + if impl_path is not None: + error_on_missing_kernels( + native_functions, + backend_indices, + backend_key, + autograd_key, + class_name, + impl_path, + ) + + gen_dispatchkey_nativefunc_headers( + fm, + class_name, + cpp_namespace, + backend_indices, + grouped_native_functions, + backend_key, + autograd_key, + ) + + for dispatch_key in ( + [backend_key] if autograd_key is None else [backend_key, autograd_key] + ): + gen_dispatcher_registrations( + fm, + output_dir, + class_name, + backend_indices, + grouped_native_functions, + backend_key, + dispatch_key, + selector, + ) + + +if __name__ == "__main__": + main() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/gen_functionalization_type.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/gen_functionalization_type.py new file mode 100644 index 0000000000000000000000000000000000000000..42407974087a0ff21cab89a6a68f19602fa9f89b --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/gen_functionalization_type.py @@ -0,0 +1,882 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import Callable, TYPE_CHECKING + +from torchgen.api import cpp, dispatcher +from torchgen.api.translate import translate +from torchgen.api.types import ( + BaseCType, + Binding, + CType, + DispatcherSignature, + FunctionalizationLambda, + iTensorListRefT, + NativeSignature, + OptionalCType, + optionalSymIntArrayRefT, + symIntArrayRefT, + SymIntT, + tensorListT, + tensorT, + VectorCType, + ViewInverseSignature, +) +from torchgen.context import ( + method_with_native_function, + native_function_manager, + with_native_function, + with_native_function_and, +) +from torchgen.model import ( + Argument, + BackendIndex, + BaseTy, + BaseType, + FunctionSchema, + ListType, + NativeFunction, + NativeFunctionsGroup, + NativeFunctionsViewGroup, + Return, + SchemaKind, + SelfArgument, + TensorOptionsArguments, +) +from torchgen.native_function_generation import ( + INPLACE_OPS_THAT_DONT_GET_GROUPED_PROPERLY, + MUTABLE_OPS_THAT_CANNOT_GET_AN_OUT_VARIANT, + OUT_OPS_THAT_DONT_GET_GROUPED_PROPERLY, +) +from torchgen.utils import dataclass_repr + + +if TYPE_CHECKING: + from torchgen.selective_build.selector import SelectiveBuilder + + +# Note: [Mutable Ops Not Using Functionalization] +# Ops in this list currently do not work with functionalization and should be fixed. +MUTABLE_OPS_NOT_USING_FUNCTIONALIZATION = ( + OUT_OPS_THAT_DONT_GET_GROUPED_PROPERLY + + MUTABLE_OPS_THAT_CANNOT_GET_AN_OUT_VARIANT + + INPLACE_OPS_THAT_DONT_GET_GROUPED_PROPERLY + + [ + # It will be BC-breaking, but we should fix their schemas. + # should be inplace? + "record_stream", + # See Note [resize_ in Functionalization] + "resize_", + "resize_as_", + # This function is used as for testing purposes only. + "_fill_mem_eff_dropout_mask_", + ] +) + +# This file contains codegen that relates to the functionalization pass. +# It includes: +# - gen_functionalization_definition +# Generates dispatcher kernel definitions for the functionalization pass. +# - gen_functionalization_registration +# Generates dispatcher kernel registrations for the functionalization pass. +# - gen_functionalization_view_inverse_declaration +# Generates a declaration for an "inverse view", for every view op +# that is needed in functionalization. We manually implement their definitions. +# - gen_composite_view_copy_kernel +# Generates view_copy() composite kernels for all view_copy operators. + + +# Generates the body of the default composite C++ kernel for a {view}_copy NativeFunction +# See Note [view_copy NativeFunctions] +@dataclass(frozen=True) +class GenCompositeViewCopyKernel: + backend_index: BackendIndex + + @method_with_native_function + def __call__(self, g: NativeFunctionsViewGroup) -> str | None: + if g.view_copy is None: + return None + elif g.view_copy.func.name.name.base != f"{g.view.func.name.name}_copy": + # If the view_copy doesn't match the standard naming scheme of _copy, + # assume it already exists and doesn't need to be generated. + # Example: slice_inverse() with the copy variant named slice_scatter() + # instead of slice_inverse_copy() + return None + + metadata = self.backend_index.get_kernel(g.view_copy) + assert metadata is not None + + # We can make view_copy work in more cases by using reshape() + # when a normal view call would ordinarily fail. + # This also makes LTC more efficient, because they don't need to include + # clone() calls in their graph (which is normally needed by reshape). + if str(g.view_copy.func.name) == "view_copy": + assert metadata.kernel == "view_copy_symint" + return """\ +at::Tensor view_copy_symint(const at::Tensor & self, at::SymIntArrayRef size) { + c10::SymDimVector shape = infer_size_dv(size, self.sym_numel()); + if (!at::detail::computeStride(self.sym_sizes(), self.sym_strides(), shape).has_value()) { + return self.reshape_symint(size); + } else { + auto output = at::_ops::view::call(self, size); + return output.clone(/*memory_format=*/at::MemoryFormat::Contiguous); + } +} +""" + # view_copy is a native signature, since we're generating an at::native:: kernel + # Functionalization always operates on symints though + view_copy_sig = NativeSignature( + g.view_copy.func, symint=metadata.supports_symint() + ) + + # view is a dispatcher signature, since we're calling into the at::_ops API + view_sig = DispatcherSignature(g.view.func) + + view_api_name = g.view.func.name.unambiguous_name() + exprs = ", ".join( + [e.expr for e in translate(view_copy_sig.arguments(), view_sig.arguments())] + ) + + # view ops today always return either a Tensor or a list of Tensors + assert len(g.view.func.returns) == 1 + assert g.view.func.returns[0].type == BaseType( + BaseTy.Tensor + ) or g.view.func.returns[0].type == ListType(BaseType(BaseTy.Tensor), None) + + if g.view.func.returns[0].type == BaseType(BaseTy.Tensor): + return_cloned_output = """\ + return output.clone(/*memory_format=*/at::MemoryFormat::Contiguous);""" + else: + # If the return type is a list, we need to clone each tensor in the list. + return_cloned_output = f"""\ + {view_copy_sig.returns_type().cpp_type()} out_clone; + for (const auto i : c10::irange(output.size())) {{ + out_clone.push_back(output[i].clone(/*memory_format=*/at::MemoryFormat::Contiguous)); + }} + return out_clone;""" + + # The default generated composite kernel for {view}_copy() operators just clones + # the input tensor, and runs the underlying view on the clone. + return f""" +{view_copy_sig.defn(name=metadata.kernel)} {{ + auto output = at::_ops::{view_api_name}::call({exprs}); + {return_cloned_output} +}} +""" + + +def return_str(rets: tuple[Return, ...], names: list[str]) -> str: + assert len(rets) == len(names) + if len(rets) == 0: + return "" + elif len(rets) == 1: + return f"return {names[0]};" + else: + return f"return {dispatcher.returns_type(rets).cpp_type()}({', '.join(names)});" + + +def modifies_arguments(f: NativeFunction) -> bool: + return any( + a.annotation is not None and a.annotation.is_write + for a in f.func.arguments.flat_all + ) + + +def wrapper_name(func: FunctionSchema) -> str: + if func.name.overload_name: + return f"{cpp.name(func)}_{func.name.overload_name}" + else: + return cpp.name(func) + + +def is_tensor_like(a: Argument | TensorOptionsArguments | SelfArgument) -> bool: + return isinstance(a, SelfArgument) or ( + isinstance(a, Argument) and a.type.is_tensor_like() + ) + + +# We need to wrap / unwrap various arguments from the op in the functionalization kernels. +# Some op schemas include non-owning types though (like TensorList), +# and when we unwrap them we expect to get out an owning type!. +# We also return a lambda that tells you how to convert the non-owning type argument into the owning type. +def get_owning_type(t: CType) -> tuple[CType, Callable[[str], str]]: + if t == BaseCType(tensorListT): + return VectorCType(BaseCType(tensorT)), lambda x: f"{x}.vec()" + if t == BaseCType(iTensorListRefT): + return VectorCType(BaseCType(tensorT)), lambda x: f"{{{x}.begin(), {x}.end()}}" + # There are technically other non-owning types out there (like IntArrayRef), + # but functionalization only actually cares about the ones involving tensors. + return t, lambda x: x + + +# unwraps all tensor-like arguments, returning: +# (1) a string containing all of the logic that does the unwrapping +# (2) a context, to be used by translate(), with all of the relevant bindings. +def unwrap_tensor_args( + sig: DispatcherSignature, *, is_view_op: bool +) -> tuple[str, list[Binding]]: + context: list[Binding] = [] + unwrapped_tensor_args: list[str] = [] + for arg in sig.arguments(): + if is_tensor_like(arg.argument): + # for tensor inputs, we want to unwrap them before passing them into the redispatch calls. + unwrapped_name = f"{arg.name}_" + # For most ops, the functionalization needs to sync any pending updates on the input tensors + # before calling the operator, since otherwise the operator will act on stale data. + # For view ops though, we can continue to defer syncing until the tensor is used by + # a non-view operator. + maybe_sync_input = ( + "" if is_view_op else f"at::functionalization::impl::sync({arg.name});" + ) + unwrapped_type, conversion_fn = get_owning_type( + arg.nctype.remove_const_ref().type + ) + unwrapped_tensor_args.append( + f""" + {unwrapped_type.cpp_type()} {unwrapped_name}; + if (at::functionalization::impl::isFunctionalTensor({arg.name})) {{ + {maybe_sync_input} + {unwrapped_name} = at::functionalization::impl::from_functional_tensor({arg.name}); + }} else {{ + {unwrapped_name} = {conversion_fn(arg.name)}; + }}""" + ) + context.append(arg.with_name(unwrapped_name)) + else: + # for non-tensor inputs, we want to pass them directly into the redispatch calls. + context.append(arg) + unwrap_tensor_args_str = "\n ".join(unwrapped_tensor_args) + return unwrap_tensor_args_str, context + + +# converts all tensor-like arguments to meta tensors, which are used to compute stride info. Returns: +# (1) a string containing all of the logic that does the conversions. +# (2) a context, to be used by translate(), with all of the relevant bindings. +def convert_to_meta_tensors(sig: DispatcherSignature) -> tuple[str, list[Binding]]: + context: list[Binding] = [] + unwrapped_tensor_args: list[str] = [] + for arg in sig.arguments(): + if is_tensor_like(arg.argument): + # for tensor inputs, we want to unwrap them before passing them into the redispatch calls. + a_ = arg.name + unwrapped_name = f"{arg.name}_meta" + unwrapped_tensor_args.append(f"auto {unwrapped_name} = to_meta({a_});") + context.append(arg.with_name(unwrapped_name)) + else: + # for non-tensor inputs, we want to pass them directly into the redispatch calls. + context.append(arg) + unwrap_tensor_args_str = "\n ".join(unwrapped_tensor_args) + return unwrap_tensor_args_str, context + + +# The functionalization codegen currently expects view op schemas to have this form: +# foo(Tensor(a), ...) -> Tensor(a) (e.g. transpose) +# foo(Tensor(a!), ...) -> Tensor(a!) (e.g. transpose_) +def assert_view_op_properties(func: FunctionSchema) -> None: + def is_alias(a: Argument) -> bool: + return a.annotation is not None + + args = func.arguments.flat_non_out + # The first argument is a tensor with an alias semantics (annotations) + assert ( + len(args) > 0 and args[0].type == BaseType(BaseTy.Tensor) + ), f"""In the functionalization codegen, we expect the first argument of every view operator to be a tensor, +but found an argument of type {str(args[0].type)} for operator: {str(func.name)}.""" + # No other arguments have aliasing semantics + assert ( + is_alias(args[0]) and not any(is_alias(a) for a in args[1:]) + ), """In the functionalization codegen, we expect the first argument of every view operator to alias the output. +View operators with multiple aliasing inputs aren't supported yet. Found an operator that doesn't satisfy this constraint""" + + +# One-liner expression for checking if an expression expr of type type has any +# symbolic values. +def emit_expr_has_symbolic_values(expr: str, type: CType) -> str: + if type == BaseCType(SymIntT): + return f"{expr}.is_symbolic()" + + if isinstance(type, OptionalCType): + innerexpr = f"(*{expr})" + return f"{expr}.has_value() ? {emit_expr_has_symbolic_values(innerexpr, type.elem)} : false" + + if type == BaseCType(optionalSymIntArrayRefT): + return emit_expr_has_symbolic_values( + expr, OptionalCType(BaseCType(symIntArrayRefT)) + ) + + if type in (BaseCType(symIntArrayRefT), VectorCType(BaseCType(SymIntT))): + argname = "arg" + lambda_check = emit_expr_has_symbolic_values(argname, BaseCType(SymIntT)) + return ( + "std::any_of(" + f"{expr}.begin(), {expr}.end(), " + f"[=](auto& {argname}) {{ return {lambda_check}; }})" + ) + + raise ValueError( + "unsupported type for has_symbolic_values check. " + "It should be a SymInt or a collection of those. " + f"Got: {type.cpp_type()}" + ) + + +# Detects whether any of the SymInt arguments are, in fact, symbolic values. +# This is used in the constructor of ViewMeta. +def emit_has_symbolic_inputs(sig: DispatcherSignature) -> tuple[str, str]: + name = "has_symbolic_inputs" + statements = [ + f"{name} = {name} | ({emit_expr_has_symbolic_values(binding.name, binding.nctype.type)});" + for binding in sig.arguments() + if ( + isinstance(binding.argument, Argument) + and binding.argument.type.is_symint_like() + ) + ] + body = "\n ".join(statements) + return ( + name, + f""" + bool {name} = false; + {body}""", + ) + + +# Generates the Functionalization kernel for: +# - ops that create aliases (e.g. transpose()) +# - ops that are views AND mutations (e.g. transpose_()) +def emit_view_functionalization_body( + g: NativeFunctionsViewGroup, *, view_inplace: bool +) -> str: + if view_inplace: + # This op is both an inplace op AND a view op. + # See Note [Functionalization Pass - Inplace View Ops] for details. + # I currently have the view meta call into the out-of-place variant of the view, to avoid + # having to define an extra ~20 inplace {view}_inverse_ functions. + # Most view ops don't have NativeFunctionGroup's both, because we don't define out= variants for view ops. + # I'm assuming that every inplace-view op has a corresponding out-of-place view op, + # with the same name but the trailing underscore removed. + # This is currently asserted at parse time in gen.py (see error_check_native_functions). + assert g.view_inplace is not None + f = g.view_inplace + else: + f = g.view + + assert g.view_copy is not None + with native_function_manager(f): + call_sig = DispatcherSignature.from_schema(g.view_copy.func) + + # the "view_copy" op name that the functionalization kernels need to call + api_name = g.view_copy.func.name.unambiguous_name() + # Sometimes the functionalization pass needs to no-op (e.g. if it was passed non-functional tensors) + # "no-op"ing in this context is just redispatching to the original op. + noop_api_name = f.func.name.unambiguous_name() + + dispatcher_sig = DispatcherSignature.from_schema(f.func) + assert_view_op_properties(f.func) + view_tensor_name = dispatcher_sig.arguments()[0].name + + return_type = dispatcher_sig.returns_type().remove_const_ref().cpp_type() + + unwrap_tensor_args_str, unwrapped_args_ctx = unwrap_tensor_args( + dispatcher_sig, is_view_op=True + ) + view_redispatch_args = [ + e.expr + for e in translate(unwrapped_args_ctx, call_sig.arguments(), method=False) + ] + + forward_lambda = FunctionalizationLambda.from_func(g, is_reverse=False) + reverse_lambda = FunctionalizationLambda.from_func(g, is_reverse=True) + + # The meta API call should use the same arguments, but convert all tensors to meta tensors first. + meta_conversion_str, meta_call_ctx = convert_to_meta_tensors(dispatcher_sig) + meta_call_args = [ + e.expr for e in translate(meta_call_ctx, call_sig.arguments(), method=False) + ] + + ( + symbolic_inputs_varname, + symbolic_inputs_check, + ) = emit_has_symbolic_inputs(call_sig) + + if "inplace_view" in f.tags: + # See Note [Functionalization Pass - Inplace View Ops] for more details + return f""" + {dispatcher_sig.defn(name=wrapper_name(f.func), is_redispatching_fn=True)} {{ + if (!at::functionalization::impl::isFunctionalTensor({view_tensor_name})) {{ + // functionalization is re-entrant, but will no-op if it wasn't passed a FunctionalTensorWrapper. + {unwrap_tensor_args_str} + at::AutoDispatchSkipFunctionalize guard; + return at::_ops::{noop_api_name}::call({", ".join(view_redispatch_args)}); + }} + auto reapply_views = at::functionalization::impl::getFunctionalizationReapplyViewsTLS(); + auto inverse_return_mode = ( + reapply_views ? at::functionalization::InverseReturnMode::ViewOrScatterInverse + : at::functionalization::InverseReturnMode::NeverView + ); + {symbolic_inputs_check} + at::functionalization::ViewMeta view_meta = at::functionalization::ViewMeta( + {forward_lambda.decl()} {{ + if (reapply_views) {{ + return {forward_lambda.inner_call(reapply_views=True)} + }} else {{ + return {forward_lambda.inner_call(reapply_views=False)} + }} + }}, + {reverse_lambda.decl()} {{ + return {reverse_lambda.inner_call()} + }}, + /*has_symbolic_inputs=*/{symbolic_inputs_varname} + ); + auto compute_reference_meta = + {view_tensor_name}.key_set().has_backend(c10::BackendComponent::XLABit) || + {view_tensor_name}.key_set().has_backend(c10::BackendComponent::LazyBit); + {return_type} reference_tensor_output; + if (compute_reference_meta && !disable_meta_reference()) {{ + {meta_conversion_str} + at::AutoDispatchSkipFunctionalize func_guard; + c10::impl::ExcludeDispatchKeyGuard guard(exclude_keys_for_meta_dispatch); + reference_tensor_output = at::_ops::{noop_api_name}::call({", ".join(meta_call_args)}); + }} + // This function adds the above view meta to the current tensor and replays them off the base, + // mutating the size/stride info of the current FunctionalTensorWrapper. + // Because of this, we need to make sure to run the reference shape function above, + // BEFORE doing this (otherwise we'll end up running the reference function using the wrong sizes/strides) + at::functionalization::impl::mutate_view_meta({view_tensor_name}, view_meta); + // See Note [Propagating strides in the functionalization pass] + // XLA/LTC don't implement the logic to propagate strides correctly, so we need to rely + // on a reference implementation here (instead of relying on the output from the forward lambda + // having the correct stride info) + if (compute_reference_meta && !disable_meta_reference()) {{ + at::functionalization::impl::set_sizes_strides_offset({view_tensor_name}, reference_tensor_output); + }} + return {view_tensor_name}; + }} +""" + + else: + is_multi_output_view = isinstance(f.func.returns[0].type, ListType) + return f""" + {dispatcher_sig.defn(name=wrapper_name(f.func), is_redispatching_fn=True)} {{ + {unwrap_tensor_args_str} + if (!at::functionalization::impl::isFunctionalTensor({view_tensor_name})) {{ + // functionalization is re-entrant, but will no-op if it wasn't passed a FunctionalTensorWrapper. + at::AutoDispatchSkipFunctionalize guard; + return at::_ops::{noop_api_name}::call({", ".join(view_redispatch_args)}); + }} + auto reapply_views = at::functionalization::impl::getFunctionalizationReapplyViewsTLS(); + auto inverse_return_mode = ( + reapply_views ? at::functionalization::InverseReturnMode::ViewOrScatterInverse + : at::functionalization::InverseReturnMode::NeverView + ); + auto compute_reference_meta = + {view_tensor_name}.key_set().has_backend(c10::BackendComponent::XLABit) || + {view_tensor_name}.key_set().has_backend(c10::BackendComponent::LazyBit); + {return_type} reference_tensor_output; + if (compute_reference_meta && !disable_meta_reference()) {{ + {meta_conversion_str} + at::AutoDispatchSkipFunctionalize func_guard; + c10::impl::ExcludeDispatchKeyGuard guard(exclude_keys_for_meta_dispatch); + reference_tensor_output = at::_ops::{noop_api_name}::call({", ".join(meta_call_args)}); + }} + {return_type} tmp_output; + {{ + at::AutoDispatchSkipFunctionalize guard; + if (reapply_views) {{ + tmp_output = at::_ops::{noop_api_name}::call({", ".join(view_redispatch_args)}); + }} else {{ + tmp_output = at::_ops::{api_name}::call({", ".join(view_redispatch_args)}); + }} + }} + {symbolic_inputs_check} + at::functionalization::ViewMeta view_meta = at::functionalization::ViewMeta( + {forward_lambda.decl()} {{ + if (reapply_views) {{ + return {forward_lambda.inner_call(reapply_views=True)} + }} else {{ + return {forward_lambda.inner_call(reapply_views=False)} + }} + }}, + {reverse_lambda.decl()} {{ + return {reverse_lambda.inner_call()} + }}, + /*has_symbolic_inputs=*/{symbolic_inputs_varname}, + /*is_multi_output=*/{str(is_multi_output_view).lower()}, + /*is_as_strided=*/{str(str(f.func.name) == "as_strided").lower()} + ); + auto out = at::functionalization::impl::create_functional_tensor_with_view_meta(tmp_output, {view_tensor_name}, view_meta); + // See Note [Propagating strides in the functionalization pass] + if (compute_reference_meta && !disable_meta_reference()) {{ + at::functionalization::impl::set_sizes_strides_offset(out, reference_tensor_output); + }} + return out; + }} +""" + + +def maybe_create_output(f: NativeFunction, var_name: str) -> str: + if len(f.func.returns) == 0: + return "" + return_type = dispatcher.returns_type(f.func.returns).remove_const_ref().cpp_type() + return f"{return_type} {var_name} = " + + +# Given a NativeFunction, and a variable name corresponding to the output of redispatching on the function, +# this returns two lists of names, consisting of: +# - the names of returns corresponding to the original (mutable) inputs of the outer function +# - the names of returns corresponding to the (immutable) outputs of the inner redispatched function +def get_mutable_redispatch_return_names( + f: NativeFunction, inner_return_var: str +) -> tuple[list[str], list[str]]: + aliased_returns = [] + non_aliased_returns = [] + for i, name in enumerate(f.func.aliased_return_names()): + if name is not None: + aliased_returns.append(name) + else: + non_aliased_returns.append( + inner_return_var + if len(f.func.returns) == 1 + else f"std::get<{i}>({inner_return_var})" + ) + return aliased_returns, non_aliased_returns + + +# When functionalization "no-op's" and redispatches on a mutable operator, we need to take care so that: +# - For fresh outputs, we return the result of the redispatch (without wrapping outputs) +# - For outputs that were aliased to inputs, we return the inputs directly (since some of them might have been wrapped) +def return_from_mutable_noop_redispatch( + f: NativeFunction, inner_return_var: str +) -> str: + aliased, non_aliased = get_mutable_redispatch_return_names(f, inner_return_var) + # Just get all of the return names, and immediately return them + return return_str(f.func.returns, aliased + non_aliased) + + +def wrap_propagate_mutations_and_return( + f: NativeFunction, functional_op: NativeFunction, inner_return_var: str +) -> str: + mutable_arg_names = f.func.arguments.mutable_arg_names() + ( + aliased_outer_rets, + non_aliased_outer_rets, + ) = get_mutable_redispatch_return_names(f, inner_return_var) + _, non_aliased_inner_rets = get_mutable_redispatch_return_names( + functional_op, inner_return_var + ) + # The outer function may have a mix of aliased and non-aliased outputs, + # But the inner functional op that we're transforming to should only have non-aliased outputs + assert len(mutable_arg_names) + len(non_aliased_outer_rets) == len( + non_aliased_inner_rets + ) + + # First, take all of the newly created outputs from the inner call and wrap them into functional tensors + updates = [] + non_aliased_wrapped_ret_names = [] + for i, inner_ret in enumerate( + non_aliased_inner_rets[: len(non_aliased_outer_rets)] + ): + ret_name = f"output_{i}" + updates.append( + f"""\ + auto output_{i} = at::functionalization::impl::to_functional_tensor({inner_ret});""" + ) + non_aliased_wrapped_ret_names.append(ret_name) + + # Next, take all of the mutated outputs from the inner call corresponding to mutated inputs, + # and propagate the mutations + for outer_arg, inner_ret in zip( + mutable_arg_names, non_aliased_inner_rets[len(non_aliased_outer_rets) :] + ): + updates.append( + f"""\ + auto {outer_arg}_inner = at::functionalization::impl::from_functional_tensor({outer_arg}); + at::functionalization::impl::replace_({outer_arg}, {inner_ret}); + at::functionalization::impl::commit_update({outer_arg}); + at::functionalization::impl::sync({outer_arg}); + auto {outer_arg}_inner_updated = at::functionalization::impl::from_functional_tensor({outer_arg}); + at::functionalization::impl::propagate_xla_data_direct({outer_arg}_inner, {outer_arg}_inner_updated);""" + ) + + # Finally, we return: + # - Any mutable arguments that also returns + # - Any immutable returns that were created wrapping the output from the inner call + returns_str = return_str( + f.func.returns, aliased_outer_rets + non_aliased_wrapped_ret_names + ) + updates_str = "\n".join(updates) + return f"""\ +{updates_str} + {returns_str}""" + + +# Generates the Functionalization kernel for: +# - mutation ops (inplace and out= ops) +@with_native_function_and +def emit_inplace_functionalization_body( + f: NativeFunction, g: NativeFunctionsGroup +) -> str: + # mutation case + assert modifies_arguments(f) + + dispatcher_sig = DispatcherSignature.from_schema(f.func) + + unwrap_tensor_args_str, unwrapped_args_ctx = unwrap_tensor_args( + dispatcher_sig, is_view_op=False + ) + + mutated_names = [ + a.name + for a in f.func.arguments.flat_all + if a.type.is_tensor_like() and a.annotation is not None + ] + non_mutated_names = [ + a.name + for a in f.func.arguments.flat_all + if a.type.is_tensor_like() and a.annotation is None + ] + non_mutated_tensor_names = [ + a.name + for a in f.func.arguments.flat_all + if a.type == BaseType(BaseTy.Tensor) and a.annotation is None + ] + # all mutable inputs must be functional tensors in order to participate in functionalization + check_all_mutated_args_are_functional = " && ".join( + ["true"] + + [ + f"at::functionalization::impl::isFunctionalTensor({a})" + for a in mutated_names + ] + ) + check_any_non_mutated_args_are_functional = " || ".join( + ["false"] + + [ + f"at::functionalization::impl::isFunctionalTensor({a})" + for a in non_mutated_names + ] + ) + + check_any_non_mutated_tensors_are_xla = " || ".join( + ["false"] + + [ + f"{a}.device().type() == c10::DeviceType::XLA" + for a in non_mutated_tensor_names + ] + ) + # These are used in the cases where we don't functionalize and redispatch to the inplace op + # case 1: we hit an inplace op that doesn't have an out-of-place equivalent + # case 2: we hit an inplace ops but our inputs are not functional tensors (in which case our kernel just no-ops) + inplace_exprs = [ + e.expr + for e in translate(unwrapped_args_ctx, dispatcher_sig.arguments(), method=False) + ] + + # call the out-of-place variant of the op + return_type = ( + dispatcher.returns_type(g.functional.func.returns).remove_const_ref().cpp_type() + ) + functional_sig = DispatcherSignature.from_schema(g.functional.func) + functional_exprs = [ + e.expr + for e in translate(unwrapped_args_ctx, functional_sig.arguments(), method=False) + ] + + if f.func.is_out_fn(): + mutable_input_post_processing = "\n".join( + [ + f""" + at::functionalization::impl::replace_( + {a.name}, {"std::get<" + str(i) + ">(tmp_output)" if len(f.func.returns) > 1 else "tmp_output"}); + at::functionalization::impl::commit_update({a.name});""" + for (i, a) in enumerate(f.func.arguments.out) + if a.annotation and a.annotation.is_write and a.type.is_tensor_like() + ] + ) + else: + mutable_input_post_processing = "\n".join( # noqa: F841 + [ + f""" + at::functionalization::impl::replace_({a.name}, tmp_output); + at::functionalization::impl::commit_update({a.name});""" + for a in f.func.arguments.flat_all + if a.annotation and a.annotation.is_write and a.type.is_tensor_like() + ] + ) + + meta_conversion_str, meta_call_ctx = convert_to_meta_tensors(dispatcher_sig) + # We don't want to run the inplace meta func for ops like .set_(), because: + # (1) they're unnecessary: inplace meta checks are only useful for ops like add_(), + # where broadcasting will work for the out-of-place case but should fail on the inplace call + # (2) They'll also fail without adding extra infra: we'd need to convert the input storage argument + # into a meta storage + any_storage_args = any( + a.type == BaseType(BaseTy.Storage) for a in f.func.arguments.flat_all + ) + + return f""" + {dispatcher_sig.defn(name=wrapper_name(f.func), is_redispatching_fn=True)} {{ + if ({str(not any_storage_args and f.func.kind() == SchemaKind.inplace).lower()} && !disable_meta_reference()) {{ + // Before converting the mutable op to its functional variant, run meta tensors through the original op. + // This will help us catch shape errors that apply to inplace ops that wouldn't apply to their functional variants. + // (We can only do this for inplace ops today though, because they technically all support meta tensors). + {meta_conversion_str} + at::AutoDispatchSkipFunctionalize func_guard; + c10::impl::ExcludeDispatchKeyGuard guard(exclude_keys_for_meta_dispatch); + at::_ops::{f.func.name.unambiguous_name()}::call({", ".join(a.name for a in meta_call_ctx)}); + }} + {unwrap_tensor_args_str} + if (!({check_all_mutated_args_are_functional})) {{ + // We want to disable this check if there are any XLA tensors. + // cpu_tensor.copy_(xla_tensor) is valid code. + if (!({check_any_non_mutated_tensors_are_xla}) && ({check_any_non_mutated_args_are_functional})) {{ + // case 1: trying to mutate a non functional tensor with a functional tensor is an error + TORCH_INTERNAL_ASSERT(false, + "mutating a non-functional tensor with a functional tensor is not allowed.", + " Please ensure that all of your inputs are wrapped inside of a functionalize() call."); + }} else {{ + // case 2: arguments are not functional tensors, so we no-op and redispatch. + at::AutoDispatchSkipFunctionalize guard; + {maybe_create_output(f, "tmp_output")}at::_ops::{f.func.name.unambiguous_name()}::call({", ".join(inplace_exprs)}); + {return_from_mutable_noop_redispatch(f, "tmp_output")} + }} + }} else {{ + {return_type} tmp_output; + {{ + at::AutoDispatchSkipFunctionalize guard; + tmp_output = at::_ops::{g.functional.func.name.unambiguous_name()}::call({", ".join(functional_exprs)}); + }} + {wrap_propagate_mutations_and_return(f, g.functional, "tmp_output")} + }} + }}""" + + +# The below functions generate RegisterFunctionalization.cpp +# These files provide the kernels that run the functionalization pass, which can be opted into +# per backend (e.g. XLA or Vulkan), or as a composable transform (functionalize() in functorch). + + +# See Note [Functionalization Pass: View Inverses]. +def gen_functionalization_view_inverse_declaration( + selector: SelectiveBuilder, g: NativeFunctionsViewGroup +) -> str | None: + # For every (non-composite) view op, we need a corresponding "inverse view" function. + # This generates the declarations so we get a good compiler error when someone adds a new view. + @with_native_function + def emit_decl_helper(g: NativeFunctionsViewGroup) -> str | None: + if g.view.has_composite_implicit_autograd_kernel: + return None + view_inverse_sig = ViewInverseSignature(g) + return view_inverse_sig.decl() + + return emit_decl_helper(g) + + +def gen_functionalization_registration( + selector: SelectiveBuilder, + g: NativeFunction | NativeFunctionsGroup | NativeFunctionsViewGroup, + composite_implicit_autograd_index: BackendIndex, +) -> list[str]: + @with_native_function + def emit_registration_helper(f: NativeFunction) -> str: + assert not f.has_composite_implicit_autograd_kernel + registration_str = f"TORCH_FN(functionalization::{wrapper_name(f.func)})" + return f'm.impl("{f.func.name}", {registration_str});' + + # Don't generate kernels in mobile build + if not selector.include_all_operators: + return [] + + if isinstance(g, NativeFunctionsViewGroup): + # functionalization needs to register kernels for view + view_inplace ops + # See Note [Functionalization <> torch.Tensor constructor] + if str(g.view.func.name) == "lift_fresh": + return [] + view_str = [] + if not g.view.has_composite_implicit_autograd_kernel: + view_str.append(emit_registration_helper(g.view)) + if ( + g.view_inplace is not None + and not g.view_inplace.has_composite_implicit_autograd_kernel + ): + assert g.view_inplace.is_view_op + view_str.append(emit_registration_helper(g.view_inplace)) + return view_str + + elif isinstance(g, NativeFunctionsGroup): + # Gets a hand-written functionalization kernel + if g.inplace is not None and str(g.inplace.func.name) == "set_.source_Tensor": + fns = [] + else: + fns = list(g.functions()) + else: + if str(g.func.name) in MUTABLE_OPS_NOT_USING_FUNCTIONALIZATION: + return [] + fns = [g] + + registrations = [] + for f in fns: + if f.has_composite_implicit_autograd_kernel: + continue + if str(f.func.name) == "lift": + # See Note [Functionalization <> torch.Tensor constructor] + return [] + if str(f.func.name) == "resize_": + # See Note [resize_ in Functionalization] + return [] + if str(f.func.name.name) != "set_": + assert not f.is_view_op + # functionalization needs to generate and register kernels for inplace ops. + # We *also* need to directly register CompositeImplicitAUtograd kernels + # so that they decompose properly before functioanlization. + if modifies_arguments(f): + registrations.append(emit_registration_helper(f)) + return registrations + + +def gen_functionalization_definition( + selector: SelectiveBuilder, + # Note: Ideally this code should never have to look at NativeFunction + # (and instead only need to operate on grouped NativeFunctions). + # The only reason currently is because we need to emit direct dispatch registrations + # For CompositeImplicitAutograd operators, which are potentially ungrouped. + g: NativeFunction | NativeFunctionsGroup | NativeFunctionsViewGroup, +) -> list[str]: + # Don't generate kernels in mobile build + if not selector.include_all_operators: + return [] + + if isinstance(g, NativeFunctionsViewGroup): + # Case 1: emit view -> view_copy kernels for the functionalization pass + view_defs = [] + if not g.composite: + # invariant: NativeFunctionsViewGroup's always have a view_copy operator + # if the view is not composite (implicit autograd) + assert g.view_copy is not None, dataclass_repr(g, indent=1) + view_defs.append(emit_view_functionalization_body(g, view_inplace=False)) + if g.view_inplace is not None: + view_defs.append(emit_view_functionalization_body(g, view_inplace=True)) + return view_defs + elif isinstance(g, NativeFunction): + # Invariant: all mutable operators that we need to handle in functionalization + # should have been properly grouped up. + # TODO: The below ops all have "problematic" schemas that prevent them from + # getting functionalized. Instead of bending over backwards to get things to work, + # I think we should either: + # (1) fix their schemas (BC-breaking) + # (2) hand-write their functionalization kernels + if ( + str(g.func.name) not in MUTABLE_OPS_NOT_USING_FUNCTIONALIZATION + and str(g.func.name.name) not in MUTABLE_OPS_NOT_USING_FUNCTIONALIZATION + ): + assert g.has_composite_implicit_autograd_kernel or not modifies_arguments(g) + return [] + else: + # Case 2: emit inplace -> out-of-place kernels for the functionalization pass + mutation_defs = [] + mutation_defs.append(emit_inplace_functionalization_body(g.out, g)) + if g.inplace is not None: + mutation_defs.append(emit_inplace_functionalization_body(g.inplace, g)) + if g.mutable is not None: + mutation_defs.append(emit_inplace_functionalization_body(g.mutable, g)) + return mutation_defs + return [] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/gen_lazy_tensor.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/gen_lazy_tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..e397561d378e2f75274e90eb39aa6313719521d4 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/gen_lazy_tensor.py @@ -0,0 +1,585 @@ +from __future__ import annotations + +import argparse +import os +from collections import namedtuple +from pathlib import Path +from typing import Any, Callable, TYPE_CHECKING + +import yaml + +import torchgen.dest as dest +from torchgen.api.lazy import setValueT +from torchgen.api.types import BaseCppType +from torchgen.dest.lazy_ir import GenLazyIR, GenLazyNativeFuncDefinition, GenTSLazyIR +from torchgen.gen import get_grouped_native_functions, parse_native_yaml +from torchgen.gen_backend_stubs import ( + error_on_missing_kernels, + gen_dispatcher_registrations, + gen_dispatchkey_nativefunc_headers, + parse_backend_yaml, +) +from torchgen.model import NativeFunction, NativeFunctionsGroup, OperatorName +from torchgen.selective_build.selector import SelectiveBuilder +from torchgen.utils import FileManager, NamespaceHelper +from torchgen.yaml_utils import YamlLoader + + +if TYPE_CHECKING: + from collections.abc import Iterable, Iterator, Sequence + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# +# Lazy Tensor Codegen +# +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# Overview +# ~~~~~~~~ +# +# This codegen script builds on existing data models and helpers used +# by all ATen backends, and adds new functionality specific to lazy +# tensor backends. +# +# Inputs: +# - _native_functions.yaml: controls which operators are +# supported by the backend. +# +# Outputs: +# (for all backends) +# Ir.h defines Lazy IR classes to be constructed during tracing +# - opt-in: also generate 'lowering' methods for the TorchScript backend only +# NativeFunctions.cpp defines implementations of native functions which perform lazy tracing +# - opt-in: 'full_codegen' section of backend yaml; 'supported' section omits these implementations +# NativeFunctions.h declares implementations of native functions for both 'supported' and 'full_codegen' +# ops +# +# Register.cpp registers all op implementations with the dispatcher +# RegisterAutograd.cpp registers all autograd implementations with the dispatcher +# +# Validation Helpers: +# - Shape Inference: errs if any ops in backend yaml require shape inference not provided by meta kernels or +# implementations in torch/csrc/lazy/core/shape_inference.* +# - native function impls: errs if any 'supported' ops do not have an implementation defined in the backend +# (non-codegen) implementation file +# +# +# About the Data Model +# ~~~~~~~~~~~~~~~~~~~~ +# +# Modeled after ATen codegen, the first step is to parse yaml and build a data model for the operators +# we care about. In this case, the _native_functions yaml defines a subset of the core operators +# (defined in more detail in the main native_functions.yaml), which will be supported by your backend. +# Backends can list ops in two categories: +# - `supported` ops require hand-implementations but still get codegenned declarations and registrations +# - `full_codegen` ops get implementations (and IR classes) generated too +# +# Each native function is modeled as an object with a schema, and each schema has objects representing their +# arguments. Much of the codegen is manipulation of the arguments and their types. For example, lazy tensor +# backends need to transform 'at::Tensor' arguments into 'lazy::Value' objects, as well as replacing reference +# types (stringref) with actual string objects, and this is done by manipulating the data model objects. +# - see api/lazy.py for the lazy data model +# +# Once the data model is set up, the rest of this script processes a number of templates for output CPP file +# and fills in the template values using helpers in `dest/lazy_ir.py` and `dest/lazy_ts_lowering.py`. These +# helpers mostly iterate over functions and their arguments, outputting different c++ snippets. +# +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +# Parses the external backend's yaml, and adds a new BackendIndex for the backend's dispatch key. +# Returns a Tuple of (backend_key, autograd_key, cpp_namespace, updated BackendIndex mapping, full_codegen) +ParsedExternalYaml = namedtuple( + "ParsedExternalYaml", + ["backend_key", "autograd_key", "cpp_namespace", "backend_indices", "full_codegen"], +) + + +def parse_native_functions_keys( + backend_yaml_path: str, + grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup], +) -> tuple[list[OperatorName], list[Any], list[OperatorName]]: + with open(backend_yaml_path) as f: + yaml_values = yaml.load(f, Loader=YamlLoader) + assert isinstance(yaml_values, dict) + + full_codegen = yaml_values.pop("full_codegen", []) + non_native = yaml_values.pop("non_native", []) + ir_gen = yaml_values.pop("ir_gen", []) + assert isinstance(full_codegen, list) + assert isinstance(non_native, list) + assert isinstance(ir_gen, list) + full_codegen_opnames = [OperatorName.parse(name) for name in full_codegen] + ir_gen_opnames = [OperatorName.parse(name) for name in ir_gen] + return full_codegen_opnames, non_native, ir_gen_opnames + + +def validate_shape_inference_header( + shape_inference_hdr: str, expected_shape_infr_decls: list[str] +) -> None: + try: + with open(shape_inference_hdr) as f: + shape_infr_decls = f.read() + shape_infr_decl_lines = set(shape_infr_decls.split("\n")) + except OSError as e: + raise AssertionError( + f"Unable to read from the specified shape_inference_hdr file: {shape_inference_hdr}" + ) from e + + # TODO(whc) add a check for shape inference functions that have meta kernels implement and should be retired. + + missing_decls = [ + decl for decl in expected_shape_infr_decls if decl not in shape_infr_decl_lines + ] + if missing_decls: + raise Exception( # noqa: TRY002 + f"""Missing shape inference function.\n +Please add declare this function in {shape_inference_hdr}:\n +and implement it in the corresponding shape_inference.cpp file.\n +{os.linesep.join(missing_decls)}""" + ) + + +# Some helper functions for the codegen. +def get_ltc_helper_fns() -> str: + return """\ +at::Tensor to_meta(const at::Tensor& tensor) { + // undefined tensors can't be converted to the meta device, since they don't have sizes/strides + if (!tensor.defined()) return tensor; + auto out = at::native::empty_strided_meta_symint(tensor.sym_sizes(), tensor.sym_strides(), \ +/*dtype=*/tensor.scalar_type(), /*layout=*/tensor.layout(), \ +/*device=*/c10::Device(c10::kMeta), /*pin_memory=*/std::nullopt); + // needs to handle wrapped numbers, so dtype promotion works properly. + if (tensor.unsafeGetTensorImpl()->is_wrapped_number()) { + out.unsafeGetTensorImpl()->set_wrapped_number(true); + } + return out; +} +std::optional to_meta(const std::optional& tensor) { + if (tensor.has_value()) { + return to_meta(*tensor); + } + return std::nullopt; +} + +std::vector to_meta(at::ITensorListRef t_list) { + std::vector outs; + outs.reserve(t_list.size()); + for (const auto& tensor : t_list) { + outs.push_back(to_meta(tensor)); + } + return outs; +} +""" + + +class default_args: + node_base: str = "Node" + node_base_hdr: str | None = None + shape_inference_hdr: str = "torch/csrc/lazy/core/shape_inference.h" + tensor_class: str = "torch::lazy::LazyTensor" + tensor_class_hdr: str = "torch/csrc/lazy/core/tensor.h" + lazy_ir_generator: type[GenLazyIR] = GenLazyIR + native_func_definition_generator: type[GenLazyNativeFuncDefinition] = ( + GenLazyNativeFuncDefinition + ) + backend_name: str = "TorchScript" + + +def main() -> None: + parser = argparse.ArgumentParser(description="Generate Lazy Tensor backend files") + parser.add_argument( + "-s", + "--source-yaml", + "--source_yaml", + help="path to source yaml file containing operator external definitions", + ) + parser.add_argument("-o", "--output-dir", "--output_dir", help="output directory") + parser.add_argument( + "--dry-run", "--dry_run", type=bool, default=False, help="output directory" + ) + parser.add_argument( + "--impl-path", + "--impl_path", + type=str, + default=None, + help="path to the source C++ file containing kernel definitions", + ) + parser.add_argument( + "--gen-ts-lowerings", + "--gen_ts_lowerings", + action="store_true", + help="Generate TorchScript lowerings in addition to Lazy IR and NativeFunctions", + ) + parser.add_argument( + "--node-base", + "--node_base", + type=str, + default=default_args.node_base, + help="Name of backend specific custom Lazy IR Node base class", + ) + parser.add_argument( + "--node-base-hdr", + "--node_base_hdr", + type=str, + default=default_args.node_base_hdr, + help="Path to header file defining custom Lazy IR Node base class", + ) + parser.add_argument( + "--shape-inference-hdr", + "--shape_inference_hdr", + type=str, + default=default_args.shape_inference_hdr, + help="Path to header file defining custom Lazy shape inference functions", + ) + parser.add_argument( + "--tensor-class", + "--tensor_class", + type=str, + default=default_args.tensor_class, + help="Name of backend specific custom Lazy Tensor class", + ) + parser.add_argument( + "--tensor-class-hdr", + "--tensor_class_hdr", + type=str, + default=default_args.tensor_class_hdr, + help="Path to header file defining custom Lazy Tensor class", + ) + parser.add_argument( + "--backend-name", + "--backend_name", + type=str, + default=default_args.backend_name, + help="Name of the backend to generate", + ) + options = parser.parse_args() + + # Assumes that this file lives at PYTORCH_ROOT/torchgen/gen_backend_stubs.py + torch_root = Path(__file__).absolute().parents[2] + aten_path = str(torch_root / "aten" / "src" / "ATen") + lazy_ir_generator: type[GenLazyIR] = default_args.lazy_ir_generator + if options.gen_ts_lowerings: + lazy_ir_generator = GenTSLazyIR + native_func_definition_generator: type[GenLazyNativeFuncDefinition] = ( + default_args.native_func_definition_generator + ) + + run_gen_lazy_tensor( + aten_path, + options.source_yaml, + options.output_dir, + options.dry_run, + options.impl_path, + options.node_base, + options.node_base_hdr, + options.tensor_class, + options.tensor_class_hdr, + options.shape_inference_hdr, + lazy_ir_generator, + native_func_definition_generator, + options.backend_name, + ) + + +def run_gen_lazy_tensor( + aten_path: str, + source_yaml: str, + output_dir: str, + dry_run: bool, + impl_path: str | None, + node_base: str = default_args.node_base, + node_base_hdr: str | None = default_args.node_base_hdr, + tensor_class: str = default_args.tensor_class, + tensor_class_hdr: str = default_args.tensor_class_hdr, + shape_inference_hdr: str = default_args.shape_inference_hdr, + lazy_ir_generator: type[GenLazyIR] = default_args.lazy_ir_generator, + native_func_definition_generator: type[ + GenLazyNativeFuncDefinition + ] = default_args.native_func_definition_generator, + # build_in_tree is true for TS backend and affects include paths + build_in_tree: bool = False, + # per_operator_headers changes whether ATen/Functions.h or individual operator headers are used + # it must match how ATen was built + per_operator_headers: bool = False, + backend_name: str = default_args.backend_name, + gen_forced_fallback_code: bool = False, + use_lazy_shape: bool = True, + # the following arguments are temporary customization points for xla backend migration. + # do not rely on them otherwise, they should be removed once migration is complete + backend_namespace: str = "torch::lazy", + get_tensorlist: str = "GetTensorList", + get_tensor_or_wrap_number: str = "GetLtcTensorOrCreateForWrappedNumber", + try_get_tensor: str = "TryGetLtcTensor", + metrics_counter: str = 'TORCH_LAZY_FN_COUNTER("lazy::")', + create_tensor: str = "LazyTensor::Create", + create_from_first_tensor: bool = False, + create_aten_from_ltc_tensor: str = "torch::lazy::CreateAtenFromLtcTensor", + tuple_aten_from_ltc_tensors: str = "torch::lazy::TupleAtenFromLtcTensors", + lazy_value_class: str = "torch::lazy::Value", + lazy_tensor_ptr: str = "LazyTensorPtr", + get_device_fn: str = "torch::lazy::GetBackendDevice", +) -> None: + lv_tokens = lazy_value_class.split("::") + lv_class = lv_tokens[-1] + lv_ns = "::".join(lv_tokens[:-1]) + setValueT(BaseCppType(lv_ns, lv_class)) + template_dir = os.path.join(aten_path, "templates") + + def make_file_manager(install_dir: str) -> FileManager: + return FileManager( + install_dir=install_dir, template_dir=template_dir, dry_run=dry_run + ) + + fm = make_file_manager(output_dir) + + native_yaml_path = os.path.join(aten_path, "native/native_functions.yaml") + tags_yaml_path = os.path.join(aten_path, "native/tags.yaml") + parsed_yaml = parse_native_yaml(native_yaml_path, tags_yaml_path) + native_functions, backend_indices = ( + parsed_yaml.native_functions, + parsed_yaml.backend_indices, + ) + grouped_native_functions = get_grouped_native_functions(native_functions) + + def sort_native_function(f: NativeFunctionsGroup | NativeFunction) -> str: + """ + We sort the native function because of the note in concat_map_codegen. + TODO(alanwaketan): Remove this sorting hack once all ops are grouped properly. + """ + func = f.functional.func if isinstance(f, NativeFunctionsGroup) else f.func + return str(func.name.name) + + grouped_native_functions = sorted( + grouped_native_functions, key=sort_native_function + ) + + parsed_backend_yaml = parse_backend_yaml( + source_yaml, grouped_native_functions, backend_indices + ) + backend_key = parsed_backend_yaml.backend_key + autograd_key = parsed_backend_yaml.autograd_key + cpp_namespace = parsed_backend_yaml.cpp_namespace + backend_indices = parsed_backend_yaml.backend_indices + # the following 3 keys are all processed differently + # for full_codegen, we generate IR, kernels, etc + # for ir_gen, we generate only IR + # non_native is used to register kernels not declared in + # native_functions.yaml + full_codegen, non_native, ir_gen = parse_native_functions_keys( + source_yaml, grouped_native_functions + ) + + def concat_map_codegen( + func: Callable[[NativeFunction], Sequence[str]], + xs: Iterable[NativeFunctionsGroup | NativeFunction], + ops_list: list[OperatorName] = full_codegen, + ) -> Iterator[str]: + """ + We code-gen for the functional variant, which is all we need for IR classes/lowerings/shape inferences, but we + only code-gen additional entries for the inplace variant for the native functions. + """ + + for x in xs: + fs = list(x.functions()) if isinstance(x, NativeFunctionsGroup) else [x] + for f in fs: + if f.func.name in ops_list: + yield from func(f) + + selector = SelectiveBuilder.get_nop_selector() + + assert backend_key is not None + class_name = backend_indices[backend_key].native_function_class_name() + + if impl_path is not None: + error_on_missing_kernels( + native_functions, + backend_indices, + backend_key, + autograd_key, + class_name, + impl_path, + full_codegen, + ) + + """ Validate Shape Inference Definitions + + Generated lazy native functions all perform shape inference, by first using a meta:: kernel + if available for that op, and otherwise using a 'compute_shape_{op}' function instead. The generator + knows the call signature for compute_shape_{op} because it matches the nativefunction (and meta::) signature, + so it just has to check whether the op is structured and generate a call for one or the other. It's up to the dev + to supply the missing compute_shape_{op} function, but the codegen at least warns you about this and provides + the expected signature which can be copy-pasted into shape_inference.h. + + compute_shape_{op} functions are handwritten and should be replaced over time as ops get ported + to structured kernels. + + See torch/csrc/lazy/core/shape_inference.cpp #READ THIS! for more information. + """ + if shape_inference_hdr is not None: + expected_shape_infr_decls = list( + concat_map_codegen( + dest.GenLazyShapeInferenceDefinition( + backend_indices[backend_key], tensor_class + ), + grouped_native_functions, + ) + ) + + validate_shape_inference_header(shape_inference_hdr, expected_shape_infr_decls) + assert class_name is not None + + # Generate nativefunction declarations + # Note, eager registrations is set to False for the lazy TS backend as another LTC backend + # may want to register their own lazy kernels instead of registering the TS ones. + # The registration will lazily happen when init_ts_backend is called. + gen_dispatchkey_nativefunc_headers( + fm, + class_name, + cpp_namespace, + backend_indices, + grouped_native_functions, + backend_key, + autograd_key, + backend_name, + ) + + # Generate Dispatcher registrations which hook up the nativefunctions + for dispatch_key in ( + [backend_key] if autograd_key is None else [backend_key, autograd_key] + ): + gen_dispatcher_registrations( + fm, + output_dir, + class_name, + backend_indices, + grouped_native_functions, + backend_key, + dispatch_key, + selector, + build_in_tree=build_in_tree, + per_operator_headers=per_operator_headers, + backend_name=backend_name, + eager_registration=False, + ) + + # Generate native function impls that build IR nodes + ns_helper = NamespaceHelper(cpp_namespace) + fm.write_with_template( + f"{backend_key}NativeFunctions.cpp", + "DispatchKeyNativeFunctions.cpp", + lambda: { + "includes": [ + f"#include <{path}>" + for path in [ + tensor_class_hdr, + shape_inference_hdr, + "ATen/Functions.h", + "ATen/native/TensorConversions.h", + "ATen/NativeFunctions.h", + "ATen/CompositeExplicitAutogradNonFunctionalFunctions.h", + "ATen/MetaFunctions.h", + "ATen/Operators.h", + "ATen/native/CPUFallback.h", + "torch/csrc/lazy/core/ir_builder.h", + "torch/csrc/lazy/core/lazy_graph_executor.h", + "torch/csrc/lazy/core/metrics.h", + "torch/csrc/lazy/core/shape.h", + f"{output_dir}/{backend_key}NativeFunctions.h", + f"{output_dir}/LazyIr.h", + ] + + ( + ["torch/csrc/lazy/ts_backend/ts_eager_fallback.h"] + if gen_forced_fallback_code + else [] + ) + ], + "helper_fns": get_ltc_helper_fns(), + "native_functions_include": "", + "namespace_prologue": ns_helper.prologue, + "namespace_epilogue": ns_helper.epilogue, + "native_function_definitions": list( + concat_map_codegen( + native_func_definition_generator( + f"{backend_key}NativeFunctions", + backend_indices[backend_key], + tensor_class, + gen_forced_fallback_code, + backend_namespace, + get_tensorlist, + get_tensor_or_wrap_number, + try_get_tensor, + metrics_counter, + create_tensor, + create_from_first_tensor, + create_aten_from_ltc_tensor, + tuple_aten_from_ltc_tensors, + lazy_tensor_ptr, + get_device_fn, + ), + grouped_native_functions, + ) + ), + }, + ) + # Generate IR node classes + lazy_ir_obj = lazy_ir_generator( + backend_indices[backend_key], backend_name, node_base, use_lazy_shape + ) + + fm.write_with_template( + "LazyIr.h", + "LazyIr.h", + lambda: { + "lazy_ir_sysinc": [ + f"#include <{path}>" + for path in [ + "ATen/core/Formatting.h", + "c10/core/ScalarType.h", + "torch/csrc/lazy/core/hash.h", + "torch/csrc/lazy/core/ir.h", + "torch/csrc/lazy/core/shape.h", + "optional", + "vector", + ] + ], + "lazy_ir_inc": [f'#include "{node_base_hdr}"'] + if node_base_hdr is not None + else [], + "ir_declarations": list( + concat_map_codegen( + lazy_ir_obj, grouped_native_functions, full_codegen + ir_gen + ) + ), + "namespace_prologue": ns_helper.prologue, + "namespace_epilogue": ns_helper.epilogue, + }, + ) + + # Generate Non Native IR Node classes + fm.write_with_template( + "LazyNonNativeIr.h", + "LazyNonNativeIr.h", + lambda: { + "lazy_non_native_ir_inc": [ + f"#include <{path}>" + for path in [ + "torch/csrc/lazy/core/ir.h", + "torch/csrc/lazy/core/ir_builder.h", + "torch/csrc/lazy/core/internal_ops/ltc_ops.h", + "torch/csrc/lazy/core/shape_inference.h", + ] + + ([node_base_hdr] if node_base_hdr else []) + if path + ], + "non_native_ir_nodes": dest.generate_non_native_lazy_ir_nodes( + non_native, lazy_ir_obj + ), + "namespace_prologue": ns_helper.prologue, + "namespace_epilogue": ns_helper.epilogue, + }, + ) + + +if __name__ == "__main__": + main() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/gen_schema_utils.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/gen_schema_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b81c91527baa187467acd5851178106d3e3d4111 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/gen_schema_utils.py @@ -0,0 +1,97 @@ +from typing import Any, Optional, Union + +from torchgen.model import ( + Annotation, + Argument, + Arguments, + BaseOperatorName, + BaseTy, + BaseType, + CustomClassType, + FunctionSchema, + ListType, + OperatorName, + Return, +) + + +# Note: These aren't actually used in torchgen, they're some utilities for generating a schema +# from real arguments. For example, this is used to generate HigherOrderOperators' schema since +# their schemas can vary for different instances of the same HOP. + + +class TypeGen: + convert_to_base_ty = { + int: BaseTy.int, + float: BaseTy.float, + str: BaseTy.str, + bool: BaseTy.bool, + } + + @staticmethod + def from_example(obj: Any) -> Union[BaseType, ListType, CustomClassType]: + import torch + + if isinstance(obj, torch.fx.GraphModule): + return BaseType(BaseTy.GraphModule) + elif isinstance(obj, torch.Tensor): + return BaseType(BaseTy.Tensor) + elif isinstance(obj, torch.SymInt): + return BaseType(BaseTy.SymInt) + elif isinstance(obj, torch.SymBool): + return BaseType(BaseTy.SymBool) + elif isinstance(obj, torch.ScriptObject): + return CustomClassType(obj._type().name()) # type: ignore[attr-defined] + elif isinstance(obj, (list, tuple)): + assert len(obj) > 0 + all_base_tys = [TypeGen.from_example(x) for x in obj] + if len(set(all_base_tys)) > 1: + raise RuntimeError( + f"Cannot generate schema for a sequence of args of heterogeneous types: {all_base_tys}. " + "Consider unpacking the argument and give proper names to them if possible " + "instead of using *args." + ) + return ListType(all_base_tys[0], len(obj)) + tp = type(obj) + if tp not in TypeGen.convert_to_base_ty: + raise RuntimeError(f"unsupported type {tp}") + return BaseType(TypeGen.convert_to_base_ty[tp]) + + +class ReturnGen: + @staticmethod + def from_example( + name: Optional[str], obj: Any, annotation: Optional[Annotation] + ) -> Return: + return Return(name, TypeGen.from_example(obj), annotation) + + +class ArgumentGen: + @staticmethod + def from_example( + name: str, obj: Any, default: Optional[str], annotation: Optional[Annotation] + ) -> Argument: + return Argument( + name, TypeGen.from_example(obj), default=default, annotation=annotation + ) + + +class FunctionSchemaGen: + @staticmethod + def from_example( + op_name: str, + example_inputs: tuple[tuple[str, Any], ...], + example_outputs: tuple[Any, ...], + ) -> FunctionSchema: + args = [] + for name, inp in example_inputs: + args.append(ArgumentGen.from_example(name, inp, None, None)) + # ignore the annotations and other attributes for now, we could add more when needed. + arguments = Arguments( + tuple(), None, tuple(args), tuple(), None, tuple(), tuple() + ) + returns = tuple( + ReturnGen.from_example(None, out, None) for out in example_outputs + ) + op_name = OperatorName(BaseOperatorName(op_name, False, False, False), "") + return FunctionSchema(op_name, arguments, returns) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/gen_vmap_plumbing.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/gen_vmap_plumbing.py new file mode 100644 index 0000000000000000000000000000000000000000..0632e7c4b96985313b9b01297f9f128b07331551 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/gen_vmap_plumbing.py @@ -0,0 +1,275 @@ +from __future__ import annotations + +import textwrap +from dataclasses import dataclass +from typing import TYPE_CHECKING + +from torchgen.api.translate import translate +from torchgen.api.types import DispatcherSignature +from torchgen.context import method_with_native_function +from torchgen.model import ( + Argument, + BaseTy, + BaseType, + FunctionSchema, + ListType, + NativeFunction, + OptionalType, + Return, + SchemaKind, + Type, +) +from torchgen.utils import mapMaybe + + +if TYPE_CHECKING: + from collections.abc import Sequence + + +def is_tensor(typ: Type) -> bool: + return isinstance(typ, BaseType) and typ.name == BaseTy.Tensor + + +def is_optional_tensor(typ: Type) -> bool: + return isinstance(typ, OptionalType) and is_tensor(typ.elem) + + +def is_tensor_list(typ: Type) -> bool: + return isinstance(typ, ListType) and is_tensor(typ.elem) + + +def unwrap_tensor(name: str, cur_level_var: str) -> list[str]: + result = f"""\ + auto [{name}_value, {name}_bdim] = unwrapTensorAtLevel({name}, {cur_level_var});""" + return textwrap.dedent(result).split("\n") + + +def unwrap_optional_tensor(name: str, cur_level_var: str) -> list[str]: + result = f"""\ + std::optional {name}_value; + std::optional {name}_bdim; + if ({name}) {{ + std::tie({name}_value, {name}_bdim) = unwrapTensorAtLevel({name}.value(), {cur_level_var}); + }}""" + return textwrap.dedent(result).split("\n") + + +def gen_unwraps( + flat_arguments: Sequence[Argument], cur_level_var: str +) -> tuple[str, list[str]]: + arg_names = [a.name for a in flat_arguments] + arg_types = [a.type for a in flat_arguments] + + tensors = [name for typ, name in zip(arg_types, arg_names) if is_tensor(typ)] + optional_tensors = [ + name for typ, name in zip(arg_types, arg_names) if is_optional_tensor(typ) + ] + + unwraps = [] + for tensor in tensors: + unwraps += unwrap_tensor(tensor, cur_level_var) + + for opt_tensor in optional_tensors: + unwraps += unwrap_optional_tensor(opt_tensor, cur_level_var) + unwrap_code = "\n".join(unwraps) + + unwrapped_arg_list = [] + for arg in arg_names: + if arg in tensors or arg in optional_tensors: + unwrapped_arg_list += [f"{arg}_value", f"{arg}_bdim"] + else: + unwrapped_arg_list.append(arg) + return unwrap_code, unwrapped_arg_list + + +def gen_case_where_all_bdims_are_none( + outer_sig: DispatcherSignature, schema: FunctionSchema, cur_level_var: str +) -> str: + conditions = [] + flat_args = schema.arguments.flat_all + for arg in flat_args: + if not arg.type.is_tensor_like(): + continue + conditions.append(f"!isBatchedAtLevel({arg.name}, {cur_level_var})") + + sig = DispatcherSignature.from_schema(schema) + translated_args = ", ".join( + e.expr for e in translate(outer_sig.arguments(), sig.arguments()) + ) + return f"""\ +if ({" && ".join(conditions)}) {{ + return at::_ops::{sig.func.name.unambiguous_name()}::call({translated_args}); +}}""" + + +def gen_returns( + returns: tuple[Return, ...], cur_level_var: str, results_var: str +) -> str: + idx = 0 + wrapped_returns = [] + for ret in returns: + if is_tensor(ret.type): + wrapped_returns.append( + f"makeBatched(std::get<{idx}>({results_var}), std::get<{idx + 1}>({results_var}), {cur_level_var})" + ) + idx += 2 + elif is_tensor_list(ret.type): + wrapped_returns.append( + f"makeBatchedVector(std::get<{idx}>({results_var}), std::get<{idx + 1}>({results_var}), {cur_level_var})" + ) + idx += 2 + else: + wrapped_returns.append(f"std::get<{idx}>({results_var})") + idx += 1 + if len(wrapped_returns) == 1: + result = f"return {wrapped_returns[0]};" + else: + result = f"return std::make_tuple({', '.join(wrapped_returns)});" + return result + + +def accepts_at_least_one_tensor_input(schema: FunctionSchema) -> bool: + return any(a.type.is_tensor_like() for a in schema.arguments.flat_all) + + +def is_mutated_arg(argument: Argument) -> bool: + return argument.annotation is not None and argument.annotation.is_write + + +def gen_vmap_inplace_plumbing(native_function: NativeFunction) -> str | None: + # Assumptions: + # - only one argument is being modified in-place + # - the argument that is being modified in-place is the first argument + # - all returns are either Tensor, tuple of Tensor, or TensorList + schema = native_function.func + sig = DispatcherSignature.from_schema(schema) + returns = schema.returns + + # Check assumptions. If these are invalid we return None + # and punt the work to handle them to the future. + assert schema.kind() == SchemaKind.inplace + if not is_mutated_arg(schema.arguments.flat_all[0]): + return None + if not len([arg for arg in schema.arguments.flat_all if is_mutated_arg(arg)]) == 1: + return None + + # Only support cases where all returns are Tensors or vector + if len(returns) == 0: + return None + if not all(is_tensor(ret.type) or is_tensor_list(ret.type) for ret in returns): + return None + if not accepts_at_least_one_tensor_input(schema): + return None + + cur_level_var = "cur_level" + + unwraps, unwrapped_arg_list = gen_unwraps(schema.arguments.flat_all, cur_level_var) + bdims_all_none_case = gen_case_where_all_bdims_are_none(sig, schema, cur_level_var) + + return f"""\ +template +{sig.decl(name=schema.name.unambiguous_name() + "_generated_plumbing")} {{ + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + auto maybe_layer = maybeCurrentDynamicLayer(); + vmap_check_escaped(maybe_layer, "gen_vmap_inplace_plumbing"); + int64_t {cur_level_var} = maybe_layer->layerId(); +{textwrap.indent(bdims_all_none_case, " ")} +{textwrap.indent(unwraps, " ")} + batch_rule({", ".join(unwrapped_arg_list)}); + return {schema.arguments.flat_all[0].name}; +}}""" + + +def gen_vmap_plumbing_no_returns(native_function: NativeFunction) -> str: + schema = native_function.func + sig = DispatcherSignature.from_schema(schema) + cur_level_var = "cur_level" + + unwraps, unwrapped_arg_list = gen_unwraps(schema.arguments.flat_all, cur_level_var) + bdims_all_none_case = gen_case_where_all_bdims_are_none(sig, schema, cur_level_var) + + return f"""\ +template +{sig.decl(name=schema.name.unambiguous_name() + "_generated_plumbing")} {{ + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + auto maybe_layer = maybeCurrentDynamicLayer(); + vmap_check_escaped(maybe_layer, "gen_vmap_plumbing_no_returns"); + int64_t {cur_level_var} = maybe_layer->layerId(); +{textwrap.indent(bdims_all_none_case, " ")} +{textwrap.indent(unwraps, " ")} + batch_rule({", ".join(unwrapped_arg_list)}); +}}""" + + +def gen_vmap_plumbing(native_function: NativeFunction) -> str | None: + schema = native_function.func + sig = DispatcherSignature.from_schema(schema) + returns = schema.returns + + # Only support cases where all returns are Tensors or vector + if not accepts_at_least_one_tensor_input(schema): + return None + if len(returns) == 0: + return gen_vmap_plumbing_no_returns(native_function) + return_symint_overrides = [ + "_scaled_dot_product_flash_attention", + "_scaled_dot_product_cudnn_attention", + ] + if ( + not all(ret.type.is_tensor_like() for ret in returns) + and schema.name.unambiguous_name() not in return_symint_overrides + ): + return None + # in-place views need special handling + if "inplace_view" in native_function.tags: + return None + + if schema.kind() == SchemaKind.inplace: + return gen_vmap_inplace_plumbing(native_function) + + # Don't support these (mutable, out, scratch) + if schema.kind() != SchemaKind.functional: + return None + + results_var = "results" + cur_level_var = "cur_level" + + unwraps, unwrapped_arg_list = gen_unwraps(schema.arguments.flat_all, cur_level_var) + bdims_all_none_case = gen_case_where_all_bdims_are_none(sig, schema, cur_level_var) + + wrapped_returns = gen_returns(returns, cur_level_var, results_var) + return f"""\ +template +{sig.decl(name=schema.name.unambiguous_name() + "_generated_plumbing")} {{ + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + auto maybe_layer = maybeCurrentDynamicLayer(); + vmap_check_escaped(maybe_layer, "gen_vmap_plumbing"); + int64_t {cur_level_var} = maybe_layer->layerId(); +{textwrap.indent(bdims_all_none_case, " ")} +{textwrap.indent(unwraps, " ")} + auto {results_var} = batch_rule({", ".join(unwrapped_arg_list)}); + {wrapped_returns} +}}""" + + +@dataclass(frozen=True) +class ComputeBatchRulePlumbing: + @method_with_native_function + def __call__(self, f: NativeFunction) -> str | None: + result = gen_vmap_plumbing(f) + return result + + +def gen_all_vmap_plumbing(native_functions: Sequence[NativeFunction]) -> str: + body = "\n".join(list(mapMaybe(ComputeBatchRulePlumbing(), native_functions))) + return f""" +#pragma once +#include +#include + +namespace at {{ namespace functorch {{ + +{body} + +}}}} // namespace at::functorch +""" diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/local.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/local.py new file mode 100644 index 0000000000000000000000000000000000000000..8d7016bbfaf67286885ef3e95ec6a3a4af9abf93 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/local.py @@ -0,0 +1,62 @@ +from __future__ import annotations + +import threading +from contextlib import contextmanager +from typing import TYPE_CHECKING + + +if TYPE_CHECKING: + from collections.abc import Iterator + + +# Simple dynamic scoping implementation. The name "parametrize" comes +# from Racket. +# +# WARNING WARNING: LOOKING TO EDIT THIS FILE? Think carefully about +# why you need to add a toggle to the global behavior of code +# generation. The parameters here should really only be used +# for "temporary" situations, where we need to temporarily change +# the codegen in some cases because we cannot conveniently update +# all call sites, and are slated to be eliminated once all call +# sites are eliminated. If you don't have a plan for how to get there, +# DON'T add a new entry here. + + +class Locals(threading.local): + use_const_ref_for_mutable_tensors: bool | None = None + use_ilistref_for_tensor_lists: bool | None = None + + +_locals = Locals() + + +def use_const_ref_for_mutable_tensors() -> bool: + assert _locals.use_const_ref_for_mutable_tensors is not None, ( + "need to initialize local.use_const_ref_for_mutable_tensors with " + "local.parametrize" + ) + return _locals.use_const_ref_for_mutable_tensors + + +def use_ilistref_for_tensor_lists() -> bool: + assert _locals.use_ilistref_for_tensor_lists is not None, ( + "need to initialize local.use_ilistref_for_tensor_lists with local.parametrize" + ) + return _locals.use_ilistref_for_tensor_lists + + +@contextmanager +def parametrize( + *, use_const_ref_for_mutable_tensors: bool, use_ilistref_for_tensor_lists: bool +) -> Iterator[None]: + old_use_const_ref_for_mutable_tensors = _locals.use_const_ref_for_mutable_tensors + old_use_ilistref_for_tensor_lists = _locals.use_ilistref_for_tensor_lists + try: + _locals.use_const_ref_for_mutable_tensors = use_const_ref_for_mutable_tensors + _locals.use_ilistref_for_tensor_lists = use_ilistref_for_tensor_lists + yield + finally: + _locals.use_const_ref_for_mutable_tensors = ( + old_use_const_ref_for_mutable_tensors + ) + _locals.use_ilistref_for_tensor_lists = old_use_ilistref_for_tensor_lists diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/model.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/model.py new file mode 100644 index 0000000000000000000000000000000000000000..826b37863f00b0c6be81b3202c3bf32f0e1eb576 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/model.py @@ -0,0 +1,2885 @@ +from __future__ import annotations + +import dataclasses +import itertools +import re +from dataclasses import dataclass +from enum import auto, Enum +from typing import Callable, Optional, TYPE_CHECKING +from typing_extensions import assert_never + +from torchgen.utils import NamespaceHelper, OrderedSet + + +if TYPE_CHECKING: + from collections.abc import Iterator, Sequence + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# +# DATA MODEL +# +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# +# Some general principles for our data model. +# +# - Stop using C++ data types as the internal data representation +# format. Instead, the internal data structures are centered +# around JIT schema representation. This avoid a big problem +# with the old codegen where we read in all the types from +# native_functions.yaml and then immediately had to retranslate +# them into C++ types. +# +# - More semantic data representation. Instead of representing +# everything as dicts and strings, we define dataclasses for +# every interesting entity the code generation has to deal with. +# These dataclasses have strong semantic invariants: for example, +# we generally require them to roundtrip losslessly into the +# form they were parsed from. These structures are immutable +# and you're expected to populate information once during +# construction. + + +# Represent a source location; used for better error reporting +@dataclass(frozen=True) +class Location: + file: str + line: int + + def __str__(self) -> str: + return f"{self.file}:{self.line}" + + +# Valid values of the 'variants' field in native_functions.yaml +class Variant(Enum): + function = auto() + method = auto() + + +# Default kernel namespace +DEFAULT_KERNEL_NAMESPACE = "at::native" + +# NOTE: Keep the list in sync with `DispatchKey` in c10/core/DispatchKey.h +BACKEND_COMPONENTS = "CPU CUDA HIP XLA MTIA MPS IPU XPU HPU VE Lazy Meta PrivateUse1 PrivateUse2 PrivateUse3".split() +FUNCTIONALITY_KEYS = [ + "", + "Quantized", + "Sparse", + "SparseCsr", + "NestedTensor", + "Autograd", +] + +# This list guards dispatches that can be used in derivatives.yaml +# For now we omit AutogradFunctionality and AutogradOther +AUTOGRAD_KEYS = ["AutogradNestedTensor"] + [ + "Autograd" + component for component in BACKEND_COMPONENTS +] + +FRAGMENT_NAMESPACES = {"quantized", "quantized_decomposed"} + + +# This doesn't have to be in sync with the header, it only needs to contain +# entries that we actually use in the codegen or want pyi entries for +class DispatchKey(Enum): + Undefined = 0 + CatchAll = Undefined + + FPGA = auto() + MAIA = auto() + Vulkan = auto() + Metal = auto() + MKLDNN = auto() + OpenGL = auto() + OpenCL = auto() + IDEEP = auto() + CustomRNGKeyId = auto() + MkldnnCPU = auto() + Sparse = auto() + SparseCsr = auto() + NestedTensor = auto() + Dense = auto() + + PythonTLSSnapshot = auto() + PreDispatch = auto() + PythonDispatcher = auto() + Python = auto() + FuncTorchDynamicLayerBackMode = auto() + ZeroTensor = auto() + Conjugate = auto() + Negative = auto() + BackendSelect = auto() + Named = auto() + AutogradOther = auto() + AutogradFunctionality = auto() + AutogradNestedTensor = auto() + Tracer = auto() + Autocast = auto() + AutocastCPU = auto() + AutocastCUDA = auto() + Batched = auto() + VmapMode = auto() + FuncTorchGradWrapper = auto() + FuncTorchBatched = auto() + BatchedNestedTensor = auto() + FuncTorchVmapMode = auto() + FuncTorchDynamicLayerFrontMode = auto() + Functionalize = auto() + TESTING_ONLY_GenericWrapper = auto() + TESTING_ONLY_GenericMode = auto() + + ADInplaceOrView = auto() + Autograd = auto() + CompositeImplicitAutograd = auto() + CompositeImplicitAutogradNestedTensor = auto() + CompositeExplicitAutograd = auto() + CompositeExplicitAutogradNonFunctional = auto() + FuncTorchBatchedDecomposition = auto() + + # BEGIN autogenerated + CPU = auto() + CUDA = auto() + HIP = auto() + XLA = auto() + MTIA = auto() + MPS = auto() + IPU = auto() + XPU = auto() + HPU = auto() + VE = auto() + Lazy = auto() + Meta = auto() + PrivateUse1 = auto() + PrivateUse2 = auto() + PrivateUse3 = auto() + QuantizedCPU = auto() + QuantizedCUDA = auto() + QuantizedHIP = auto() + QuantizedXLA = auto() + QuantizedMTIA = auto() + QuantizedMPS = auto() + QuantizedIPU = auto() + QuantizedXPU = auto() + QuantizedHPU = auto() + QuantizedVE = auto() + QuantizedLazy = auto() + QuantizedMeta = auto() + QuantizedPrivateUse1 = auto() + QuantizedPrivateUse2 = auto() + QuantizedPrivateUse3 = auto() + SparseCPU = auto() + SparseCUDA = auto() + SparseHIP = auto() + SparseXLA = auto() + SparseMTIA = auto() + SparseMPS = auto() + SparseIPU = auto() + SparseXPU = auto() + SparseHPU = auto() + SparseVE = auto() + SparseLazy = auto() + SparseMeta = auto() + SparsePrivateUse1 = auto() + SparsePrivateUse2 = auto() + SparsePrivateUse3 = auto() + SparseCsrCPU = auto() + SparseCsrCUDA = auto() + SparseCsrHIP = auto() + SparseCsrXLA = auto() + SparseCsrMTIA = auto() + SparseCsrMPS = auto() + SparseCsrIPU = auto() + SparseCsrXPU = auto() + SparseCsrHPU = auto() + SparseCsrVE = auto() + SparseCsrLazy = auto() + SparseCsrMeta = auto() + SparseCsrPrivateUse1 = auto() + SparseCsrPrivateUse2 = auto() + SparseCsrPrivateUse3 = auto() + NestedTensorCPU = auto() + NestedTensorCUDA = auto() + NestedTensorHIP = auto() + NestedTensorXLA = auto() + NestedTensorMTIA = auto() + NestedTensorMPS = auto() + NestedTensorIPU = auto() + NestedTensorXPU = auto() + NestedTensorHPU = auto() + NestedTensorVE = auto() + NestedTensorLazy = auto() + NestedTensorMeta = auto() + NestedTensorPrivateUse1 = auto() + NestedTensorPrivateUse2 = auto() + NestedTensorPrivateUse3 = auto() + AutogradCPU = auto() + AutogradCUDA = auto() + AutogradHIP = auto() + AutogradXLA = auto() + AutogradMTIA = auto() + AutogradMPS = auto() + AutogradIPU = auto() + AutogradXPU = auto() + AutogradHPU = auto() + AutogradVE = auto() + AutogradLazy = auto() + AutogradMeta = auto() + AutogradPrivateUse1 = auto() + AutogradPrivateUse2 = auto() + AutogradPrivateUse3 = auto() + # END autogenerated + + def __str__(self) -> str: + return self.name + + def lower(self) -> str: + return str(self).lower() + + @staticmethod + def parse(value: str) -> DispatchKey: + for k, v in DispatchKey.__members__.items(): + if k == value: + return v + raise AssertionError(f"unknown dispatch key {value}") + + +class _TorchDispatchModeKey(Enum): + FAKE = auto() + PROXY = auto() + FUNCTIONAL = auto() + + +def codegen_per_backend_entries() -> str: + r: list[str] = [] + for fk in FUNCTIONALITY_KEYS: + r.extend(f" {fk}{bc} = auto()" for bc in BACKEND_COMPONENTS) + return "\n".join(r) + + +for fk in FUNCTIONALITY_KEYS: + for bc in BACKEND_COMPONENTS: + if not hasattr(DispatchKey, fk + bc): + r = codegen_per_backend_entries() + print(r) + raise RuntimeError( + f"Missing {fk}{bc} from DispatchKey enum. Here is the autogenerated list we expect to have:\n\n{r}" + ) + + +STRUCTURED_DISPATCH_KEYS = { + DispatchKey.MPS, + DispatchKey.CUDA, + DispatchKey.CPU, + DispatchKey.XPU, + DispatchKey.MTIA, +} +UFUNC_DISPATCH_KEYS = {DispatchKey.CUDA, DispatchKey.CPU} + +# Set of supported dispatch keys +dispatch_keys = [ + DispatchKey.CPU, + DispatchKey.SparseCPU, + DispatchKey.SparseCsrCPU, + DispatchKey.MkldnnCPU, + DispatchKey.CUDA, + DispatchKey.MPS, + DispatchKey.XPU, + DispatchKey.SparseXPU, + DispatchKey.SparseCsrXPU, + DispatchKey.SparseCUDA, + DispatchKey.SparseCsrCUDA, + DispatchKey.QuantizedCPU, + DispatchKey.QuantizedCUDA, + DispatchKey.CompositeImplicitAutograd, + DispatchKey.CompositeImplicitAutogradNestedTensor, + DispatchKey.CompositeExplicitAutograd, + DispatchKey.CompositeExplicitAutogradNonFunctional, + DispatchKey.NestedTensorCPU, + DispatchKey.NestedTensorCUDA, + DispatchKey.NestedTensorXPU, + DispatchKey.NestedTensorHPU, + # Meta is a magic key: it is automatically generated for structured + # kernels + DispatchKey.Meta, + DispatchKey.SparseMeta, + DispatchKey.SparseCsrMeta, + DispatchKey.QuantizedMeta, + DispatchKey.NestedTensorMeta, + DispatchKey.ZeroTensor, + DispatchKey.MTIA, +] + + +# Dispatch keys that "support all backends". These codegen slightly differently +# then backend specific keys. +def is_generic_dispatch_key(dk: DispatchKey) -> bool: + return dk in { + DispatchKey.CompositeExplicitAutograd, + DispatchKey.CompositeExplicitAutogradNonFunctional, + DispatchKey.CompositeImplicitAutograd, + DispatchKey.CompositeImplicitAutogradNestedTensor, + } + + +# CUDA specific dispatch keys +def is_cuda_dispatch_key(dk: DispatchKey) -> bool: + return dk in { + DispatchKey.CUDA, + DispatchKey.QuantizedCUDA, + DispatchKey.SparseCUDA, + DispatchKey.SparseCsrCUDA, + DispatchKey.NestedTensorCUDA, + DispatchKey.AutogradCUDA, + } + + +# XPU specific dispatcy keys +def is_xpu_dispatch_key(dk: DispatchKey) -> bool: + return dk in { + DispatchKey.XPU, + DispatchKey.QuantizedXPU, + DispatchKey.SparseXPU, + DispatchKey.SparseCsrXPU, + DispatchKey.NestedTensorXPU, + DispatchKey.AutogradXPU, + } + + +# Structured kernel generation is only supported for certain key types; +# otherwise use old-style +def is_structured_dispatch_key(dk: DispatchKey) -> bool: + return dk in STRUCTURED_DISPATCH_KEYS + + +def is_ufunc_dispatch_key(dk: DispatchKey) -> bool: + # For now, ufunc dispatch keys coincide with structured keys + return dk in UFUNC_DISPATCH_KEYS + + +dispatch_device_map = {is_cuda_dispatch_key: "cuda", is_xpu_dispatch_key: "xpu"} + + +# This is oddly named ScalarType and not DType for symmetry with C++ +class ScalarType(Enum): + Byte = auto() + Char = auto() + Short = auto() + Int = auto() + Long = auto() + Half = auto() + Float = auto() + Double = auto() + ComplexHalf = auto() + ComplexFloat = auto() + ComplexDouble = auto() + Bool = auto() + BFloat16 = auto() + Float8_e5m2 = auto() + Float8_e5m2fnuz = auto() + Float8_e4m3fn = auto() + Float8_e4m3fnuz = auto() + Float8_e8m0fnu = auto() + + def __str__(self) -> str: + return self.name + + @staticmethod + def maybe_parse(value: str) -> ScalarType | None: + for k, v in ScalarType.__members__.items(): + if k == value: + return v + return None + + @staticmethod + def parse(value: str) -> ScalarType: + mb_r = ScalarType.maybe_parse(value) + assert mb_r is not None, f"unknown dtype {value}" + return mb_r + + @staticmethod + def parse_set(values: str) -> OrderedSet[ScalarType]: + dtypes: OrderedSet[ScalarType] = OrderedSet() + for value in values.split(", "): + if value in DTYPE_CLASSES: + dtypes.update(DTYPE_CLASSES[value]) + else: + dtypes.add(ScalarType.parse(value)) + return dtypes + + +DTYPE_CLASSES: dict[str, OrderedSet[ScalarType]] = {} +# NB: Integral doesn't include boolean +DTYPE_CLASSES["Integral"] = OrderedSet( + [ + ScalarType.Byte, + ScalarType.Char, + ScalarType.Int, + ScalarType.Long, + ScalarType.Short, + ] +) +# NB: Floating doesn't include low precision types +DTYPE_CLASSES["Floating"] = OrderedSet([ScalarType.Float, ScalarType.Double]) +DTYPE_CLASSES["Complex"] = OrderedSet( + [ScalarType.ComplexFloat, ScalarType.ComplexDouble] +) +DTYPE_CLASSES["All"] = DTYPE_CLASSES["Integral"] | DTYPE_CLASSES["Floating"] +DTYPE_CLASSES["AllAndComplex"] = DTYPE_CLASSES["All"] | DTYPE_CLASSES["Complex"] +DTYPE_CLASSES["FloatingAndComplex"] = ( + DTYPE_CLASSES["Floating"] | DTYPE_CLASSES["Complex"] +) + + +# Represents the valid entries for ufunc_inner_loop in native_functions.yaml. +# NB: if you add a new UfuncKey, you will teach torchgen.dest.ufunc how +# to process it. Most logic will ignore keys they don't understand, so your +# new key will get silently ignored until you hook in logic to deal with it. +class UfuncKey(Enum): + # These are low level keys that represent exactly one particular + # instantiation of the kernel produced by codegen + CUDAFunctor = auto() + CUDAFunctorOnOther = auto() + CUDAFunctorOnSelf = auto() + + CPUScalar = auto() + CPUVector = auto() + + # These are the ones users will usually specify, and + # implicitly "fill in" the low level keys + ScalarOnly = auto() # CUDA*, CPUScalar + Generic = auto() # CUDA*, CPU* + + def __str__(self) -> str: + return self.name + + @staticmethod + def parse(value: str) -> UfuncKey: + for k, v in UfuncKey.__members__.items(): + if k == value: + return v + raise AssertionError(f"unknown ufunc key {value}") + + +class DeviceCheckType(Enum): + NoCheck = 0 + ExactSame = 1 + + +class ViewSchemaKind(Enum): + aliasing = auto() + aliasing_inplace = auto() + non_aliasing = auto() + + +# The basic input to the code generation is native_functions.yaml. +# The name "native", BTW, comes from the distinction between native +# functions and legacy TH functions. The legacy TH functions are gone, +# but the "native" descriptor has stuck. +# +# NativeFunction models a single entry in native_functions.yaml. Its +# fields roughly correspond to what you would see in the YAML itself, +# but after canonicalization and parsing has occurred. +# +# You can see some of the overall design patterns for how we setup +# dataclasses in this class, but we will defer a complete discussion +# of this at FunctionSchema. +@dataclass(frozen=True) +class NativeFunction: + # The namespace for this operator. For example, if we have "at::add" + # then the namespace would be "at". This enables ops to be registered + # through the same DSL with a custom namespace. If not specified, the + # default namespace would be "at". + namespace: str + + # The function schema of the operator in question. This schema + # has been parsed; see FunctionSchema for more about its structure. + # (This type is quoted as we are forward referencing a type + # defined later in the file. I opted for this ordering of the + # classes for expository clarity.) + func: FunctionSchema + + # Whether or not to generate mutable tensor arguments like regular + # ones + use_const_ref_for_mutable_tensors: bool + + # Whether or not to omit automatic generation of a DeviceGuard + device_guard: bool + + # How to emit automatic generation of device check + device_check: DeviceCheckType + + # What python module to put the function in + python_module: str | None + + # TODO: figure out what this does + category_override: str | None + + # If no variants are specified in native_functions.yaml, this is + # assumed to be {'function'}. + variants: set[Variant] + + # Whether or not we should skip generating registrations for + # this kernel. This is a bit of a double-edged sword, as manual + # registrations don't participate in codegen-based selective build! + manual_kernel_registration: bool + + # Whether or not to skip generating TensorMethod/Functions bindings + # for this kernel. Technically, this doesn't actually skip generating + # the binding; instead, the binding gets generated to __dispatch_{funcname} + # so you can make use of the normal binding if you need it. + manual_cpp_binding: bool + + # The location in the YAML file were this native function entry was + # defined. This is for conveniently reporting error messages! + loc: Location + + # A list of operators that are expected to be auto-generated for this NativeFunction. + # Note: This list isn't actually directly used by the codegen to generate anything. + # Instead, the codegen figures out what operators to generate purely based off of + # function schema, and uses the autogen declarations to error check. + # We expect every NativeFunction that gets auto-generated be explicitly called out + # in native_functions.yaml + autogen: list[OperatorName] + + # If non-empty, this kernel is subject to ufunc codegen. + # Sorted by ufunc_key + ufunc_inner_loop: dict[UfuncKey, UfuncInnerLoop] + + # Whether or not this out functions is a "structured kernel". Structured + # kernels are defined a little differently from normal kernels; in + # particular, their shape checking logic is defined separately from + # the kernel. Only out functions can be structured; other functions + # delegate to the out function using the structured_delegate keyword. + # Every structured kernel must have at least an out and a functional + # variant. + structured: bool + + # Whether or not this non-out function is a structured kernel, defined + # in terms of the out kernel referenced by the string here. + structured_delegate: OperatorName | None + + # Only valid for structured kernels. Specifies alternative of what + # to inherit from when defining the meta class for the structured + # operator. This will usually be TensorIteratorBase. This also + # changes the semantics of set_output to call the parent class. + structured_inherits: str | None + + # Structured kernels can declare elements as "precomputed". These elements + # are returned by the meta function in one struct and passed to the impl + # function in lieu of certain kernel arguments that these precomputed + # elements supersede. Information about the names and types of these + # precomputed elements and how they correspond to kernel arguments is stored + # in this member, if applicable. + precomputed: Precompute | None + + # Argument names whose default should be excluded from the C++ interface. + # Intended for resolving overload ambiguities between signatures. + cpp_no_default_args: set[str] + + # Note [Abstract ATen methods] + # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + # An abstract ATen method is one whose dispatch differs between + # types. These are implemented in derived types (with a + # standard (throwing) definition in Type). A concrete ATen + # method is one which has the same dispatch for all types; + # we just implement it in the base Type. This is exposed + # in Declarations.yaml via a field named 'abstract'. + is_abstract: bool + + # Whether or not the NativeFunction contains a backend-agnostic kernel + has_composite_implicit_autograd_kernel: bool + has_composite_implicit_autograd_nested_tensor_kernel: bool + has_composite_explicit_autograd_kernel: bool + has_composite_explicit_autograd_non_functional_kernel: bool + + # Tags are used to describe semantic information about (groups of) operators, + # That aren't easily inferable directly from the operator's schema. + tags: set[str] + + # NB: The benefit of defining a dataclass is that we automatically get + # a constructor defined for all the fields we specify. No need + # to explicitly write it out. + + # We parse both the NativeFunction + backend-specific information about it, which it stored in a corresponding BackendIndex. + @staticmethod + def from_yaml( + ei: dict[str, object], + loc: Location, + valid_tags: set[str], + ignore_keys: set[DispatchKey] | None = None, + ) -> tuple[NativeFunction, dict[DispatchKey, dict[OperatorName, BackendMetadata]]]: + """ + Parse a NativeFunction from a dictionary as directly parsed + from native_functions.yaml + """ + e = ei.copy() + + funcs = e.pop("func") + assert isinstance(funcs, str), f"not a str: {funcs}" + # only support one level of namespace. E.g., aten::add + namespace_helper = NamespaceHelper.from_namespaced_entity( + namespaced_entity=funcs, max_level=1 + ) + namespace = namespace_helper.get_cpp_namespace(default="aten") + func = FunctionSchema.parse(namespace_helper.entity_name) + + cpp_no_default_args_list = e.pop("cpp_no_default_args", []) + assert isinstance(cpp_no_default_args_list, list) + cpp_no_default_args = set(cpp_no_default_args_list) + + use_const_ref_for_mutable_tensors = e.pop( + "use_const_ref_for_mutable_tensors", False + ) + assert isinstance(use_const_ref_for_mutable_tensors, bool) + + if use_const_ref_for_mutable_tensors: + assert not func.arguments.out, ( + "see https://github.com/pytorch/pytorch/issues/145522" + ) + + variants_s = e.pop("variants", "function") + assert isinstance(variants_s, str) + variants: set[Variant] = set() + for v in variants_s.split(", "): + if v == "function": + variants.add(Variant.function) + elif v == "method": + variants.add(Variant.method) + else: + raise AssertionError(f"illegal variant {v}") + + manual_kernel_registration = e.pop("manual_kernel_registration", False) + assert isinstance(manual_kernel_registration, bool), ( + f"not a bool: {manual_kernel_registration}" + ) + + manual_cpp_binding = e.pop("manual_cpp_binding", False) + assert isinstance(manual_cpp_binding, bool), f"not a bool: {manual_cpp_binding}" + + device_guard = e.pop("device_guard", True) + assert isinstance(device_guard, bool), f"not a bool: {device_guard}" + + device_check_s = e.pop("device_check", None) + assert device_check_s is None or isinstance(device_check_s, str), ( + f"not a str: {device_check_s}" + ) + assert ( + device_check_s is None or device_check_s in DeviceCheckType.__members__ + ), f"illegal device_check: {device_check_s}" + device_check: DeviceCheckType + if device_check_s is None: + device_check = DeviceCheckType.ExactSame + else: + device_check = DeviceCheckType[device_check_s] + + structured = e.pop("structured", False) + assert isinstance(structured, bool), f"not a bool: {structured}" + + structured_delegate_s = e.pop("structured_delegate", None) + assert structured_delegate_s is None or isinstance( + structured_delegate_s, str + ), f"not a str: {structured_delegate_s}" + assert structured_delegate_s is None or "::" not in structured_delegate_s, ( + "namespace is not supported in structured delegate," + " using the same namespace as the native function" + ) + structured_delegate: OperatorName | None = None + if structured_delegate_s is not None: + structured_delegate = OperatorName.parse(structured_delegate_s) + + structured_inherits = e.pop("structured_inherits", None) + assert structured_inherits is None or isinstance(structured_inherits, str), ( + f"not a str: {structured_inherits}" + ) + assert structured_inherits is None or "::" not in structured_inherits, ( + "namespace is not supported in structured inherits," + " using the same namespace as the native function" + ) + + python_module = e.pop("python_module", None) + assert python_module is None or isinstance(python_module, str), ( + f"not a str: {python_module}" + ) + assert python_module is None or Variant.method not in variants, ( + "functions in modules cannot be methods" + ) + + category_override = e.pop("category_override", None) + assert category_override is None or isinstance(category_override, str), ( + f"not a str: {category_override}" + ) + + precomputed_dict = e.pop("precomputed", None) + assert precomputed_dict is None or structured is True + precomputed = Precompute.parse(precomputed_dict) if precomputed_dict else None + + tags_inp = e.pop("tags", []) + if isinstance(tags_inp, str): + tags_inp = [tags_inp] + assert isinstance(tags_inp, list) + + # All aten ops generated by torchgen receive the pt2_compliant tag. + if namespace == "aten" and "pt2_compliant_tag" in valid_tags: + tags_inp.append("pt2_compliant_tag") + + tags: set[str] = set() + for t in tags_inp: + assert len(valid_tags) > 0 + # TODO: verify that the tag is valid and has an entry in tags.yaml + if t in valid_tags: + tags.add(t) + else: + raise AssertionError(f"illegal tag {t}") + + from torchgen.api import cpp + + raw_dispatch = e.pop("dispatch", None) + assert raw_dispatch is None or isinstance(raw_dispatch, dict), e + dispatch: dict[DispatchKey, BackendMetadata] = {} + num_dispatch_keys: int = 0 + if raw_dispatch is not None: + assert not manual_kernel_registration, ( + "cannot specify both manual_kernel_registration and dispatch; with " + "manual registration, dispatch has no effect!" + ) + redundant_composite_implicit_autograd = False + for ks, v in raw_dispatch.items(): + if ks == "__line__": + continue # not worth tracking line numbers for dispatch entries + assert isinstance(ks, str), ( + f"illegal dispatch key '{ks}' in {raw_dispatch}" + ) + assert isinstance(v, str), ( + f"illegal dispatch value '{v}' in {raw_dispatch}" + ) + for k in ks.split(","): + dispatch_key = DispatchKey.parse(k.strip()) + num_dispatch_keys += 1 + + if ignore_keys and dispatch_key in ignore_keys: + continue + assert dispatch_key in dispatch_keys, ( + f"Dispatch key {dispatch_key} of kernel {v} " + "is not a supported dispatch key." + ) + # We only allow at most 3 levels of namespace for kernels. + # We will append "native" to a custom kernel namespace. + namespace_helper = NamespaceHelper.from_namespaced_entity( + v, max_level=3 + ) + kernel_namespace = namespace_helper.get_cpp_namespace(default="at") + # Why is 'structured' included? External backends (e.g. + # XLA) opt into which ops are structured independently + # of which in-tree ops are structured + dispatch[dispatch_key] = BackendMetadata( + kernel=namespace_helper.entity_name, + structured=structured + and is_structured_dispatch_key(dispatch_key), + cpp_namespace=(kernel_namespace + "::native"), + ) + if ( + dispatch_key is DispatchKey.CompositeImplicitAutograd + and v == cpp.name(func) + ): + redundant_composite_implicit_autograd = True + + # We count the number of dispatch keys which have not been ignored to prevent a dispatch table + # in which all backend keys are ignored but necessarily kept, remaining compositeimplicit, + # from being treated as redundant. + assert not ( + num_dispatch_keys == 1 and redundant_composite_implicit_autograd + ), ( + "unnecessary dispatch table for this function; just delete the dispatch " + "key entirely" + ) + # if a function is a structured delegate, deleting the dispatch + # table is NOT semantics preserving + assert ( + structured_delegate + or dispatch.keys() != {DispatchKey.CompositeImplicitAutograd} + or dispatch[DispatchKey.CompositeImplicitAutograd].supports_symint() + or num_dispatch_keys != 1 + ), ( + f"unexpected name for singleton CompositeImplicitAutograd dispatch entry: expected {cpp.name(func)} " + f"but got {dispatch[DispatchKey.CompositeImplicitAutograd]}. Rename your implementation to the expected " + "name, then delete the dispatch table" + ) + elif not structured and structured_delegate is None: + name = str(func.name.name) + assert not ( + name.startswith("new_") + or name.endswith("_like") + # TODO: maybe it's better to test the return + or ( + func.arguments.tensor_options + and not func.arguments.has_tensor_arg() + ) + ), ( + f"expected {name} to have a CompositeExplicitAutograd " + "dispatch entry, but there was no dispatch table. Factory functions " + "should not have implicit dispatch as they should not be decomposed " + "for __torch_dispatch__" + ) + dispatch[DispatchKey.CompositeImplicitAutograd] = BackendMetadata( + cpp.name(func), structured=False, cpp_namespace=DEFAULT_KERNEL_NAMESPACE + ) + + composites_in_dispatch = [ + d + for d in dispatch + if d == DispatchKey.CompositeExplicitAutograd + or d == DispatchKey.CompositeExplicitAutogradNonFunctional + or d == DispatchKey.CompositeImplicitAutograd + or d == DispatchKey.CompositeImplicitAutogradNestedTensor + ] + + assert len(composites_in_dispatch) <= 1 or ( + len(composites_in_dispatch) == 2 + and ( + DispatchKey.CompositeExplicitAutogradNonFunctional + not in composites_in_dispatch + ) + and ( + DispatchKey.CompositeImplicitAutogradNestedTensor + in composites_in_dispatch + ) + ), ( + "cannot specify more than one of CompositeExplicitAutograd, CompositeExplicitAutogradNonFunctional, " + "or CompositeImplicitAutograd on a single kernel; each " + "strictly subsumes the other. If you wanted to provide an explicit autograd " + "implementation, specify CompositeExplicitAutograd; otherwise specify CompositeImplicitAutograd only" + ) + + autogen_str = e.pop("autogen", "") + assert isinstance(autogen_str, str) + autogen = ( + [] + if autogen_str == "" + else [OperatorName.parse(x) for x in autogen_str.split(", ")] + ) + + raw_ufunc_inner_loop = e.pop("ufunc_inner_loop", {}) + ufunc_inner_loop = {} + if isinstance(raw_ufunc_inner_loop, str): + ufunc_inner_loop[UfuncKey.Generic] = UfuncInnerLoop.parse( + raw_ufunc_inner_loop, UfuncKey.Generic + ) + elif isinstance(raw_ufunc_inner_loop, dict): + for k, vo in raw_ufunc_inner_loop.items(): + if k == "__line__": + continue + assert isinstance(k, str), f"ufunc_inner_loop key is not a str: {k}" + assert isinstance(vo, str), f"ufunc_inner_loop value is not a str: {v}" + ufunc_key = UfuncKey.parse(k) + ufunc_inner_loop[ufunc_key] = UfuncInnerLoop.parse(vo, ufunc_key) + else: + raise AssertionError( + f"ufunc_inner_loop not str or dict: {raw_ufunc_inner_loop}" + ) + # Program the BackendIndex for the implicit dispatch entry from ufunc + if ufunc_inner_loop: + assert structured, "ufunc must be structured" + + # Delay import ufunc here to avoid circular import issue + # See: https://github.com/pytorch/pytorch/issues/81294 + import torchgen.api.ufunc as ufunc + + for dispatch_key in UFUNC_DISPATCH_KEYS: + assert dispatch_key not in dispatch, ( + f"ufunc should not have explicit dispatch entry for {dispatch_key}" + ) + dispatch[dispatch_key] = BackendMetadata( + kernel=ufunc.schema_kernel_name(func, dispatch_key), + structured=True, + cpp_namespace=DEFAULT_KERNEL_NAMESPACE, + ) + + if structured_delegate: + # Structured functions MUST have a dispatch table + is_abstract = True + else: + is_abstract = ( + dispatch.keys() != {DispatchKey.CompositeImplicitAutograd} + and dispatch.keys() + != {DispatchKey.CompositeImplicitAutogradNestedTensor} + and dispatch.keys() + != { + DispatchKey.CompositeImplicitAutograd, + DispatchKey.CompositeImplicitAutogradNestedTensor, + } + ) + + has_composite_implicit_autograd_kernel = ( + DispatchKey.CompositeImplicitAutograd in dispatch + ) + has_composite_implicit_autograd_nested_tensor_kernel = ( + DispatchKey.CompositeImplicitAutogradNestedTensor in dispatch + ) + has_composite_explicit_autograd_kernel = ( + DispatchKey.CompositeExplicitAutograd in dispatch + ) + has_composite_explicit_autograd_non_functional_kernel = ( + DispatchKey.CompositeExplicitAutogradNonFunctional in dispatch + ) + + # We aren't going to store dispatch metadata inline in NativeFunctions; + # instead it is separately indexed by backend (so other backends can + # add more dispatch entries after the fact). Reindex the individual + # metadata by OperatorName! + backend_metadata = {k: {func.name: v} for k, v in dispatch.items()} + + # don't care if it exists or not; make it easier to use this function + # with other yaml parsers that aren't setting __line__ in the dict + e.pop("__line__", None) + assert not e, f"leftover entries: {e}" + + # Asserts that we can't do in post_init, because they rely on backend-specific info + if structured_delegate is not None: + for key in STRUCTURED_DISPATCH_KEYS: + assert key not in dispatch, ( + f"if structured_delegate, then must not have {key} in dispatch dictionary " + "(it is delegated!)" + ) + + return ( + NativeFunction( + func=func, + use_const_ref_for_mutable_tensors=use_const_ref_for_mutable_tensors, + variants=variants, + structured=structured, + structured_delegate=structured_delegate, + structured_inherits=structured_inherits, + precomputed=precomputed, + autogen=autogen, + ufunc_inner_loop=ufunc_inner_loop, + manual_kernel_registration=manual_kernel_registration, + manual_cpp_binding=manual_cpp_binding, + python_module=python_module, + category_override=category_override, + device_guard=device_guard, + device_check=device_check, + loc=loc, + cpp_no_default_args=cpp_no_default_args, + is_abstract=is_abstract, + has_composite_implicit_autograd_kernel=has_composite_implicit_autograd_kernel, + has_composite_implicit_autograd_nested_tensor_kernel=has_composite_implicit_autograd_nested_tensor_kernel, + has_composite_explicit_autograd_kernel=has_composite_explicit_autograd_kernel, + has_composite_explicit_autograd_non_functional_kernel=has_composite_explicit_autograd_non_functional_kernel, + tags=tags, + namespace=namespace, + ), + backend_metadata, + ) + + def validate_unstructured(self) -> None: + # TODO: probably better to accumulate these errors and report them all + # at once + assert not self.structured, ( + "This function is structured, but there was " + "no valid functional variant of it." + ) + assert self.structured_delegate, ( + "This function delegates to another structured out function, " + "but no valid function was found (the delegate may not exist, or it has the wrong type)" + ) + + # __post_init__ functions in dataclasses can be used to do extra + # validation after construction. + # + # Notice that we don't do any type validation here. In fact, we + # rely exclusively on mypy to check if you've done types correctly! + # Validation is for nontrivial invariants that cannot be (conveniently) + # encoded in the type system. + def __post_init__(self) -> None: + if self.func.arguments.out: + assert self.variants == {Variant.function}, ( + "Native functions with out arguments MUST " + "be declared with only function variant; e.g., variants: function; " + "otherwise you will tickle a Python argument binding bug " + "(which usually manifests itself as the result variable being undefined.)" + ) + if self.structured: + assert self.func.kind() == SchemaKind.out, ( + "Put structured field on the out= " + "variant of a function; did you mean structured_delegate?" + ) + assert self.device_guard, ( + "device_guard: False is not respected by structured kernels" + ) + if self.structured_delegate: + assert self.func.kind() != SchemaKind.out, ( + "structured_delegate field not allowed " + "on out= functions; did you mean structured?" + ) + assert self.device_guard, ( + "device_guard: False is not respected by structured kernels" + ) + # Technically, with the asserts above, this assert is impossible to + # happen + assert not (self.structured and self.structured_delegate), ( + "Cannot have both structured and structured_delegate on function" + ) + defaulted_arguments = { + a.name for a in self.func.schema_order_arguments() if a.default is not None + } + invalid_args = set.difference(self.cpp_no_default_args, defaulted_arguments) + assert len(invalid_args) == 0, f"Invalid cpp_no_default_args: {invalid_args}" + if self.structured_inherits is not None: + assert self.structured, ( + "structured_inherits must also imply structured: True" + ) + if str(self.func.name).startswith("_foreach"): + assert self.device_check == DeviceCheckType.NoCheck, ( + "foreach kernels fall back to slow path when tensor are on different devices, " + "device_check not allowed to be enabled" + ) + + # NB: if your function accidentally has rand/dropout/... in its name + # but is not actually random, feel free to amend this to special case + if ( + "rand" in str(self.func.name) + or ( + ( + "dropout" in str(self.func.name) + or any( + "dropout" in arg.name for arg in self.func.arguments.flat_all + ) + ) + # Backwards of dropout is typically deterministic + and "backward" not in str(self.func.name) + and str(self.func.name.name) not in ["_cudnn_init_dropout_state"] + ) + or self.func.arguments.has_generator_arg() + ): + assert "nondeterministic_seeded" in self.tags, str(self.func.name) + + @property + def has_composite_kernel(self) -> bool: + return ( + self.has_composite_implicit_autograd_kernel + or self.has_composite_explicit_autograd_kernel + or self.has_composite_explicit_autograd_non_functional_kernel + ) or ( + self.has_composite_implicit_autograd_kernel + and self.has_composite_implicit_autograd_nested_tensor_kernel + ) + + @property + def is_view_op(self) -> bool: + rets = self.func.returns + is_non_mutating_view = len(rets) > 0 and any( + r.annotation is not None and not r.annotation.is_write for r in rets + ) + # See Note [resize_ in Functionalization] for more dtails + is_inplace_view = ( + "inplace_view" in self.tags + and str(self.func.name) != "resize_" + and str(self.func.name) != "resize_as_" + ) + is_wildcard_view = any( + inp.annotation is not None and "*" in inp.annotation.alias_set_after + for inp in self.func.schema_order_arguments() + ) + return is_non_mutating_view or is_inplace_view or is_wildcard_view + + @property + def view_schema_kind(self) -> ViewSchemaKind: + if self.is_view_op and self.func.name.name.inplace: + assert "inplace_view" in self.tags + return ViewSchemaKind.aliasing_inplace + if self.is_view_op: + return ViewSchemaKind.aliasing + else: + return ViewSchemaKind.non_aliasing + + @property + def root_name(self) -> str: + return self.func.name.name.base + + @property + def part_of_structured_group(self) -> bool: + return self.structured or self.structured_delegate is not None + + +class SchemaKind(Enum): + functional = auto() + inplace = auto() + out = auto() + mutable = auto() + scratch = auto() + + +# A structured kernel is guaranteed to have a functional and out variant, and +# optionally an inplace variant. +# +# NB: we create NativeFunctionsGroup *even if* the function is not +# actually annotated structured. Test the structured boolean to see if it +# actually is structured or not. +@dataclass(frozen=True) +class NativeFunctionsGroup: + functional: NativeFunction + inplace: NativeFunction | None + mutable: NativeFunction | None + out: NativeFunction + + @property + def structured(self) -> bool: + # Whether or not the operator has a meta() function. This information is backend-agnostic. + return self.out.structured + + def __post_init__(self) -> None: + test_sig: FunctionSchema = self.functional.func.signature() + for f in self.functions(): + if test_sig != f.func.signature(): + raise AssertionError( + "NativeFunctionsGroup constructed from two NativeFunctions " + f"that don't have matching signatures: {test_sig} != {f.func.signature()}" + ) + + if self.structured != f.part_of_structured_group: + raise AssertionError( + "NativeFunctionsGroup constructed from structured and unstructured " + f"functions: {self.out.func.name} and {f.func.name}" + ) + assert self.functional.func.kind() == SchemaKind.functional + assert self.out.func.kind() == SchemaKind.out + assert self.functional.namespace == self.out.namespace + if self.inplace is not None: + assert self.inplace.func.kind() == SchemaKind.inplace + assert self.inplace.namespace == self.functional.namespace + + if self.mutable is not None: + assert self.mutable.func.kind() == SchemaKind.mutable + assert self.mutable.namespace == self.functional.namespace + # See Note [Overload Ambiguity With Functional Variants] + assert self.functional.func.name.name.functional_overload + + if self.structured: + # For now, structured composite kernels are not supported (need some + # design work to figure out how to make the composite case work) + assert ( + not self.out.has_composite_implicit_autograd_kernel + and not self.out.has_composite_implicit_autograd_nested_tensor_kernel + ) + + assert self.functional.structured_delegate == self.out.func.name, ( + f"{self.functional.func.name} delegates to {self.functional.structured_delegate} " + f"but its actual delegate is {self.out.func.name}" + ) + if self.inplace is not None: + assert self.inplace.structured_delegate == self.out.func.name + + generated_fns = sorted( + [str(f.func.name) for f in self.functions() if "generated" in f.tags] + ) + generated_fns_str = ", ".join(str(x) for x in generated_fns) + expected_generated_fns: set[str] = set() + for f in self.functions(): + expected_generated_fns.update(str(op) for op in f.autogen) + expected_generated_fns_str = ", ".join( + str(x) for x in sorted(expected_generated_fns) + ) + if len(expected_generated_fns) == 0 and len(generated_fns) > 0: + raise RuntimeError( + f"The codegen expects to be able to generate '{generated_fns_str}'." + " In order to generate them however, we expect them to be called out explicitly in the yaml." + f" Please add an 'autogen: {generated_fns_str}' line to the entry for {str(f.func.name)}" + ) + if expected_generated_fns_str != generated_fns_str: + raise RuntimeError( + f"The codegen expects to be able to generate '{generated_fns_str}'." + f" To do so, it expects a line: 'autogen: {generated_fns_str}'." + f" Instead, it found 'autogen: {expected_generated_fns_str}'" + ) + + def signature(self) -> FunctionSchema: + return self.out.func.signature() + + def functions(self) -> Iterator[NativeFunction]: + yield self.functional + yield self.out + if self.inplace is not None: + yield self.inplace + if self.mutable is not None: + yield self.mutable + + @property + def root_name(self) -> str: + return self.functional.root_name + + @staticmethod + def from_dict(d: dict[SchemaKind, NativeFunction]) -> NativeFunctionsGroup | None: + assert d + if len(d) == 1: + return None + d = dict(d) # non-destructive updates please + functional = d.pop(SchemaKind.functional, None) + inplace = d.pop(SchemaKind.inplace, None) + mutable = d.pop(SchemaKind.mutable, None) + out = d.pop(SchemaKind.out, None) + assert not d + assert functional is not None + # There are a few operators which only have functional/inplace variants; + # these don't count as structured for our purposes here + if out is None: + return None + # assuming all variants have the same namespace + return NativeFunctionsGroup( + functional=functional, + inplace=inplace, + mutable=mutable, + out=out, + ) + + +@dataclass(frozen=True) +class BackendMetadata: + # The name of the backend kernel, for a given operator + # for in-tree backends. These names come directly from the 'dispatch" field + # in native_functions.yaml. The dispatch entry is optional; in that + # case, that is equivalent to having written: + # + # dispatch: + # CompositeImplicitAutograd: $operator_name + kernel: str + # Whether or not the operator has a structured kernel implemented, for this particular backend. + # For in-tree backends, they all have the same value for structured- this is listed + # in native_functions.yaml. + # However, external backends like XLA can indendently toggle which ops are structured. + structured: bool + + # The namespace for kernels, default value: DEFAULT_KERNEL_NAMESPACE + cpp_namespace: str + + def supports_symint(self) -> bool: + return "_symint" in self.kernel + + +@dataclass(frozen=True) +class UfuncInnerLoop: + name: str + supported_dtypes: OrderedSet[ScalarType] + # key is stored here because it affects the semantics of name, + # so its helpful to have them together for further processing + ufunc_key: UfuncKey + + @staticmethod + def parse(value: str, ufunc_key: UfuncKey) -> UfuncInnerLoop: + name, supported_dtypes_str = value.split(" ", 1) + assert supported_dtypes_str[0] == "(" + assert supported_dtypes_str[-1] == ")" + supported_dtypes: OrderedSet[ScalarType] = OrderedSet() + for k in supported_dtypes_str[1:-1].split(", "): + supported_dtypes |= ScalarType.parse_set(k) + return UfuncInnerLoop( + name=name, supported_dtypes=supported_dtypes, ufunc_key=ufunc_key + ) + + +# BackendIndex represents a backend. +# The BackendIndex encodes per-operator information that is potentially different +# for each backend. The most obvious example is the name of the kernel +# (the 'dispatch' entry in native_functions.yaml). +# However, there can be other examples of different backends having different information. +# External backends can choose to opt their kernels to be structured independently from in-tree backends, +# which means that this information isn't inherently tied to a NativeFunction- it's different per backend. +@dataclass(frozen=True) +class BackendIndex: + dispatch_key: DispatchKey + # Mainly important for structured kernels, this determines which variant in the operator group is used to implement the others. + # All in-tree ops use out kernels, while XLA uses functional kernels. + use_out_as_primary: bool + # Whether the backend requires a device guard, and device checks. + # For in-tree backends, this is currently just CUDA/HIP + # For out-of-tree backends, this is currently just Intel XPU + device_guard: bool + # Whether the backend is in-tree (CPU/CUDA) or out-of-tree (XLA) + external: bool + # Other backend-specific information that is on a per-operator basis + index: dict[OperatorName, BackendMetadata] + + @staticmethod + def grow_index( + parent_index: dict[DispatchKey, dict[OperatorName, BackendMetadata]], + child_index: dict[DispatchKey, dict[OperatorName, BackendMetadata]], + ) -> None: + for k, v in child_index.items(): + for op_name, metadata in v.items(): + assert op_name not in parent_index[k], ( + f"duplicate operator {op_name} for dispatch key {k}" + ) + parent_index[k][op_name] = metadata + + def primary(self, g: NativeFunctionsGroup) -> NativeFunction: + if self.use_out_as_primary: + return g.out + else: + return g.functional + + def has_kernel(self, g: NativeFunction | NativeFunctionsGroup) -> bool: + m = self.get_kernel(g) + return m is not None + + def get_kernel( + self, g: NativeFunction | NativeFunctionsGroup + ) -> BackendMetadata | None: + if isinstance(g, NativeFunction): + f = g + elif isinstance(g, NativeFunctionsGroup): + f = self.primary(g) + else: + assert_never(g) + if f.func.name not in self.index: + return None + return self.index[f.func.name] + + def native_function_class_name(self) -> str | None: + if self.external: + return f"{str(self.dispatch_key)}NativeFunctions" + else: + # TODO: This discrepancy isn't required; we could also generated + # a class for in-tree kernels. It'll just require carefully + # updating every kernel definition + callsite of every in-tree aten kernel. + return None + + +# The function schema is undoubtedly the most important data structure +# in all of the codegen, as it defines the type signature for operators, +# and most of the code generation we do is type directed (e.g., look at +# the types, decide what to do. Think about how we code generate +# C++ function stubs!) +# +# We will also see in this class the general structure for how we model +# data in this code generation. A few notable properties to point out +# ahead of time: +# +# - These dataclasses are a *lossless* representation of the strings +# they are parsed from. In fact, we assert that given the +# information stored in the dataclass, we can exactly reconstruct +# the string we parsed from (and assert this inside the parse +# definition). There are a few reasons for this: +# +# - If you find that it is difficult to reconstruct the string +# given a dataclass, that is a clue that you are data +# representation is wrong. +# +# - It helps ensure that all relevant information is present +# in the dataclass, so that downstream users aren't tempted +# to reparse the original string to get some information +# that was omitted. +# +# - It forces you to represent the data in-memory in the same way +# it is recorded textually, which makes the dataclasses easier +# to understand for someone who is familiar with the +# textual format. (As a tradeoff, it means you have to model +# the syntax, even when it is inconvenient. But maybe that means +# the syntax is bad!) If you don't understand the internal +# representation, go look at the printing code to see how +# it maps onto the surface syntax! +# +# - It makes it easy to test the parsing code, as parsing code +# that is inconsistent with the string code will fail early +# and loudly. (As a tradeoff, it makes the parsing code a bit +# brittle (in particular, with trivial whitespace changes you +# are likely to trigger an assert error). +# +# In general, try to make the __str__ code as simple as possible +# (even at the cost of more complex parsing logic.) Additionally, +# try to minimize redundancy in data representation. (Precomputed +# fields are OK though: they are defined as a simple function on +# the canonical representation in question.) +# +# - These dataclasses are all frozen; once constructed their +# values never change. This makes it easy to tell where any +# given data came from: just look to the constructor. As a +# tradeoff, you can't easily "decorate" a schema with extra +# information from a post-facto analysis. We impose this +# restriction to make these structures more understandable. +# +@dataclass(frozen=True) +class FunctionSchema: + # The name of the operator this function schema describes. + name: OperatorName + + arguments: Arguments + + # TODO: Need to handle collisions with argument names at some point + returns: tuple[Return, ...] + + @property + def is_mutable(self) -> bool: + def is_write(arg: Argument) -> bool: + if arg.annotation is None: + return False + return arg.annotation.is_write + + # Corresponds to torch._C._FunctionSchema.is_mutable + # See aten/src/ATen/core/function_schema.h (keep these in sync) + return any(is_write(a) for a in self.arguments.flat_all) + + def schema_order_arguments(self) -> Iterator[Argument]: + return itertools.chain( + self.arguments.flat_positional, + self.arguments.flat_kwarg_only, + self.arguments.out, + ) + + decl_re = re.compile(r"(?P[^\(]+)\((?P.*)\) -> (?P.*)") + + @staticmethod + def parse(func: str) -> FunctionSchema: + # We should probably get a proper parser here + decls = FunctionSchema.decl_re.findall(func) + assert len(decls) == 1, f"Invalid function schema: {func}" + ops, args, return_decl = decls[0] + name = OperatorName.parse(ops) + arguments = Arguments.parse(args) + returns = parse_returns(return_decl) + r = FunctionSchema(name=name, arguments=arguments, returns=returns) + assert str(r) == func, f"{str(r)} != {func}" + return r + + def returns_are_aliased(self) -> bool: + # We assert earlier that schemas can't have a mix of aliased and non-aliased returns + return any( + r + for r in self.returns + if r.annotation is not None and r.annotation.is_write + ) + + def __post_init__(self) -> None: + for arg, ret in zip(self.arguments.out, self.returns): + assert arg.annotation == ret.annotation, ( + "Out arguments must have matching return Tensor; furthermore, " + "the ith-argument needs to correspond to the ith return" + ) + # We also enforce that if you have any mutable, positional args, then they are not returned. + # This makes it easier to group these functions properly with their functional/out= counterparts. + for a in self.arguments.post_self_positional_mutable: + assert not any(a.annotation == r.annotation for r in self.returns), ( + f"If you have a schema with mutable positional args, we expect them to not be returned. schema: {str(self)}" + ) + # Invariant: we expect out arguments to appear as keyword arguments in the schema. + # This means that all mutable returns should be aliased to a keyword argument + # (except for "self", which we explicitly don't treat as an out argument because of its use in methods) + # See Note [is_out_fn] + out_and_self = list(self.arguments.out) + [ + arg for arg in self.arguments.flat_positional if arg.name == "self" + ] + mutable_returns = [ + ret + for ret in self.returns + if ret.annotation is not None and ret.annotation.is_write + ] + immutable_returns = [ + ret + for ret in self.returns + if ret.annotation is None or not ret.annotation.is_write + ] + # Some assertions: We don't want any functions with a return type of "-> (Tensor(a!), Tensor)", + # because: + # (1) It's more annoying to handle properly + # (2) It's unnecessary - you can't method-chain on the first (mutated) output because it's part of a tuple. + # Instead, we expect the (a!) argument to not be returned. + assert len(mutable_returns) == 0 or len(immutable_returns) == 0, ( + f"NativeFunctions must have either only mutable returns, or only immutable returns. Found: {str(self)}" + ) + for ret in mutable_returns: + assert any(ret.annotation == arg.annotation for arg in out_and_self), ( + 'All mutable returns must be aliased either to a keyword argument, or to "self". ' + "Did you forget to mark an out argument as keyword-only?" + ) + if self.arguments.out: + # out= ops that return their mutable inputs are only really useful for method chaining. + # And method chaining is only really useful if the thing you're returning is a plain Tensor. + # So ideally, we'd enforce that out= ops with a single plain mutable tensor should return the tensor, + # and all other types of out= op schemas should return void. + # There are a bunch of existing out= ops that return tuples of tensors though, so we're stuck with allowing that. + if any(a.type != BaseType(BaseTy.Tensor) for a in self.arguments.out): + assert len(self.returns) == 0, ( + "out= ops that accept tensor lists as out arguments " + ) + "are expected to have no return type (since you can't do method chaining on them)" + else: + # mutable keyword arguments whose name has _scratch_ prefix are + # scratch tensors for memory planning and should not be returned + assert len( + [ + arg + for arg in self.arguments.out + if not arg.name.startswith("_scratch_") + ] + ) == len(self.returns), ( + "Must return as many arguments as there are out arguments, or no return at all" + ) + + if self.name.name.inplace: + self_a = self.arguments.self_arg + assert ( + self_a + and self_a.argument.annotation + and self_a.argument.annotation.is_write + ) + if self_a.argument.type == BaseType(BaseTy.Tensor): + # All inplace ops with an ordinary `Tensor self` argument should return self, + # to allow for method chaining. + assert ( + len(self.returns) == 1 + and self.returns[0].annotation == self_a.argument.annotation + ) + else: + # You can't method chain on non-tensor self arguments though (like a list[Tensor]) + # so in all other cases we expect the return type to be none. + assert len(self.returns) == 0 + + if self.arguments.tensor_options is not None: + assert self.kind() == SchemaKind.functional, ( + "Found an operator that is not functional or out variant, but has tensor options arguments." + "This is not allowed- tensor options arguments are only allowed for factory functions." + f"schema: {str(self)}" + ) + if self.is_functional_fn(): + assert self.kind() == SchemaKind.functional, ( + "Found an operator that is not functional, but its overload contains the string 'functional'." + "This is a special keyword in the codegen, please use a different overload name." + f"schema: {str(self)}" + ) + + def is_functional_fn(self) -> bool: + return "functional" in self.name.overload_name + + def is_out_fn(self) -> bool: + # Note [is_out_fn] + # + # out functions are the variants which take an explicit out= argument + # to populate into. We need to know if a schema corresponds to an + # out function for several reasons: + # + # - They codegen differently in C++ API + # - codegen to at::add_out rather than at::add + # - out argument is moved to front of C++ argument list + # + # out functions are DEFINED to be any function with a keyword-only + # argument that is mutable. In principle, this could lead to a + # false positive if you define a function that mutates a + # kwarg only argument, but this isn't the "true" output of this + # function. A more robust definition that would work in this + # case would also look at: + # + # - The output types. Out functions take in the arguments + # they mutate and then return them again; this is sort + # of "definitionally" what makes something an out function. + # Historically, we DO check this for consistency. + # - Correspondence with pure variant. An out function + # should have a signature equivalent to its pure variant, + # but just with extra kwargs for the output elements. This + # is difficult to actually check for and historically + # we only do this check in tools/ + return bool(self.arguments.out) + + def kind(self) -> SchemaKind: + """ + What kind of schema is this? A functional schema is one + that returns a newly allocated output; an inplace schema + modifies the self argument inplace; an out schema writes + the result into an explicitly provided out argument. + """ + is_out = bool(self.arguments.out) + is_scratch = bool( + [arg for arg in self.arguments.out if arg.name.startswith("_scratch_")] + ) + is_inplace = self.name.name.inplace + is_mutable = any( + a.annotation is not None and a.annotation.is_write + for a in self.arguments.post_self_positional + ) + assert not (is_out and is_inplace) + # out= and inplace schemas can also have post_self_positional mutable args, + # but we give precedence to out= and inplace when deciding the schema kind. + # Tradeoff: we probably don't want to have to teach codegen that looks at inplace ops + # to also worry about mutable post_self_positional arguments, + # but it seems like a much bigger lift to classify them has having a new schema kind. + # The number of ops that fit in this strange category is small enough that + # we can probably manually write code for them instead of forcing the codegen to handle them. + if is_inplace: + return SchemaKind.inplace + elif is_scratch: + assert is_out, ( + "invariant: all scratch operators are expected to be out= operators too" + ) + return SchemaKind.scratch + elif is_out: + assert not is_scratch, ( + "We should not categorize a scratch op as an out variant. Check if the order of if statements are expected!" + ) # noqa: B950 + return SchemaKind.out + elif is_mutable: + return SchemaKind.mutable + else: + return SchemaKind.functional + + # For every return: + # - If the return aliases an input, we return the input name + # - Otherwise, we return None. + # If return names were enforced to be consistent with aliasing information, then we wouldn't need this. + def aliased_return_names(self) -> list[str | None]: + outs: list[str | None] = [] + for r in self.returns: + aliased_args = [ + a + for a in self.arguments.flat_all + if a.annotation is not None and a.annotation == r.annotation + ] + if len(aliased_args) == 0: + outs.append(None) + elif len(aliased_args) == 1: + outs.append(aliased_args[0].name) + else: + aliased_names = ", ".join(a.name for a in aliased_args) + raise AssertionError( + f"Found a return ({r.name})that aliases multiple inputs ({aliased_names})" + ) + return outs + + def signature( + self, + *, + strip_default: bool = False, + strip_view_copy_name: bool = False, + keep_return_names: bool = False, + ) -> FunctionSchema: + """ + Certain schemas are 'related', in that they are simply + inplace/out/functional versions of the same function. This method + factors these schemas into the "core" functional signature which + is equal across all versions. + + Here is what normalization happens to the schema to convert + it to a signature: + - The overload name is stripped (name is retained, since + it expresses semantic content about what the function does) + - Inplace is set False + - Out arguments are stripped + - Mutable post_self_positional args are converted to returns + - Mutability annotations are stripped (this is sound + because you cannot overload on mutability annotation) + - Return names are stripped since they are not overloadable and + some variants have return names but some not + - TensorOptions are dropped + because out= variants of factory functions don't include them + (and we want to be able to pair up factory functions with their out variants) + + Finally, we want to be able to pair up related "view" and their + corresponding "view_copy" operators. We do this by optionally + stripping the trailing "_copy" from the base name. + + Example of a mutable op before and after: + + f.func (Mutable operator): + _fused_moving_avg_obs_fq_helper(Tensor self, Tensor observer_on, Tensor fake_quant_on, Tensor(a!) running_min, Tensor(b!) running_max, Tensor(c!) scale, Tensor(d!) zero_point, float averaging_const, int quant_min, int quant_max, int ch_axis, bool per_row_fake_quant=False, bool symmetric_quant=False) -> (Tensor output, Tensor mask) # noqa: B950 + + f.func (Corresponding functional operator): + _fused_moving_avg_obs_fq_helper.functional(Tensor self, Tensor observer_on, Tensor fake_quant_on, Tensor running_min, Tensor running_max, Tensor scale, Tensor zero_point, float averaging_const, int quant_min, int quant_max, int ch_axis, bool per_row_fake_quant=False, bool symmetric_quant=False) -> (Tensor output, Tensor mask, Tensor running_min_out, Tensor running_max_out, Tensor scale_out, Tensor zero_point_out) # noqa: B950 + + f.func.signature() output: + _fused_moving_avg_obs_fq_helper(Tensor self, Tensor observer_on, Tensor fake_quant_on, Tensor running_min, Tensor running_max, Tensor scale, Tensor zero_point, float averaging_const, int quant_min, int quant_max, int ch_axis, bool per_row_fake_quant=False, bool symmetric_quant=False) -> (Tensor, Tensor, Tensor, Tensor, Tensor, Tensor) # noqa: B950 + """ + + def strip_ret_annotation(r: Return) -> Return: + return Return( + name=r.name if keep_return_names else None, + type=r.type, + annotation=None, + ) + + base_name = self.name.name.base + if strip_view_copy_name: + if base_name.endswith("_copy"): + base_name = base_name.replace("_copy", "") + elif base_name.endswith("_scatter"): + base_name = base_name.replace("scatter", "inverse") + + # find mutable inputs that are not originally returned, and convert them to returns + returns_from_mutable_inputs = tuple( + # When we're grouping functions we strip the return names, + # but when we're generating the actual functional variants then we follow + # a convention for what to name the returns + Return( + name=f"{a.name}_out" if keep_return_names else None, + type=a.type, + annotation=None, + ) + for a in itertools.chain( + # Order is important here (otherwise e.g. inplace with mutable args + # and out= with mutable args won't have the same signature) + ( + [self.arguments.self_arg.argument] + if self.arguments.self_arg is not None + else [] + ), + self.arguments.out, + self.arguments.post_self_positional, + ) + if a.annotation is not None + and a.annotation.is_write + and not any(a.annotation == r.annotation for r in self.returns) + ) + original_returns = tuple(map(strip_ret_annotation, self.returns)) + # Ordering is important here. We expect the "mutable input" returns to come last. + returns = original_returns + returns_from_mutable_inputs + + args_sig = self.arguments.signature(strip_default=strip_default) + # See Note [bernoulli.p schema] + if str(self.name) == "bernoulli.p": + args_sig = Arguments.parse(str(args_sig).replace("float p", "float p=0.5")) + + return FunctionSchema( + name=OperatorName( + name=BaseOperatorName( + base=base_name, + inplace=False, + dunder_method=self.name.name.dunder_method, + ), + overload_name="", # stripped + ), + arguments=args_sig, + returns=returns, + ) + + def view_signature(self) -> FunctionSchema: + return self.signature(strip_view_copy_name=True) + + def with_name(self, name: OperatorName) -> FunctionSchema: + return FunctionSchema( + name=name, + arguments=self.arguments, + returns=self.returns, + ) + + @property + def modifies_arguments(self) -> bool: + return self.kind() in [SchemaKind.inplace, SchemaKind.out, SchemaKind.mutable] + + def has_symint(self) -> bool: + return self.arguments.has_symint_arg() + + def __str__(self) -> str: + all_arguments_str = str(self.arguments) + if len(self.returns) == 1: + returns = str(self.returns[0]) # omit parentheses + else: + returns = "(" + ", ".join(map(str, self.returns)) + ")" + return f"{self.name}({all_arguments_str}) -> {returns}" + + +# Here is the rest of the data model, described more briefly. + + +# Simplified version for what actually shows up in built-ins. +# Look at alias_info.h for expanded syntax. If you need the structure, +# you also need to make this structure recursive so it can be lined +# up with the type components too. For primitives this isn't really +# necessary +@dataclass(frozen=True) +class Annotation: + # Typically only has one element. Not actually a set so + # we can conveniently assume it is canonically ordered + alias_set: tuple[str, ...] + is_write: bool + alias_set_after: tuple[str, ...] + + @staticmethod + def parse(ann: str) -> Annotation: + # TODO: implement a proper parser if this gets more ugly + # Regex Explanation: + # Example: "a! -> a|b" + # Group #1: alias before optional '|', required. Matches the first + # character 'a' in the example + # Group #2: optional alias set after optional '|', matches empty string + # in the example + # Group #3: optional "is write" flag, matches '!' in the example. + # Group #4: optional section containing arrow, matches " -> a|b" in the + # example. + # Group #5: optional alias after set, supports wildcard, matches "a|b" + # in the example. + # Group #6: optional sub-section of alias after set, matches "|b" in the + # example. + m = re.match(r"^([a-z])(\|[a-z])*(!?)( -> (\*|[a-z](\|[a-z])*))?$", ann) + + assert m is not None, f"unrecognized alias annotation {ann}" + before_alias = m.group(1) + (m.group(2) if m.group(2) else "") + alias_set = tuple(before_alias.split("|")) + is_write = m.group(3) == "!" + assert not (is_write and len(alias_set) > 1), ( + f"alias set larger than 1 is not mutable, got {ann} instead." + ) + after_set = tuple(m.group(5).split("|")) if m.group(5) else () + assert not (len(before_alias) > 1 and len(after_set) > 1), ( + f"before alias set and after alias set cannot be larger than 1 at the same time, got {ann} instead." + ) + r = Annotation( + alias_set=alias_set, is_write=is_write, alias_set_after=after_set + ) + assert str(r) == ann, f"{r} != {ann}" + return r + + def __str__(self) -> str: + alias_set = "|".join(self.alias_set) + if self.is_write: + alias_set = f"{alias_set}!" + alias_set_after = "|".join(self.alias_set_after) + if alias_set_after: + alias_set = f"{alias_set} -> {alias_set_after}" + return alias_set + + +# The base class for the type system. This is also loosely modeled +# off of jit_type.h, but we've simplified the hierarchy to focus +# in on the aspects of the type system that matter for code generation +# (for example, there's no SingleElementType subclass anymore). +# You never actually construct a Type; usually it's going to be one +# of the subclasses. If Python had ADTs this would be one! +@dataclass(frozen=True) +class Type: + @staticmethod + def parse(t: str) -> Type: + r = Type._parse(t) + assert str(r) == t, f"{r} != {t}" + return r + + @staticmethod + def _parse(t: str) -> Type: + m = re.match(r"^(.+)\?$", t) + if m is not None: + return OptionalType(Type.parse(m.group(1))) + m = re.match(r"^(.+)\[([0-9]+)?\]$", t) + if m is not None: + size = int(m.group(2)) if m.group(2) is not None else None + return ListType(elem=Type.parse(m.group(1)), size=size) + + # '__torch__.torch.classes.' is the prefix for custom class + m = re.match(r"^__torch__\.torch\.classes\.([a-zA-Z0-9_.]+)$", t) + if m is not None: + return CustomClassType(m.group(1)) + try: + return BaseType(BaseTy[t]) + except KeyError as e: + raise RuntimeError(f"unrecognized type {t}") from e + + def __str__(self) -> str: + raise NotImplementedError + + # WARNING: These concepts are not very well-defined. For example, + # is "int?" nullable? How about "int?[]". They are defined + # so we can conveniently generate legacy Declarations.yaml but + # really we should probably just remove these at some point + + def is_base_ty_like(self, base_ty: BaseTy) -> bool: + raise NotImplementedError + + def is_tensor_like(self) -> bool: + return self.is_base_ty_like(BaseTy.Tensor) + + def is_generator_like(self) -> bool: + return self.is_base_ty_like(BaseTy.Generator) + + def is_symint_like(self) -> bool: + return self.is_base_ty_like(BaseTy.SymInt) + + def is_nullable(self) -> bool: + raise NotImplementedError + + def is_list_like(self) -> ListType | None: + raise NotImplementedError + + +# Base types are simple, atomic types with no further structure +class BaseTy(Enum): + Generator = auto() + ScalarType = auto() + Tensor = auto() + int = auto() + Dimname = auto() + DimVector = auto() + float = auto() + str = auto() + bool = auto() + Layout = auto() + Device = auto() + DeviceIndex = auto() + Scalar = auto() + MemoryFormat = auto() + QScheme = auto() + Storage = auto() + Stream = auto() + SymInt = auto() + SymBool = auto() + GraphModule = auto() + + +@dataclass(frozen=True) +class BaseType(Type): + name: BaseTy + + def __str__(self) -> str: + return f"{self.name.name}" + + def is_base_ty_like(self, base_ty: BaseTy) -> bool: + return self.name == base_ty + + def is_nullable(self) -> bool: + return False + + def is_list_like(self) -> ListType | None: + return None + + def is_symint_like(self) -> bool: + return self.name == BaseTy.SymInt + + +# Optional types may be specified, or may also be validly given None +@dataclass(frozen=True) +class OptionalType(Type): + elem: Type + + def __str__(self) -> str: + return f"{self.elem}?" + + def is_base_ty_like(self, base_ty: BaseTy) -> bool: + return self.elem.is_base_ty_like(base_ty) + + def is_symint_like(self) -> bool: + return self.elem.is_symint_like() + + def is_nullable(self) -> bool: + return True + + def is_list_like(self) -> ListType | None: + return self.elem.is_list_like() + + +# A type representing a PyTorch custom class +@dataclass(frozen=True) +class CustomClassType(Type): + class_name: str + + def __str__(self) -> str: + """ + Return the class name will prefix __torch__.torch.classes + """ + return f"__torch__.torch.classes.{self.class_name}" + + def is_base_ty_like(self, base_ty: BaseTy) -> bool: + return False + + def is_symint_like(self) -> bool: + return False + + def is_nullable(self) -> bool: + """ + Assume a custom class is not nullable. + """ + return False + + def is_list_like(self) -> ListType | None: + return None + + +# List types specify that we may have multiples of an element. We +# also support explicit sizes on list types, but these have +# some nontrivial semantics! (However, for C++ API purposes, explicit +# sizes are mostly erased from the type system.) +# +# DANGER WILL ROBINSON: C++ elaboration depends on elem type; e.g., +# int[] elaborates differently than bool[3]! +@dataclass(frozen=True) +class ListType(Type): + elem: Type + size: int | None + + def __str__(self) -> str: + size = f"{self.size}" if self.size else "" + return f"{self.elem}[{size}]" + + def is_base_ty_like(self, base_ty: BaseTy) -> bool: + return self.elem.is_base_ty_like(base_ty) + + def is_symint_like(self) -> bool: + return self.elem.is_symint_like() + + def is_nullable(self) -> bool: + return self.elem.is_nullable() + + def is_list_like(self) -> ListType | None: + return self + + +@dataclass(frozen=True) +class Argument: + # NB: I didn't put kwarg_only as a boolean field here, unlike + # c10::Argument, so that printing works correctly + + name: str + type: Type + default: str | None + + # The semantics of the annotation field are a little strange. + # + # Alias annotations parametrize Tensors (since Tensors are the only things + # that can alias.) This motivates why I write Tensor(a!)? (and not, for + # example, Tensor?(a!)), because the (a!) describes aliasing on the tensor, + # which may be optional (i.e., the alias annotation should bind first to + # Tensor, before the optional postfix annotation). + # + # However, despite being a property of Tensor, we (and c10::Argument) + # store the annotation at the top level of the Argument, rather than + # inside the embedded Tensor type. In the C++ version of this + # class, we then go through great lengths to mimic the type + # structure in the annotation structure so we can correlate + # annotations with types. + # + # Now, it turns out, in all applications in code generation, the + # structure of annotated types is very simple. So we just hard + # code it here. But if we ever do get anything more complex, this + # model will have to change! + annotation: Annotation | None + + @property + def alias_info(self) -> Annotation | None: + return self.annotation + + @staticmethod + def parse(arg: str) -> Argument: + name: str + default: str | None + assert " " in arg, f"illegal argument '{arg}'" + if "=" in arg: + assert arg.count("=") == 1, f"illegal argument with default value: '{arg}'" + type_and_annot_and_name, default = arg.split("=") + type_and_annot, name = type_and_annot_and_name.rsplit(" ", 1) + name_and_default = f"{name}={default}" + else: + type_and_annot, name_and_default = arg.rsplit(" ", 1) + name = name_and_default + default = None + # TODO: deduplicate annotation matching with Return + match = re.match(r"Tensor\((.+)\)(.*)", type_and_annot) + annotation: Annotation | None + if match: + # If you update this, make sure the __str__ still works too + assert match.group(2) in [ + "", + "?", + "[]", + ], "unrecognized alias analysis form with Tensor" + type_s = "Tensor" + match.group(2) + annotation = Annotation.parse(match.group(1)) + else: + type_s = type_and_annot + annotation = None + type = Type.parse(type_s) + r = Argument( + name=name, + type=type, + default=default, + annotation=annotation, + ) + assert str(r) == arg, f"{str(r)} != {arg}" + return r + + @property + def is_write(self) -> bool: + return self.annotation is not None and self.annotation.is_write + + def __str__(self) -> str: + type = f"{self.type}" + if self.annotation: + assert type in ["Tensor", "Tensor?", "Tensor[]"] + type = type.replace("Tensor", f"Tensor({self.annotation})") + if self.name is None: + return type + else: + mb_default = "" + if self.default: + mb_default = f"={self.default}" + return f"{type} {self.name}{mb_default}" + + +@dataclass(frozen=True) +class Return: + name: str | None + type: Type + annotation: Annotation | None + + @property + def alias_info(self) -> Annotation | None: + return self.annotation + + @staticmethod + def parse(arg: str) -> Return: + name: str | None + if " " in arg: + type_and_annot, name = arg.rsplit(" ", 1) + else: + type_and_annot = arg + name = None + match = re.match(r"Tensor\((.+)\)(.*)", type_and_annot) + annotation: Annotation | None + if match: + # If you update this, make sure the __str__ still works too + assert match.group(2) in [ + "", + "?", + "[]", + ], "unrecognized alias analysis form with Tensor" + type_s = "Tensor" + match.group(2) + annotation = Annotation.parse(match.group(1)) + else: + type_s = type_and_annot + annotation = None + type = Type.parse(type_s) + r = Return( + name=name, + type=type, + annotation=annotation, + ) + assert str(r) == arg, f"{str(r)} != {arg}" + return r + + @property + def is_write(self) -> bool: + return self.annotation is not None and self.annotation.is_write + + def __str__(self) -> str: + type = f"{self.type}" + if self.annotation: + assert type in ["Tensor", "Tensor?", "Tensor[]"] + type = type.replace("Tensor", f"Tensor({self.annotation})") + if self.name is None: + return type + else: + return f"{type} {self.name}" + + +# Represents the self argument for functions that may be methods +@dataclass(frozen=True) +class SelfArgument: + argument: Argument + + +# Bundle of arguments that represent a TensorOptions. This is mostly +# relevant for the public C++ API but we bake it into the core data +# model because other APIs often have to interact with it +@dataclass(frozen=True) +class TensorOptionsArguments: + dtype: Argument + layout: Argument + device: Argument + pin_memory: Argument + + def all(self) -> Sequence[Argument]: + return [self.dtype, self.layout, self.device, self.pin_memory] + + +@dataclass(frozen=True) +class Arguments: + # pre_self_positional is usually empty, but is notably non-empty + # for where.self, where the condition argument comes before the + # self argument + pre_self_positional: tuple[Argument, ...] + self_arg: SelfArgument | None + post_self_positional: tuple[Argument, ...] + + pre_tensor_options_kwarg_only: tuple[Argument, ...] + tensor_options: TensorOptionsArguments | None + # post_tensor_options is typically memory format, which should be + # part of tensor options but isn't right now, and is usually + # placed after the tensor options arguments + post_tensor_options_kwarg_only: tuple[Argument, ...] + + # Unlike in the previous codegen, we have factored out 'out' arguments + # in the canonical representation, removing them from kwarg + # arguments. This choice is justified by numerous downstream + # transformations which treat out arguments specially; additionally, + # you can see that canonicity is not violated! + out: tuple[Argument, ...] # these are also kwarg-only + + @property + def flat_non_out(self) -> Sequence[Argument]: + ret: list[Argument] = [] + ret.extend(self.flat_positional) + ret.extend(self.flat_kwarg_only) + return ret + + @property + def flat_positional(self) -> Sequence[Argument]: + ret: list[Argument] = [] + ret.extend(self.pre_self_positional) + if self.self_arg is not None: + ret.append(self.self_arg.argument) + ret.extend(self.post_self_positional) + return ret + + @property + def post_self_positional_mutable(self) -> Sequence[Argument]: + return [a for a in self.post_self_positional if a.is_write] + + # NB: doesn't contain out arguments + @property + def flat_kwarg_only(self) -> Sequence[Argument]: + ret: list[Argument] = [] + ret.extend(self.pre_tensor_options_kwarg_only) + if self.tensor_options is not None: + ret.extend(self.tensor_options.all()) + ret.extend(self.post_tensor_options_kwarg_only) + return ret + + @property + def flat_all(self) -> Sequence[Argument]: + ret: list[Argument] = [] + ret.extend(self.flat_positional) + ret.extend(self.flat_kwarg_only) + ret.extend(self.out) + return ret + + @property + def non_out( + self, + ) -> Sequence[Argument | SelfArgument | TensorOptionsArguments]: + ret: list[Argument | SelfArgument | TensorOptionsArguments] = [] + ret.extend(self.positional) + ret.extend(self.kwarg_only) + return ret + + @property + def positional(self) -> Sequence[Argument | SelfArgument]: + ret: list[Argument | SelfArgument] = [] + ret.extend(self.pre_self_positional) + if self.self_arg is not None: + ret.append(self.self_arg) + ret.extend(self.post_self_positional) + return ret + + @property + def kwarg_only(self) -> Sequence[Argument | TensorOptionsArguments]: + ret: list[Argument | TensorOptionsArguments] = [] + ret.extend(self.pre_tensor_options_kwarg_only) + if self.tensor_options is not None: + ret.append(self.tensor_options) + ret.extend(self.post_tensor_options_kwarg_only) + return ret + + @property + def all(self) -> Sequence[Argument | SelfArgument | TensorOptionsArguments]: + ret: list[Argument | SelfArgument | TensorOptionsArguments] = [] + ret.extend(self.positional) + ret.extend(self.kwarg_only) + ret.extend(self.out) + return ret + + def mutable_arg_names(self) -> list[str]: + return [ + a.name + for a in self.flat_all + if a.annotation is not None and a.annotation.is_write + ] + + def has_tensor_arg(self) -> bool: + return any(a.type.is_tensor_like() for a in self.flat_non_out) + + def has_symint_arg(self) -> bool: + return any(a.type.is_symint_like() for a in self.flat_non_out) + + def has_generator_arg(self) -> bool: + return any(a.type.is_generator_like() for a in self.flat_non_out) + + def signature(self, *, strip_default: bool = False) -> Arguments: + # dataclasses.replace could be used here, but it is less + # type safe so for now I've opted to type everything out + def strip_arg_annotation(a: Argument) -> Argument: + return Argument( + name=a.name, + type=a.type, + default=a.default if not strip_default else None, + annotation=None, + ) + + return Arguments( + pre_self_positional=tuple( + map(strip_arg_annotation, self.pre_self_positional) + ), + self_arg=( + SelfArgument(strip_arg_annotation(self.self_arg.argument)) + if self.self_arg is not None + else None + ), + post_self_positional=tuple( + map(strip_arg_annotation, self.post_self_positional) + ), + # Since TensorOptions are dropped, the post_tensor_options_kwargs are + # converted to pre_tensor_options_kwargs + pre_tensor_options_kwarg_only=tuple( + map(strip_arg_annotation, self.pre_tensor_options_kwarg_only) + ) + + tuple(map(strip_arg_annotation, self.post_tensor_options_kwarg_only)), + # TensorOptions are dropped in signature, + # so we can pair factory functions with their out= variants. + tensor_options=None, + post_tensor_options_kwarg_only=(), + # out arguments are dropped in signature + out=(), + ) + + def remove_self_annotation(self) -> Arguments: + assert self.self_arg is not None + return dataclasses.replace( + self, + self_arg=SelfArgument( + dataclasses.replace(self.self_arg.argument, annotation=None) + ), + ) + + def with_out_args(self, outs: list[Argument]) -> Arguments: + assert len(self.out) == 0 + return dataclasses.replace( + self, + out=tuple(outs), + ) + + @staticmethod + def _preparse(args: str) -> tuple[list[Argument], list[Argument], list[Argument]]: + positional: list[Argument] = [] + kwarg_only: list[Argument] = [] + out: list[Argument] = [] + arguments_acc = positional + + # TODO: Use a real parser here; this will get bamboozled + # by signatures that contain things like std::array (note the space) + for arg in args.split(", "): + if not arg: + continue + if arg == "*": + assert arguments_acc is positional, ( + "invalid syntax: kwarg-only specifier * can only occur once" + ) + arguments_acc = kwarg_only + continue + parg = Argument.parse(arg) + # Currently, we rely directly on the invariant that there are NO + # kwarg-only mutating arguments. If you want to relax this, + # we will need a more semantic way of matching that takes + # into account return arguments. In that case, you will have + # to manage out computation a level up, in FunctionSchema. See Note + # [is_out_fn] + if parg.annotation is not None and parg.annotation.is_write: + if arguments_acc is positional: + pass # do nothing + elif arguments_acc is kwarg_only: + arguments_acc = out + else: + assert arguments_acc is not out + arguments_acc.append(parg) + + return positional, kwarg_only, out + + @staticmethod + def parse(args: str) -> Arguments: + """ + Input: 'int x, int y, int z' + """ + + # We do this in two phases. First we parse into three + # main categories: positional, kwarg_only, out. + # Then, we reparse positional and kwarg_only to separate + # out the self argument and tensor options arguments. + + positional, kwarg_only, out = Arguments._preparse(args) + + # Split self argument + self_ix = None + for i, a in enumerate(positional): + if a.name == "self": + self_ix = i + break + pre_self_positional: list[Argument] + self_arg: SelfArgument | None + post_self_positional: list[Argument] + if self_ix is not None: + pre_self_positional = positional[:self_ix] + self_arg = SelfArgument(positional[self_ix]) + post_self_positional = positional[self_ix + 1 :] + else: + pre_self_positional = [] + self_arg = None + post_self_positional = positional + + # Group tensor options arguments + pre_tensor_options_kwarg_only: list[Argument] = [] + tensor_options: TensorOptionsArguments | None = None + post_tensor_options_kwarg_only: list[Argument] = [] + kwarg_only_acc = pre_tensor_options_kwarg_only + + def pred(name: str, ty: Type) -> Callable[[Argument], bool]: + return lambda a: a.name == name and a.type in [ty, OptionalType(ty)] + + predicates = [ # order matters + pred("dtype", Type.parse("ScalarType")), + pred("layout", Type.parse("Layout")), + pred("device", Type.parse("Device")), + pred("pin_memory", Type.parse("bool")), + ] + + i = 0 + while i < len(kwarg_only): + # If there is enough space... + if i <= len(kwarg_only) - len(predicates): + # And the next len(predicates) arguments look like TensorOptions arguments + if all( + p(a) + for p, a in zip(predicates, kwarg_only[i : i + len(predicates)]) + ): + assert kwarg_only_acc is pre_tensor_options_kwarg_only + # Group them together as one argument + tensor_options = TensorOptionsArguments( + dtype=kwarg_only[i], + layout=kwarg_only[i + 1], + device=kwarg_only[i + 2], + pin_memory=kwarg_only[i + 3], + ) + i += len(predicates) + kwarg_only_acc = post_tensor_options_kwarg_only + continue + kwarg_only_acc.append(kwarg_only[i]) + i += 1 + + return Arguments( + pre_self_positional=tuple(pre_self_positional), + self_arg=self_arg, + post_self_positional=tuple(post_self_positional), + pre_tensor_options_kwarg_only=tuple(pre_tensor_options_kwarg_only), + tensor_options=tensor_options, + post_tensor_options_kwarg_only=tuple(post_tensor_options_kwarg_only), + out=tuple(out), + ) + + def __str__(self) -> str: + all_arguments: list[str] = [] + all_arguments.extend(map(str, self.flat_positional)) + if self.flat_kwarg_only or self.out: + all_arguments.append("*") + all_arguments.extend(map(str, self.flat_kwarg_only)) + all_arguments.extend(map(str, self.out)) + return ", ".join(all_arguments) + + def __post_init__(self) -> None: + # TODO: These invariants are weirdly asymmetric? + # TODO: Fancier types? + if self.self_arg is None: + assert not self.pre_self_positional + if self.tensor_options is None: + assert not self.post_tensor_options_kwarg_only + + # We don't allow any of the following to have argument annotations, + # to keep things simple. + mutable_pre_self_positionals = [ + a + for a in self.pre_self_positional + if a.annotation is not None and a.annotation.is_write + ] + assert len(mutable_pre_self_positionals) == 0, ( + "mutable pre_self_positional arguments are not currently supported in the schema" + ) + + +# Names that validly are __iXXX__ indicating inplace operations. +# Taken from https://www.python.org/dev/peps/pep-0203/#new-methods +# NB: PyTorch hasn't actually implemented all of these +AUGMENTED_ASSIGNMENT_NAMES = [ + "add", + "sub", + "mul", + "div", + "mod", + "pow", + "lshift", + "rshift", + "and", + "xor", + "or", +] + + +# A BaseOperatorName is what we think of the operator name, without +# the overload name. Unusually, we don't represent this as just a +# string; instead, we directly represent a few important semantic +# bits of information we derive from the string: namely whether +# or not it's inplace (add_) and whether or not it's a double-underscore +# method (__add__) +@dataclass(frozen=True) +class BaseOperatorName: + base: str + inplace: bool + dunder_method: bool + # Note [Overload Ambiguity With Functional Variants] + # A handful of operators have both a "mutable" and a "functional" variant. + # (native_batch_norm is a good example, although this isn't the case today). + # For those operators, the mutable and functional variant take in the same set of + # arguments, but have different alias annotations. + # this makes it ambiguous when you try to resolve an OverloadPacket into an overload, + # given a set of input arguments. + # + # So instead of making the "functional" variant in this case a real overload, e.g: + # native_batch_norm (mutable variant) + # native_batch_norm.functional (functional variant) + # we make it a new base operator, + # native_batch_norm_functional (functional variant) + # + # In an ideal world, we would probably invert this so the operators were: + # native_batch_norm.mutable (mutable variant) + # native_batch_norm (functional variant) + # + # Doing that is BC-breaking though, so we're stuck with the above modeling. + functional_overload: bool = False + + # NB: We don't officially support namespace in FunctionSchema, we treat this prefix + # as part of the base operator name, for __str__() to consume. + # The canonical input (from the rest of the infra) will not contain namespace, but + # we have a usecase in ExecuTorch where we want to support BaseOperatorName with namespace. + namespace: Optional[str] = None + + @staticmethod + def parse(op: str) -> BaseOperatorName: + assert op != "" + assert not op.endswith("_out"), ( + "_out suffix is reserved and not permitted for operator names; " + "did you mean to specify an out overload name instead?" + ) + # Extract namespace out. Base operator name may or may not contain namespace. + # E.g., aten::__lshift__ is a valid base operator name, __lshift__ is also valid. + # We want to split the namespace out from the base operator name. + match = re.match(r"^(?:(.*)::)?(.*)$", op) + namespace = match.group(1) if match else "" + op_without_ns = match.group(2) if match else op + m = re.match(r"^__([^_]+)__$", op_without_ns) + if m is not None: + dunder_method = True + base = m.group(1) + if any(base == f"i{n}" for n in AUGMENTED_ASSIGNMENT_NAMES): + inplace = True + base = base[1:] + else: + inplace = False + # temporary, this is not intrinsically true but + # has been historically true for dunder methods + # we support (but, if we ever got, say, __int__, this would + # be wrong!) + assert base[0] != "i" + else: + dunder_method = False + base = op_without_ns + if base[-1] == "_": + inplace = True + base = base[:-1] + else: + inplace = False + + # See Note [Overload Ambiguity With Functional Variants] + functional_suffix = "_functional" + if base.endswith(functional_suffix): + functional_overload = True + base = base[: -len(functional_suffix)] + # This seems complicated and unnecessary, so banning dunder methods + # for now on ops that have a functional + mutable variant (like native_batch_norm). + assert not dunder_method and not inplace + else: + functional_overload = False + + r = BaseOperatorName( + base=base, + inplace=inplace, + dunder_method=dunder_method, + functional_overload=functional_overload, + namespace=namespace, + ) + assert str(r) == op, f"{str(r)} != {op}" + return r + + def __str__(self) -> str: + namespace_prefix = f"{self.namespace}::" if self.namespace else "" + if self.dunder_method: + i = "i" if self.inplace else "" + return f"{namespace_prefix}__{i}{self.base}__" + else: + i = ( + "_" + if self.inplace + else "_functional" + if self.functional_overload + else "" + ) + return f"{namespace_prefix}{self.base}{i}" + + +# Operator name is the base operator name along with the (typically not +# user visible) overload string. +@dataclass(frozen=True) +class OperatorName: + name: BaseOperatorName + overload_name: str + + @staticmethod + def parse(op_name: str) -> OperatorName: + if "." in op_name: + name, overload_name = op_name.split(".", 1) + else: + name = op_name + overload_name = "" + r = OperatorName(name=BaseOperatorName.parse(name), overload_name=overload_name) + assert str(r) == op_name, f"{str(r)} != {op_name}" + return r + + def __str__(self) -> str: + if self.overload_name: + return f"{self.name}.{self.overload_name}" + else: + return f"{self.name}" + + # NB: This must be synchronized with the naming scheme in + # aten/src/ATen/templates/Operators.h + # Given a function schema "aten::op.overload(...)", + # If there is no overload name, this returns f"{op}" + # If there is an overload name, this returns f"{op}_{overload}" + def unambiguous_name(self) -> str: + if self.overload_name: + return f"{self.name}_{self.overload_name}" + else: + return f"{self.name}" + + def remove_inplace(self) -> OperatorName: + return OperatorName( + name=BaseOperatorName( + base=self.name.base, + inplace=False, + dunder_method=self.name.dunder_method, + ), + overload_name=self.overload_name, + ) + + def with_overload(self, overload: str) -> OperatorName: + return OperatorName( + name=BaseOperatorName( + base=self.name.base, + inplace=False, + dunder_method=self.name.dunder_method, + ), + overload_name=overload, + ) + + +def gets_generated_out_inplace_wrapper( + f: NativeFunction, g: NativeFunctionsGroup, b: BackendIndex +) -> bool: + return ( + f.func.kind() is not SchemaKind.functional + and not b.has_kernel(f) + and b.has_kernel(g.functional) + ) + + +# NativeFunction objects that are views (f.is_view_op returns True) +# are added into a `NativeFunctionsViewGroup`, which we can use to +# easily access the generated (optional) view_copy NativeFunction. +# It's convenient to group them together, so we pair them up in NativeFunctionsViewGroup. +# See Note [Codegen'd {view}_copy Operators] +# +# One property of this representation is that in order for a view-like op to be part of +# a NativeFunctionsViewGroup, the "aliasing" version of that view op must exist. +# There's one case where that doesn't happen: we have a non-aliasing `narrow_copy.out` op, +# but don't have corresponding aliasing `narrow.out` op. +# This means that `narrow_copy.out` won't appear as a NativeFunctionsViewGroup. +@dataclass(frozen=True) +class NativeFunctionsViewGroup: + view: NativeFunction + # Note: the {view}_copy operator is optional because we currently don't generate copy variants + # for all view ops. Notably, we don't generate them for CompositeImplicitAutograd views + # (we already get them "for free" through decomposition) + view_copy: NativeFunction | None + # view_inplace ops are also optional, but every view_inplace op should have out-of-place variant. + view_inplace: NativeFunction | None + + def __post_init__(self) -> None: + assert self.view.is_view_op + if self.view_copy is None: + assert not gets_generated_view_copy(self.view), ( + f"{str(self.view.func.name)} appears to be a new operator that aliases its inputs." + " The codegen expects you to add a corresponding operator to native_functions.yaml:" + f" {get_view_copy_name(self.view)!s}." + " See Note [view_copy NativeFunctions] for details." + ) + else: + assert self.view_copy.func.name.name.base.endswith(("_copy", "_scatter")) + assert self.view.func.signature() == self.view_copy.func.signature( + strip_view_copy_name=True, + ) + assert "view_copy" in self.view_copy.tags, ( + f"{str(self.view_copy.func.name), str(self.view.tags)} appears to be a view_copy operator. The codegen expects" + " view_copy operators to be annotated with the 'view_copy' tag in native_functions.yaml." + " See Note [view_copy NativeFunction] for details." + ) + if self.view_inplace is not None: + assert self.view.func.signature() == self.view_inplace.func.signature() + + if self.view.has_composite_implicit_autograd_kernel: + if self.view_inplace is not None: + assert self.view_inplace.has_composite_implicit_autograd_kernel, ( + f"{str(self.view.func.name)} and {str(self.view_inplace.func.name)} must either" + " both have CompositeImplicitAutograd kernels, or both not have composite kernels." + ) + if self.view.has_composite_implicit_autograd_nested_tensor_kernel: + if self.view_inplace is not None: + assert self.view_inplace.has_composite_implicit_autograd_nested_tensor_kernel, ( + f"{str(self.view.func.name)} and {str(self.view_inplace.func.name)} must either" + " both have CompositeImplicitAutogradNestedTensor kernels, or both not have composite kernels." + ) + + def functions(self, *, include_copy: bool = True) -> Iterator[NativeFunction]: + yield self.view + if self.view_inplace is not None: + yield self.view_inplace + if self.view_copy is not None and include_copy: + yield self.view_copy + + @property + def root_name(self) -> str: + return self.view.root_name + + @property + def composite(self) -> bool: + # We currently assert that the "group" is consistent. + # If the view op is composite, then its view_inplace op is too. + return self.view.has_composite_implicit_autograd_kernel + + +def gets_generated_view_copy(f: NativeFunction) -> bool: + # Only aliasing (view) operators get a copy variant. + if not f.is_view_op: + return False + # We don't need to bother generating copy variants for CompositeImplicitAutograd ops, + # because we can let them decompose into base view ops. + if f.has_composite_implicit_autograd_kernel: + return False + # We also don't need to generate copy variants for inplace views. + if "inplace_view" in f.tags: + return False + # Assume ops ending in _inverse have manually-defined copy variants + # (e.g. slice_inverse() has the copy variant slice_scatter()). + # We -could- probably generate these as well, but the codegen will be + # slightly different, and hand-writing these few kernels keeps codegen + # complexity lower. + if f.func.name.name.base.endswith("_inverse"): + return False + return True + + +# Given a NativeFunction that corresponds to a view op, +# returns the OperatorName of the corresponding "copy" variant of the op. +def get_view_copy_name(f: NativeFunction) -> OperatorName: + # Right now, when asking for a view op's corresponding "view_copy" name + # we assert for sanity that the op is allowed to have a generated view_copy variant. + # (We can do this because "gets_generated_view_copy()" tell us which ops get a generated view_copy op). + # However, narrow_copy() already exists as an op directly in native_functions.yaml. + # I'm hardcoding narrow_copy here for now to maintain the assert, + # But we could also just get rid of the assert. + list_of_ops_with_explicit_view_copy_operators = ["narrow"] + if str(f.func.name) not in list_of_ops_with_explicit_view_copy_operators: + assert gets_generated_view_copy(f) + + base_name = f"{f.func.name.name.base}_copy" + view_copy_name = OperatorName( + name=BaseOperatorName( + base=base_name, inplace=False, dunder_method=f.func.name.name.dunder_method + ), + overload_name=f.func.name.overload_name, + ) + return view_copy_name + + +# Helper functions for parsing argument lists (both inputs and returns) + + +def parse_returns(return_decl: str) -> tuple[Return, ...]: + """ + Input: '()' + Output: [] + """ + if return_decl == "()": + return () + if return_decl[0] == "(" and return_decl[-1] == ")": + return_decl = return_decl[1:-1] + return tuple(Return.parse(arg) for arg in return_decl.split(", ")) + + +# A Precompute instance consists of a map from kernel argument name +# to the list of Argument instances that should replace that +# kernel argument in the impl function. +@dataclass(frozen=True) +class Precompute: + # A map from kernel argument name -> a list of precomputed + # elements that replaces/supersedes it. + replace: dict[str, list[Argument]] + # List of precomputed args added without replacement + add: list[Argument] + + @staticmethod + def parse(src: object) -> Precompute: + assert isinstance(src, list) + + # src is a list of strings of the format: + # {kernel param name} -> {replacement decl}[, {replacement decl}, ...] + # [{add decl}[, {add decl}, ...]] + # The last line is optional and contains the precomputed parameters that are + # added without replacement. + # The other lines are parsed to get the names of which precomputed elements + # should replace which kernel arguments. + add_args = [] + if " -> " not in src[-1]: + add_list = src[-1].split(",") + add_args = [Argument.parse(name.strip()) for name in add_list] + src = src[:-1] + + replace = {} + for raw_replace_item in src: + assert isinstance(raw_replace_item, str) + assert " -> " in raw_replace_item, ( + "precomputed parameters without replacement" + " are allowed only in the last line" + ) + + arg, with_list_raw = raw_replace_item.split(" -> ") + assert " " not in arg, ( + f"illegal kernel param name '{arg}' in precomputed parameters'" + ) + with_list = with_list_raw.split(",") + with_list_args = [Argument.parse(name.strip()) for name in with_list] + replace[arg] = with_list_args + + r = Precompute(replace=replace, add=add_args) + assert r.to_list() == src, "r.to_list() != src" + return r + + def __post_init__(self) -> None: + # the template parameters are upper so if these are the + # same then it is ambiguous + for a in self.add: + assert a.name.upper() != a.name + for args in self.replace.values(): + for a in args: + assert a.name.upper() != a.name + + def to_list(self) -> list[str]: + replace_list = [] + for kernel_param, replacement_params in self.replace.items(): + replacements = ", ".join(str(param) for param in replacement_params) + replace_list.append(f"{kernel_param} -> {replacements}") + + return replace_list diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/native_function_generation.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/native_function_generation.py new file mode 100644 index 0000000000000000000000000000000000000000..f986c77f8faaaeb5d961082a044ca5f595851136 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/native_function_generation.py @@ -0,0 +1,651 @@ +from __future__ import annotations + +import string +from collections import defaultdict +from typing import TYPE_CHECKING + +import torchgen.api.dispatcher as dispatcher +from torchgen.api.translate import translate +from torchgen.api.types import Binding, DispatcherSignature, Expr +from torchgen.context import with_native_function +from torchgen.model import ( + Annotation, + Argument, + BackendIndex, + BackendMetadata, + BaseOperatorName, + BaseTy, + BaseType, + DEFAULT_KERNEL_NAMESPACE, + DeviceCheckType, + DispatchKey, + FunctionSchema, + NativeFunction, + NativeFunctionsGroup, + OperatorName, + Return, + SchemaKind, + Variant, +) +from torchgen.utils import concatMap + + +if TYPE_CHECKING: + from collections.abc import Sequence + + +# See Note: [Out ops with functional variants that don't get grouped properly] +OUT_OPS_THAT_DONT_GET_GROUPED_PROPERLY = [ + # This has a functional variant, but it's currently marked private. + # This function should be marked private as well (*_backward ops aren't exposed to python anyway). + "adaptive_avg_pool3d_backward.grad_input", + # There's a functional variant, _slow_conv2d_backward.output_mask, that isn't grouped properly. + # Maybe we can kill this operator in favor of convolution_backward? + "_slow_conv2d_backward.grad_input", +] + + +# See Note: [Mutable ops that cannot get an out variant] +MUTABLE_OPS_THAT_CANNOT_GET_AN_OUT_VARIANT = [ + # should be out=? + "_cummax_helper", + # should be out=? + "_cummin_helper", +] + +# All of these operators don't have any tensor like returns +FUNCTIONAL_OPS_THAT_CANNOT_GET_AN_OUT_VARIANT = [ + "_assert_async", # no return + "_assert_async.msg", # no return + "_assert_tensor_metadata", # no return + "_cslt_sparse_mm_search", # returns an int + "_assert_scalar", # no return + "_dimI", # returns an int + "_dimV", # returns an int + "_has_same_storage_numel", # returns a boolean + "_linalg_check_errors", # no return + "_local_scalar_dense", # returns a Scalar + "_nested_tensor_from_mask_left_aligned", # returns a boolean + "_nnz", # returns an int + "_use_cudnn_ctc_loss", # returns a boolean + "_use_cudnn_ctc_loss.Tensor", # returns a boolean + "_validate_compressed_sparse_indices", # no return + "allclose", # returns a boolean + "dense_dim", # returns an int + "equal", # returns a boolean + "is_coalesced", # returns an boolean + "is_pinned", # returns a boolean + "is_same_size", # returns a boolean + "is_set_to", # returns a boolean + "q_per_channel_axis", # returns an int + "q_scale", # returns a float + "q_zero_point", # returns an int + "qscheme", # returns a QScheme + "record_stream", # no return + "sparse_dim", # returns an int + "sym_constrain_range", # no return + "sym_constrain_range_for_size", # no return + "_nested_tensor_storage_offsets", # returns a vector of ints + "_chunk_grad_outputs_efficient_attention", # returns a bool + "_fused_sdp_choice", # returns an int + "_print", # no return + "_sink_tokens", # no return + "_nested_get_ragged_idx", # returns an int +] + +INPLACE_OPS_THAT_DONT_GET_GROUPED_PROPERLY = [ + # polygamma and polygamma.out both exist, but have a + # pre-self arg (while polygamma_ does not) + # We should either fix this schema so it can be grouped properly, + # or allow the codegen to generate new functional/out= NativeFunctions for this op + # (which would require changing its overload name to prevent overload ambiguity). + "polygamma_" +] + + +# Groups "similar" NativeFunctions together +# example add.Tensor, add_.Tensor, add.out +# "similar" NativeFunctions are all expected to have an identical `signature()`, +# But have differing SchemaKinds. +def pre_group_native_functions( + native_functions: Sequence[NativeFunction], +) -> dict[FunctionSchema, dict[SchemaKind, NativeFunction]]: + pre_grouped_native_functions: dict[ + FunctionSchema, dict[SchemaKind, NativeFunction] + ] = defaultdict(dict) + for f in native_functions: + d = pre_grouped_native_functions[f.func.signature()] + assert f.func.kind() not in d + d[f.func.kind()] = f + return pre_grouped_native_functions + + +# Returns the out variant overload name given a base function overload name +def get_expected_out_variant_overload_name(overload_name: str | None) -> str: + return "out" if not overload_name else f"{overload_name}_out" + + +# Helper function: given an inplace FunctionSchema, generate its corresponding out= variant +# Example before: +# _add_relu_.Scalar(Tensor(a!) self, Scalar other, Scalar alpha=1) -> Tensor(a!) +# Example after: +# _add_relu.Scalar_out(Tensor self, Scalar other, Scalar alpha=1, *, Tensor(a!) out) +def self_to_out_signature(func: FunctionSchema) -> FunctionSchema: + # Generating an out= schema from an inplace schema. + assert func.kind() == SchemaKind.inplace + assert func.arguments.self_arg is not None + # The new out= schema has: + # - a new out argument with the same type as "func" (but with a mutable annotation) + # - The returns (if any) now alias the out= argument instead of "func" + # - an "out" overload name + return FunctionSchema( + name=func.name.remove_inplace().with_overload( + get_expected_out_variant_overload_name(func.name.overload_name) + ), + arguments=func.arguments.remove_self_annotation().with_out_args( + [ + Argument( + name="out", + type=func.arguments.self_arg.argument.type, + default=None, + annotation=func.arguments.self_arg.argument.annotation, + ) + ] + ), + returns=func.returns, + ) + + +# Helper function: given a functional FunctionSchema, generate its corresponding out= variant +# Example before: +# _to_copy(Tensor self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, +# bool? pin_memory=None, bool non_blocking=False, MemoryFormat? memory_format=None) -> Tensor +# Example after: +# _to_copy._out(Tensor self, *, bool non_blocking=False, MemoryFormat? memory_format=None, +# Tensor(a!) out) -> Tensor(a!) +def functional_to_out_signature(func: FunctionSchema) -> FunctionSchema: + # Generating an out= schema from a functional schema. + assert func.kind() == SchemaKind.functional + + new_returns, new_out_args = generate_out_args_from_schema(func) + # The new out= schema has: + # - one or more new out argument(s) with the same type as returns (but with a mutable annotation) + # - The returns now alias the out= arguments + # - an "_out" overload name + return FunctionSchema( + name=func.name.with_overload( + get_expected_out_variant_overload_name(func.name.overload_name) + ), + arguments=func.arguments.signature().with_out_args( + new_out_args, + ), + returns=tuple(new_returns), + ) + + +# Helper function: given a function schema, generate corresponding out arguments, also the updated return annotations. +def generate_out_args_from_schema( + func: FunctionSchema, +) -> tuple[list[Return], list[Argument]]: + # More of a sanity check - our existing restrictions on schemas should enforce that + # mutable schema kinds never return their mutable arguments. + assert not any( + r.annotation is not None and r.annotation.is_write for r in func.returns + ) + + tensorlike_rets = [r for r in func.returns if r.type.is_tensor_like()] + assert len(tensorlike_rets) > 0 + + used_annotations = concatMap( + lambda a: [] if a.annotation is None else a.annotation.alias_set, + func.arguments.flat_all, + ) + valid_annotations = [x for x in string.ascii_lowercase if x not in used_annotations] + + all_rets_are_tensors = all(r.type == BaseType(BaseTy.Tensor) for r in func.returns) + + new_out_args: list[Argument] = [] + # The end result of new_returns is that: + # - If every return is a plain tensor, then the new returns == the old returns, but with the out= alias annotations added. + # - Otherwise, none of the out arguments show up in the returns (and we're only left with non-tensor-like returns, if any). + new_returns: list[Return] = [] + for i, r in enumerate(func.returns): + if r.type.is_tensor_like(): + new_out = Argument( + name="out" if len(func.returns) == 1 else f"out{i}", + type=r.type, + default=None, + annotation=Annotation.parse(f"{valid_annotations[i]}!"), + ) + new_out_args.append(new_out) + if all_rets_are_tensors: + # The convention for out= schemas is that they only return their out arguments + # if the return is a plain Tensor (or if it's a tuple of plain Tensors) + new_ret = Return( + name=None, type=new_out.type, annotation=new_out.annotation + ) + new_returns.append(new_ret) + else: + new_returns.append(r) + return new_returns, new_out_args + + +# Helper function: given a mutable FunctionSchema, generate its corresponding out= variant +# Example before: +# _fused_moving_avg_obs_fq_helper(Tensor self, Tensor observer_on, Tensor fake_quant_on, Tensor(a!) running_min, Tensor(b!) running_max, Tensor(c!) scale, Tensor(d!) zero_point, float averaging_const, int quant_min, int quant_max, int ch_axis, bool per_row_fake_quant=False, bool symmetric_quant=False) -> (Tensor output, Tensor mask) # noqa: B950 +# Example after: +# _fused_moving_avg_obs_fq_helper._out(Tensor self, Tensor observer_on, Tensor fake_quant_on, Tensor(a!) running_min, Tensor(b!) running_max, Tensor(c!) scale, Tensor(d!) zero_point, float averaging_const, int quant_min, int quant_max, int ch_axis, bool per_row_fake_quant=False, bool symmetric_quant=False, *, Tensor(e!) out0, Tensor(f!) out1) -> (Tensor(e!), Tensor(f!)) # noqa: B950 +def mutable_to_out_signature(func: FunctionSchema) -> FunctionSchema: + # Generating an out= schema from a mutable schema. + assert func.kind() == SchemaKind.mutable + # The new out= schema has: + # - Any non-aliased tensor-like returns are converted to mutable, aliased out= arguments + # (if the argument is a tensor then we also return it for method chaining, + # otherwise we return nothing) + # - an "out" overload name + # + # Note that: + # (1) This also means that we can *only* generate an out= variant from a mutable schema + # if the mutable schema has at least one tensor-like non-aliasing return. + # (2) The generated out= variant still has mutable positional arguments, + # but if necessary we could probably add another out= variant that also + # functionalizes the mutable arguments (a functional_out variant) + + new_returns, new_out_args = generate_out_args_from_schema(func) + + return FunctionSchema( + name=func.name.remove_inplace().with_overload( + get_expected_out_variant_overload_name(func.name.overload_name) + ), + arguments=func.arguments.with_out_args(new_out_args), + returns=tuple(new_returns), + ) + + +# This function, given function of one SchemaKind, as well as a target SchemaKind, +# generates a new NativeFunction with the same properties, but using the target SchemaKind. +# We only actually generate functions for either functional or out= SchemaKinds. +# This function returns a tuple, with: +# - The generated NativeFunction +# - a dictionary of `BackendIndex` objects, describing which dispatch keys +# we will generate kernels for, for the new NativeFunction. +# Details are in the function, but we only generate composite kernels (in some cases) today. +def generate_function( + f: NativeFunction, k: SchemaKind +) -> tuple[NativeFunction, dict[DispatchKey, dict[OperatorName, BackendMetadata]]]: + from torchgen.api import cpp + + if k == SchemaKind.functional: + assert f.func.kind() != SchemaKind.functional + # The new "functional" NativeFunction has: + # - any mutable arguments have been converted into (immutable) returns. + # (if a mutable argument was not also a return, it gets converted to one) + # - "_functional" appended to the base name, ONLY IF this op has a mutable variant. + # See Note [Overload Ambiguity With Functional Variants] + # The default grouping logic in signature() actually already does this, + # so we can piggy-back off it (but we still want return names) + func = f.func.signature(keep_return_names=True).with_name( + OperatorName( + name=BaseOperatorName( + base=f.func.name.name.base, + inplace=False, + dunder_method=f.func.name.name.dunder_method, + # See Note [Overload Ambiguity With Functional Variants] + functional_overload=f.func.kind() == SchemaKind.mutable, + ), + overload_name=f.func.name.overload_name, + ) + ) + elif k == SchemaKind.out: + # We generate out= ops mostly just so that we can pair up NativeFunctions into groups easily, + # but at least today, there is no good reason to actually use them. + # we'll generate a dispatcher entry for them, but won't actually register any kernels for them. + if f.func.kind() == SchemaKind.inplace: + func = self_to_out_signature(f.func) + elif f.func.kind() == SchemaKind.mutable: + func = mutable_to_out_signature(f.func) + elif f.func.kind() == SchemaKind.functional: + func = functional_to_out_signature(f.func) + else: + raise AssertionError( + "We only bother generating out= functions from either inplace or mutable or functional variants" + ) + else: + raise AssertionError( + "We currently only generate either functional or out= NativeFunctions" + ) + + # Generated kernel naming convention for out: _. The reason for this is to + # disambiguate operator with the same name but different overload name, e.g., `randn.names_out` and + # `randn.generator_with_names_out`. + kernel_name = ( + func.name.unambiguous_name() + if func.kind() == SchemaKind.out + else cpp.name(func) + ) + if f.func.has_symint(): + kernel_name += "_symint" + backend_metadata = { + DispatchKey.CompositeExplicitAutograd: { + func.name: BackendMetadata( + kernel=kernel_name, + structured=False, + cpp_namespace=DEFAULT_KERNEL_NAMESPACE, + ) + } + } + tags = {"generated"} | set( + f.tags & {"nondeterministic_seeded", "view_copy", "pt2_compliant_tag"} + ) + + return ( + NativeFunction( + func=func, + use_const_ref_for_mutable_tensors=f.use_const_ref_for_mutable_tensors, + # These generated fn's aren't meant to be user friendly- don't generate methods. + variants={Variant.function}, + structured=False, + structured_delegate=None, + structured_inherits=None, + precomputed=None, + autogen=[], + ufunc_inner_loop={}, + manual_kernel_registration=False, + manual_cpp_binding=False, + python_module=None, + category_override=None, + device_guard=False, + device_check=DeviceCheckType.NoCheck, + loc=f.loc, + cpp_no_default_args=set(), + is_abstract=f.is_abstract, + has_composite_implicit_autograd_kernel=False, + has_composite_implicit_autograd_nested_tensor_kernel=False, + has_composite_explicit_autograd_kernel=True, + has_composite_explicit_autograd_non_functional_kernel=False, + # Every generated NativeFunction gets a "generated" tag, so it's easy to tell + # which NativeFunction objects did not come directly from native_functions.yaml. + tags=tags, + namespace=f.namespace, + ), + backend_metadata, + ) + + +# This function is responsible for adding generated NativeFunctions which don't appear +# explicitly in the codegen. +# You can inspect the full list of NativeFunctions yourself with the torchgen package, by running +# torchgen.parse_native_yaml("aten/src/ATen/native/native_functions.yaml", "aten/src/ATen/native/tags.yaml") +# (Maybe we should make a friendly API for this) +# +# Note: this function *mutates* its two inputs, +# adding the new NativeFunctions / BackendMetadata to them +def add_generated_native_functions( + rs: list[NativeFunction], + indices: dict[DispatchKey, dict[OperatorName, BackendMetadata]], +) -> None: + # The main code for generating new NativeFunctions + # First we group of NativeFunctions by schema kind, + # then we detect which ones are missing and generate them. + pre_grouped_native_functions = pre_group_native_functions(rs) + for d in pre_grouped_native_functions.values(): + has_functional = SchemaKind.functional in d + has_inplace = SchemaKind.inplace in d + has_mutable = SchemaKind.mutable in d + has_out = SchemaKind.out in d + is_core = any("core" in variant.tags for variant in d.values()) + + # We automatically generate a few native functions that don't exist in the yaml, for a few reasons: + # (1) If an operator has an inplace/out= variant but no functional variant, we can generate + # a simple functional variant that the functionalization pass can consume. + # (2) If an operator has an inplace or functional but no out= variant, we generate an out= + # variant, mostly so we can easily pair up functions into NativeFunctionsGroup, + # while maintaining the constraint that the out= variant is "required". + if has_mutable or has_inplace or has_out or has_functional: + # Don't bother generating functions trio's for native functions that bypass the dispatcher. + are_manual = all(f.manual_cpp_binding for f in d.values()) + # Don't bother generating functional + out= variants for view operators + # set_ is technically an inplace_view, but for now it is treated + # as a normal inplace op in the codegen + has_view_ops = any( + f.is_view_op and str(f.func.name.name) != "set_" for f in d.values() + ) + # Don't generate the other variants for non-core CompositeImplicitAutograd operators. + # We could probably do this, but the main benefit of generating the function triplets + # is for transforms that need them, and transforms don't need to act directly + # on CompositeImplicitAutograd operators (since we let them decompose). + are_composite_implicit = all( + f.has_composite_implicit_autograd_kernel for f in d.values() + ) + if are_manual or has_view_ops or are_composite_implicit and not is_core: + continue + if has_out and len(d.values()) == 1: + # Note: [Out ops with functional variants that don't get grouped properly] + # In theory we could validly have an out= operator in native_functions.yaml + # that has no other variants. + # But today, all of the operators where that's the case actually do have + # functional variants, that we are just unable to pair up properly. + # I think banning this all together is probably safer + # (you can always add a functional variant yourself if you want to add a new out= operator). + # + # We should probably fix the existing cases; this check is to prevent us from adding more over time. + if ( + str(d[SchemaKind.out].func.name) + not in OUT_OPS_THAT_DONT_GET_GROUPED_PROPERLY + ): + raise AssertionError( + f"Found an out= operator that we could not find any other variants of: {str(d[SchemaKind.out].func)}" + ) + continue + + # Some inplace ops that have problematic schemas (that we should fix), which prevent us + # from generating out= and functional variants + if ( + has_inplace + and str(d[SchemaKind.inplace].func.name) + in INPLACE_OPS_THAT_DONT_GET_GROUPED_PROPERLY + ): + continue + + base_fn = ( + d[SchemaKind.mutable] + if has_mutable + else d[SchemaKind.inplace] + if has_inplace + else d[SchemaKind.out] + if has_out + else d[SchemaKind.functional] + ) + + # Note: [Mutable ops that cannot get an out variant] + # We can only generate an out= variant if either: + # - the original function has tensor-like returns (since we can convert them to out kwargs) + # - or it's inplace (since we can convert `self` to an out kwarg) + # There are only two functions that don't fit this criteria today though, + # and they both look like they should be fixed to be out= variants, + # so if feels safer to ban this schema all-together + base_fn_valid = base_fn.func.kind() == SchemaKind.inplace or any( + r.type.is_tensor_like() for r in base_fn.func.returns + ) + # Note: [Loosen the assertion that all functional should have out variant] + # By design all functional operators should have our variants. The needs_out check + # is loosening this requirement, changing it to only generate out variant if there's + # an `autogen` block in the native function, in the long run it should be removed. + # FIXME: Remove this after figuring out CI job failures related to min, max, mean + needs_out = any("out" in str(op_name) for op_name in base_fn.autogen) + gets_out_variant = not has_out and base_fn_valid and needs_out + if not has_out and not base_fn_valid: + if ( + str(base_fn.func.name) + not in MUTABLE_OPS_THAT_CANNOT_GET_AN_OUT_VARIANT + and str(base_fn.func.name) + not in FUNCTIONAL_OPS_THAT_CANNOT_GET_AN_OUT_VARIANT + ): + raise AssertionError( + f"""Found an operator that we could not generate an out= variant for: {str(base_fn.func)}. +This type of operators don't have tensor-like return, making it difficult to generate a proper out= variant. If +out= variant is not needed, please add the function name into FUNCTIONAL_OPS_THAT_CANNOT_GET_AN_OUT_VARIANT list.""" + ) + + # Generate an out= variant + if gets_out_variant: + fn, metadata = generate_function(base_fn, SchemaKind.out) + d[SchemaKind.out] = fn + BackendIndex.grow_index(indices, metadata) + rs.append(fn) + + # Generate a functional variant, but only do it if the operator got an out= variant + # (Functional variants are only useful if we can group up the variants, + # which we can only do if they have an out= variant) + if not has_functional and (has_out or gets_out_variant): + fn, metadata = generate_function(base_fn, SchemaKind.functional) + d[SchemaKind.functional] = fn + BackendIndex.grow_index(indices, metadata) + rs.append(fn) + + +def return_str(rets: tuple[Return, ...], names: list[str]) -> str: + assert len(rets) == len(names) + if len(rets) == 0: + return "" + elif len(rets) == 1: + return f"return {names[0]};" + else: + return f"return {dispatcher.returns_type(rets).cpp_type()}({', '.join(names)});" + + +# Given a function, and the name of a variable corresponding to the output of that function, +# gather up all of the individual returns that are not aliased +def gather_nonaliased_inner_rets(func: FunctionSchema, out_var: str) -> list[str]: + aliased_rets = func.aliased_return_names() + non_aliased_names = [] + is_out_var_a_tuple = len(func.returns) > 1 + for i, r in enumerate(aliased_rets): + if r is None: + non_aliased_names.append( + f"std::get<{i}>({out_var})" if is_out_var_a_tuple else out_var + ) + return non_aliased_names + + +# Generates functional kernels in terms of their inplace.mutable counterparts. +# We only do this for "generated" NativeFunctions +@with_native_function +def gen_composite_functional_kernel(g: NativeFunctionsGroup) -> str | None: + # We should only be generating these for code-generated NativeFunctions + if "generated" not in g.functional.tags: + return None + # And we always write the kernel for a generated op in terms of a non-generated op. + if g.inplace is not None and "generated" not in g.inplace.tags: + target_f = g.inplace + elif g.mutable is not None and "generated" not in g.mutable.tags: + target_f = g.mutable + else: + # We should be guaranteed to have a valid inplace/mutable variant to call into. + # See Note: [Mutable Ops Not Using Functionalization] + raise AssertionError(str(g.functional.func)) + + sig = DispatcherSignature(g.functional.func) + target_sig = DispatcherSignature(target_f.func) + + context: list[Binding | Expr] = [] + clone_mutable_inputs = [] + cloned_return_names = [] + # We can't just directly pass all of the arguments from the functional op into the mutating op. + # We need to check for which inputs to the mutating operator are mutable, + # and clone those inputs first. + for a_curr, a_tgt in zip( + dispatcher.jit_arguments(g.functional.func), + dispatcher.jit_arguments(target_f.func), + ): + if a_tgt.annotation is not None and a_tgt.annotation.is_write: + clone_mutable_inputs.append( + f"auto {a_curr.name}_clone = clone_arg({a_curr.name});" + ) + context.append( + Expr( + expr=f"{a_curr.name}_clone", + type=dispatcher.argument_type(a_curr, binds=a_curr.name), + ) + ) + # Invariant: mutable arguments on the inner mutable op are always returns on the functional op. + cloned_return_names.append(f"{a_curr.name}_clone") + else: + context.append(dispatcher.argument(a_curr)) + exprs = ", ".join([e.expr for e in translate(context, target_sig.arguments())]) + + out_name = "output" + maybe_assign = f"auto {out_name} = " if len(target_f.func.returns) > 0 else "" + inner_return_names = gather_nonaliased_inner_rets(target_f.func, out_name) + ret_str = return_str( + g.functional.func.returns, inner_return_names + cloned_return_names + ) + + clone_mutable_inputs_str = "\n".join(clone_mutable_inputs) + return f""" +{sig.defn(name=sig.name() + ("_symint" if g.out.func.has_symint() else ""))} {{ + {clone_mutable_inputs_str} + {maybe_assign}at::_ops::{target_f.func.name.unambiguous_name()}::call({exprs}); + {ret_str} +}} +""" + + +# Generates out= kernels in terms of their functional counterparts. +# We only do this for "generated" NativeFunctions +@with_native_function +def gen_composite_out_kernel(g: NativeFunctionsGroup) -> str | None: + # We should only be generating these for code-generated NativeFunctions + if "generated" not in g.out.tags: + return None + # And we always write the kernel for the out= op in terms of the functional. + # Note that the functional op might have also been generated, but we don't have to + # worry about cycles, because the generated functional kernels are always implemented + # in terms of non-generated kernels (see gen_composite_functional_kernel). + + sig = DispatcherSignature(g.out.func) + target_sig = DispatcherSignature(g.functional.func) + + exprs = ", ".join( + [e.expr for e in translate(sig.arguments(), target_sig.arguments())] + ) + + copy_outs = [] + out_name = "tmp_output" + for i, out_arg in enumerate(g.out.func.arguments.out): + functional_return_name = ( + out_name + if len(g.functional.func.returns) == 1 + else f"std::get<{i}>({out_name})" + ) + copy_outs.append( + f"""\ + resize_out_helper({out_arg.name}, {functional_return_name}); + copy_arg({out_arg.name}, {functional_return_name});""" + ) + + rets = [] + # For each return arg in the calling (out=) operator, + # If it corresponds to an aliased input, return the input. + # Otherwise, return the corresponding output from calling the functional operator. + for i, ret_name in enumerate(g.out.func.aliased_return_names()): + if ret_name is not None: + rets.append(ret_name) + else: + functional_return_name = ( + out_name + if len(g.functional.func.returns) == 1 + else f"std::get<{i}>({out_name})" + ) + rets.append(functional_return_name) + + copy_outs_str = "\n".join(copy_outs) + + # Kernel name needs to follow the naming convention defined in `generate_function()` + return f""" +{sig.defn(name=g.out.func.name.unambiguous_name() + ("_symint" if g.out.func.has_symint() else ""))} {{ + auto {out_name} = at::_ops::{g.functional.func.name.unambiguous_name()}::call({exprs}); + {copy_outs_str} + {return_str(g.out.func.returns, rets)} +}} +""" diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/utils.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..905d6fd0c0b6c43283013d0bf75501a3e0fe9fb6 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/utils.py @@ -0,0 +1,568 @@ +from __future__ import annotations + +import contextlib +import functools +import hashlib +import os +import re +import sys +import textwrap +from dataclasses import fields, is_dataclass +from enum import auto, Enum +from pathlib import Path +from typing import Any, Callable, Generic, Literal, NoReturn, TYPE_CHECKING, TypeVar +from typing_extensions import assert_never, deprecated, Self + +from torchgen.code_template import CodeTemplate + + +if TYPE_CHECKING: + from argparse import Namespace + from collections.abc import Iterable, Iterator, Sequence + + +TORCHGEN_ROOT = Path(__file__).absolute().parent +REPO_ROOT = TORCHGEN_ROOT.parent + + +# Many of these functions share logic for defining both the definition +# and declaration (for example, the function signature is the same), so +# we organize them into one function that takes a Target to say which +# code we want. +# +# This is an OPEN enum (we may add more cases to it in the future), so be sure +# to explicitly specify with Literal[Target.XXX] or Literal[Target.XXX, Target.YYY] +# what targets are valid for your use. +class Target(Enum): + # top level namespace (not including at) + DEFINITION = auto() + DECLARATION = auto() + # TORCH_LIBRARY(...) { ... } + REGISTRATION = auto() + # namespace { ... } + ANONYMOUS_DEFINITION = auto() + # namespace cpu { ... } + NAMESPACED_DEFINITION = auto() + NAMESPACED_DECLARATION = auto() + + +# Matches "foo" in "foo, bar" but not "foobar". Used to search for the +# occurrence of a parameter in the derivative formula +IDENT_REGEX = r"(^|\W){}($|\W)" + + +# TODO: Use a real parser here; this will get bamboozled +def split_name_params(schema: str) -> tuple[str, list[str]]: + m = re.match(r"(\w+)(\.\w+)?\((.*)\)", schema) + if m is None: + raise RuntimeError(f"Unsupported function schema: {schema}") + name, _, params = m.groups() + return name, params.split(", ") + + +T = TypeVar("T") +S = TypeVar("S") + +# These two functions purposely return generators in analogy to map() +# so that you don't mix up when you need to list() them + + +# Map over function that may return None; omit Nones from output sequence +def mapMaybe(func: Callable[[T], S | None], xs: Iterable[T]) -> Iterator[S]: + for x in xs: + r = func(x) + if r is not None: + yield r + + +# Map over function that returns sequences and cat them all together +def concatMap(func: Callable[[T], Sequence[S]], xs: Iterable[T]) -> Iterator[S]: + for x in xs: + yield from func(x) + + +# Conveniently add error context to exceptions raised. Lets us +# easily say that an error occurred while processing a specific +# context. +@contextlib.contextmanager +def context(msg_fn: Callable[[], str]) -> Iterator[None]: + try: + yield + except Exception as e: + # TODO: this does the wrong thing with KeyError + msg = msg_fn() + msg = textwrap.indent(msg, " ") + msg = f"{e.args[0]}\n{msg}" if e.args else msg + e.args = (msg,) + e.args[1:] + raise + + +if TYPE_CHECKING: + # A little trick from https://github.com/python/mypy/issues/6366 + # for getting mypy to do exhaustiveness checking + # TODO: put this somewhere else, maybe + @deprecated("Use typing_extensions.assert_never instead") + def assert_never(x: NoReturn) -> NoReturn: # type: ignore[misc] # noqa: F811 + raise AssertionError(f"Unhandled type: {type(x).__name__}") + + +@functools.cache +def _read_template(template_fn: str) -> CodeTemplate: + return CodeTemplate.from_file(template_fn) + + +# String hash that's stable across different executions, unlike builtin hash +def string_stable_hash(s: str) -> int: + sha1 = hashlib.sha1(s.encode("latin1"), usedforsecurity=False).digest() + return int.from_bytes(sha1, byteorder="little") + + +# A small abstraction for writing out generated files and keeping track +# of what files have been written (so you can write out a list of output +# files) +class FileManager: + def __init__( + self, + install_dir: str | Path, + template_dir: str | Path, + dry_run: bool, + ) -> None: + self.install_dir = Path(install_dir) + self.template_dir = Path(template_dir) + self.files: set[Path] = set() + self.dry_run = dry_run + + @property + def filenames(self) -> frozenset[str]: + return frozenset({file.as_posix() for file in self.files}) + + def _write_if_changed(self, filename: str | Path, contents: str) -> None: + file = Path(filename) + old_contents: str | None = None + try: + old_contents = file.read_text(encoding="utf-8") + except OSError: + pass + if contents != old_contents: + # Create output directory if it doesn't exist + file.parent.mkdir(parents=True, exist_ok=True) + file.write_text(contents, encoding="utf-8") + + # Read from template file and replace pattern with callable (type could be dict or str). + def substitute_with_template( + self, + template_fn: str | Path, + env_callable: Callable[[], str | dict[str, Any]], + ) -> str: + assert not Path(template_fn).is_absolute(), ( + f"template_fn must be relative: {template_fn}" + ) + template_path = self.template_dir / template_fn + env = env_callable() + if isinstance(env, dict): + if "generated_comment" not in env: + generator_default = TORCHGEN_ROOT / "gen.py" + try: + generator = Path( + sys.modules["__main__"].__file__ or generator_default + ).absolute() + except (KeyError, AttributeError): + generator = generator_default.absolute() + + try: + generator_path = generator.relative_to(REPO_ROOT).as_posix() + except ValueError: + generator_path = generator.name + + env = { + **env, # copy the original dict instead of mutating it + "generated_comment": ( + "@" + f"generated by {generator_path} from {template_fn}" + ), + } + template = _read_template(template_path) + substitute_out = template.substitute(env) + # Ensure an extra blank line between the class/function definition + # and the docstring of the previous class/function definition. + # NB: It is generally not recommended to have docstrings in pyi stub + # files. But if there are any, we need to ensure that the file + # is properly formatted. + return re.sub( + r''' + (""")\n+ # match triple quotes + ( + (\s*@.+\n)* # match decorators if any + \s*(class|def) # match class/function definition + ) + ''', + r"\g<1>\n\n\g<2>", + substitute_out, + flags=re.VERBOSE, + ) + if isinstance(env, str): + return env + assert_never(env) + + def write_with_template( + self, + filename: str | Path, + template_fn: str | Path, + env_callable: Callable[[], str | dict[str, Any]], + ) -> None: + filename = Path(filename) + assert not filename.is_absolute(), f"filename must be relative: {filename}" + file = self.install_dir / filename + assert file not in self.files, f"duplicate file write {file}" + self.files.add(file) + if not self.dry_run: + substitute_out = self.substitute_with_template( + template_fn=template_fn, + env_callable=env_callable, + ) + self._write_if_changed(filename=file, contents=substitute_out) + + def write( + self, + filename: str | Path, + env_callable: Callable[[], str | dict[str, Any]], + ) -> None: + self.write_with_template(filename, filename, env_callable) + + def write_sharded( + self, + filename: str | Path, + items: Iterable[T], + *, + key_fn: Callable[[T], str], + env_callable: Callable[[T], dict[str, list[str]]], + num_shards: int, + base_env: dict[str, Any] | None = None, + sharded_keys: set[str], + ) -> None: + self.write_sharded_with_template( + filename, + filename, + items, + key_fn=key_fn, + env_callable=env_callable, + num_shards=num_shards, + base_env=base_env, + sharded_keys=sharded_keys, + ) + + def write_sharded_with_template( + self, + filename: str | Path, + template_fn: str | Path, + items: Iterable[T], + *, + key_fn: Callable[[T], str], + env_callable: Callable[[T], dict[str, list[str]]], + num_shards: int, + base_env: dict[str, Any] | None = None, + sharded_keys: set[str], + ) -> None: + file = Path(filename) + assert not file.is_absolute(), f"filename must be relative: {filename}" + everything: dict[str, Any] = {"shard_id": "Everything"} + shards: list[dict[str, Any]] = [ + {"shard_id": f"_{i}"} for i in range(num_shards) + ] + all_shards = [everything] + shards + + if base_env is not None: + for shard in all_shards: + shard.update(base_env) + + for key in sharded_keys: + for shard in all_shards: + if key in shard: + assert isinstance(shard[key], list), ( + "sharded keys in base_env must be a list" + ) + shard[key] = shard[key].copy() + else: + shard[key] = [] + + def merge_env(into: dict[str, list[str]], from_: dict[str, list[str]]) -> None: + for k, v in from_.items(): + assert k in sharded_keys, f"undeclared sharded key {k}" + into[k] += v + + if self.dry_run: + # Dry runs don't write any templates, so incomplete environments are fine + items = () + + for item in items: + key = key_fn(item) + sid = string_stable_hash(key) % num_shards + env = env_callable(item) + + merge_env(shards[sid], env) + merge_env(everything, env) + + for shard in all_shards: + shard_id = shard["shard_id"] + self.write_with_template( + file.with_stem(f"{file.stem}{shard_id}"), + template_fn, + lambda: shard, + ) + + # filenames is used to track compiled files, but FooEverything.cpp isn't meant to be compiled + self.files.discard(self.install_dir / file.with_stem(f"{file.stem}Everything")) + + def write_outputs(self, variable_name: str, filename: str | Path) -> None: + """Write a file containing the list of all outputs which are generated by this script.""" + content = "\n".join( + ( + "set(", + variable_name, + # Use POSIX paths to avoid invalid escape sequences on Windows + *(f' "{file.as_posix()}"' for file in sorted(self.files)), + ")", + ) + ) + self._write_if_changed(filename, content) + + def template_dir_for_comments(self) -> str: + """ + This needs to be deterministic. The template dir is an absolute path + that varies across builds. So, just use the path relative to this file, + which will point to the codegen source but will be stable. + """ + return os.path.relpath(self.template_dir, os.path.dirname(__file__)) + + +# Helper function to generate file manager +def make_file_manager( + options: Namespace, + install_dir: str | Path | None = None, +) -> FileManager: + template_dir = os.path.join(options.source_path, "templates") + install_dir = install_dir if install_dir else options.install_dir + return FileManager( + install_dir=install_dir, + template_dir=template_dir, + dry_run=options.dry_run, + ) + + +# Helper function to create a pretty representation for dataclasses +def dataclass_repr( + obj: Any, + indent: int = 0, + width: int = 80, +) -> str: + # built-in pprint module support dataclasses from python 3.10 + if sys.version_info >= (3, 10): + from pprint import pformat + + return pformat(obj, indent, width) + + return _pformat(obj, indent=indent, width=width) + + +def _pformat( + obj: Any, + indent: int, + width: int, + curr_indent: int = 0, +) -> str: + assert is_dataclass(obj), f"obj should be a dataclass, received: {type(obj)}" + + class_name = obj.__class__.__name__ + # update current indentation level with class name + curr_indent += len(class_name) + 1 + + fields_list = [(f.name, getattr(obj, f.name)) for f in fields(obj) if f.repr] + + fields_str = [] + for name, attr in fields_list: + # update the current indent level with the field name + # dict, list, set and tuple also add indent as done in pprint + _curr_indent = curr_indent + len(name) + 1 + if is_dataclass(attr): + str_repr = _pformat(attr, indent, width, _curr_indent) + elif isinstance(attr, dict): + str_repr = _format_dict(attr, indent, width, _curr_indent) + elif isinstance(attr, (list, set, tuple)): + str_repr = _format_list(attr, indent, width, _curr_indent) + else: + str_repr = repr(attr) + + fields_str.append(f"{name}={str_repr}") + + indent_str = curr_indent * " " + body = f",\n{indent_str}".join(fields_str) + return f"{class_name}({body})" + + +def _format_dict( + attr: dict[Any, Any], + indent: int, + width: int, + curr_indent: int, +) -> str: + curr_indent += indent + 3 + dict_repr = [] + for k, v in attr.items(): + k_repr = repr(k) + v_str = ( + _pformat(v, indent, width, curr_indent + len(k_repr)) + if is_dataclass(v) + else repr(v) + ) + dict_repr.append(f"{k_repr}: {v_str}") + + return _format(dict_repr, indent, width, curr_indent, "{", "}") + + +def _format_list( + attr: list[Any] | set[Any] | tuple[Any, ...], + indent: int, + width: int, + curr_indent: int, +) -> str: + curr_indent += indent + 1 + list_repr = [ + _pformat(l, indent, width, curr_indent) if is_dataclass(l) else repr(l) + for l in attr + ] + start, end = ("[", "]") if isinstance(attr, list) else ("(", ")") + return _format(list_repr, indent, width, curr_indent, start, end) + + +def _format( + fields_str: list[str], + indent: int, + width: int, + curr_indent: int, + start: str, + end: str, +) -> str: + delimiter, curr_indent_str = "", "" + # if it exceed the max width then we place one element per line + if len(repr(fields_str)) >= width: + delimiter = "\n" + curr_indent_str = " " * curr_indent + + indent_str = " " * indent + body = f", {delimiter}{curr_indent_str}".join(fields_str) + return f"{start}{indent_str}{body}{end}" + + +class NamespaceHelper: + """A helper for constructing the namespace open and close strings for a nested set of namespaces. + + e.g. for namespace_str torch::lazy, + + prologue: + namespace torch { + namespace lazy { + + epilogue: + } // namespace lazy + } // namespace torch + """ + + def __init__( + self, + namespace_str: str, + entity_name: str = "", + max_level: int = 2, + ) -> None: + # cpp_namespace can be a colon joined string such as torch::lazy + cpp_namespaces = namespace_str.split("::") + assert len(cpp_namespaces) <= max_level, ( + f"Codegen doesn't support more than {max_level} level(s) of custom namespace. Got {namespace_str}." + ) + self.cpp_namespace_ = namespace_str + self.prologue_ = "\n".join([f"namespace {n} {{" for n in cpp_namespaces]) + self.epilogue_ = "\n".join( + [f"}} // namespace {n}" for n in reversed(cpp_namespaces)] + ) + self.namespaces_ = cpp_namespaces + self.entity_name_ = entity_name + + @staticmethod + def from_namespaced_entity( + namespaced_entity: str, + max_level: int = 2, + ) -> NamespaceHelper: + """ + Generate helper from nested namespaces as long as class/function name. E.g.: "torch::lazy::add" + """ + names = namespaced_entity.split("::") + entity_name = names[-1] + namespace_str = "::".join(names[:-1]) + return NamespaceHelper( + namespace_str=namespace_str, entity_name=entity_name, max_level=max_level + ) + + @property + def prologue(self) -> str: + return self.prologue_ + + @property + def epilogue(self) -> str: + return self.epilogue_ + + @property + def entity_name(self) -> str: + return self.entity_name_ + + # Only allow certain level of namespaces + def get_cpp_namespace(self, default: str = "") -> str: + """ + Return the namespace string from joining all the namespaces by "::" (hence no leading "::"). + Return default if namespace string is empty. + """ + return self.cpp_namespace_ if self.cpp_namespace_ else default + + +class OrderedSet(Generic[T]): + storage: dict[T, Literal[None]] + + def __init__(self, iterable: Iterable[T] | None = None) -> None: + if iterable is None: + self.storage = {} + else: + self.storage = dict.fromkeys(iterable) + + def __contains__(self, item: T) -> bool: + return item in self.storage + + def __iter__(self) -> Iterator[T]: + return iter(self.storage.keys()) + + def update(self, items: OrderedSet[T]) -> None: + self.storage.update(items.storage) + + def add(self, item: T) -> None: + self.storage[item] = None + + def copy(self) -> OrderedSet[T]: + ret: OrderedSet[T] = OrderedSet() + ret.storage = self.storage.copy() + return ret + + @staticmethod + def union(*args: OrderedSet[T]) -> OrderedSet[T]: + ret = args[0].copy() + for s in args[1:]: + ret.update(s) + return ret + + def __or__(self, other: OrderedSet[T]) -> OrderedSet[T]: + return OrderedSet.union(self, other) + + def __ior__(self, other: OrderedSet[T]) -> Self: + self.update(other) + return self + + def __eq__(self, other: object) -> bool: + if isinstance(other, OrderedSet): + return self.storage == other.storage + else: + return set(self.storage.keys()) == other diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/yaml_utils.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/yaml_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..720d1944602e7c810138d71d7cf60fe351f87500 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchgen/yaml_utils.py @@ -0,0 +1,26 @@ +# Safely load fast C Yaml loader/dumper if they are available +try: + from yaml import CSafeLoader as Loader +except ImportError: + from yaml import SafeLoader as Loader # type: ignore[assignment, misc] + +try: + from yaml import CSafeDumper as Dumper +except ImportError: + from yaml import SafeDumper as Dumper # type: ignore[assignment, misc] +YamlDumper = Dumper + + +# A custom loader for YAML that errors on duplicate keys. +# This doesn't happen by default: see https://github.com/yaml/pyyaml/issues/165 +class YamlLoader(Loader): + def construct_mapping(self, node, deep=False): # type: ignore[no-untyped-def] + mapping = [] + for key_node, value_node in node.value: + key = self.construct_object(key_node, deep=deep) # type: ignore[no-untyped-call] + assert key not in mapping, ( + f"Found a duplicate key in the yaml. key={key}, line={node.start_mark.line}" + ) + mapping.append(key) + mapping = super().construct_mapping(node, deep=deep) # type: ignore[no-untyped-call] + return mapping diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers-4.57.6.dist-info/INSTALLER b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers-4.57.6.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers-4.57.6.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers-4.57.6.dist-info/METADATA b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers-4.57.6.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..c627362070a48e8af8a12be7aa3a818b02b615d4 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers-4.57.6.dist-info/METADATA @@ -0,0 +1,881 @@ +Metadata-Version: 2.4 +Name: transformers +Version: 4.57.6 +Summary: State-of-the-art Machine Learning for JAX, PyTorch and TensorFlow +Home-page: https://github.com/huggingface/transformers +Author: The Hugging Face team (past and future) with the help of all our contributors (https://github.com/huggingface/transformers/graphs/contributors) +Author-email: transformers@huggingface.co +License: Apache 2.0 License +Keywords: NLP vision speech deep learning transformer pytorch tensorflow jax BERT GPT-2 Wav2Vec2 ViT +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: Topic :: Scientific/Engineering :: Artificial Intelligence +Requires-Python: >=3.9.0 +Description-Content-Type: text/markdown +License-File: LICENSE +Requires-Dist: filelock +Requires-Dist: huggingface-hub<1.0,>=0.34.0 +Requires-Dist: numpy>=1.17 +Requires-Dist: packaging>=20.0 +Requires-Dist: pyyaml>=5.1 +Requires-Dist: regex!=2019.12.17 +Requires-Dist: requests +Requires-Dist: tokenizers<=0.23.0,>=0.22.0 +Requires-Dist: safetensors>=0.4.3 +Requires-Dist: tqdm>=4.27 +Provides-Extra: ja +Requires-Dist: fugashi>=1.0; extra == "ja" +Requires-Dist: ipadic<2.0,>=1.0.0; extra == "ja" +Requires-Dist: unidic_lite>=1.0.7; extra == "ja" +Requires-Dist: unidic>=1.0.2; extra == "ja" +Requires-Dist: sudachipy>=0.6.6; extra == "ja" +Requires-Dist: sudachidict_core>=20220729; extra == "ja" +Requires-Dist: rhoknp<1.3.1,>=1.1.0; extra == "ja" +Provides-Extra: sklearn +Requires-Dist: scikit-learn; extra == "sklearn" +Provides-Extra: tf +Requires-Dist: tensorflow<2.16,>2.9; extra == "tf" +Requires-Dist: onnxconverter-common; extra == "tf" +Requires-Dist: tf2onnx; extra == "tf" +Requires-Dist: tensorflow-text<2.16; extra == "tf" +Requires-Dist: keras-nlp<0.14.0,>=0.3.1; extra == "tf" +Provides-Extra: tf-cpu +Requires-Dist: keras<2.16,>2.9; extra == "tf-cpu" +Requires-Dist: tensorflow-cpu<2.16,>2.9; extra == "tf-cpu" +Requires-Dist: onnxconverter-common; extra == "tf-cpu" +Requires-Dist: tf2onnx; extra == "tf-cpu" +Requires-Dist: tensorflow-text<2.16; extra == "tf-cpu" +Requires-Dist: keras-nlp<0.14.0,>=0.3.1; extra == "tf-cpu" +Requires-Dist: tensorflow-probability<0.24; extra == "tf-cpu" +Provides-Extra: torch +Requires-Dist: torch>=2.2; extra == "torch" +Requires-Dist: accelerate>=0.26.0; extra == "torch" +Provides-Extra: accelerate +Requires-Dist: accelerate>=0.26.0; extra == "accelerate" +Provides-Extra: hf-xet +Requires-Dist: hf_xet; extra == "hf-xet" +Provides-Extra: retrieval +Requires-Dist: faiss-cpu; extra == "retrieval" +Requires-Dist: datasets>=2.15.0; extra == "retrieval" +Provides-Extra: flax +Requires-Dist: jax<=0.4.13,>=0.4.1; extra == "flax" +Requires-Dist: jaxlib<=0.4.13,>=0.4.1; extra == "flax" +Requires-Dist: flax<=0.7.0,>=0.4.1; extra == "flax" +Requires-Dist: optax<=0.1.4,>=0.0.8; extra == "flax" +Requires-Dist: scipy<1.13.0; extra == "flax" +Provides-Extra: tokenizers +Requires-Dist: tokenizers<=0.23.0,>=0.22.0; extra == "tokenizers" +Provides-Extra: ftfy +Requires-Dist: ftfy; extra == "ftfy" +Provides-Extra: onnxruntime +Requires-Dist: onnxruntime>=1.4.0; extra == "onnxruntime" +Requires-Dist: onnxruntime-tools>=1.4.2; extra == "onnxruntime" +Provides-Extra: onnx +Requires-Dist: onnxconverter-common; extra == "onnx" +Requires-Dist: tf2onnx; extra == "onnx" +Requires-Dist: onnxruntime>=1.4.0; extra == "onnx" +Requires-Dist: onnxruntime-tools>=1.4.2; extra == "onnx" +Provides-Extra: modelcreation +Requires-Dist: cookiecutter==1.7.3; extra == "modelcreation" +Provides-Extra: sagemaker +Requires-Dist: sagemaker>=2.31.0; extra == "sagemaker" +Provides-Extra: deepspeed +Requires-Dist: deepspeed>=0.9.3; extra == "deepspeed" +Requires-Dist: accelerate>=0.26.0; extra == "deepspeed" +Provides-Extra: optuna +Requires-Dist: optuna; extra == "optuna" +Provides-Extra: ray +Requires-Dist: ray[tune]>=2.7.0; extra == "ray" +Provides-Extra: sigopt +Requires-Dist: sigopt; extra == "sigopt" +Provides-Extra: hub-kernels +Requires-Dist: kernels<=0.9,>=0.6.1; extra == "hub-kernels" +Provides-Extra: integrations +Requires-Dist: kernels<=0.9,>=0.6.1; extra == "integrations" +Requires-Dist: optuna; extra == "integrations" +Requires-Dist: ray[tune]>=2.7.0; extra == "integrations" +Provides-Extra: serving +Requires-Dist: openai>=1.98.0; extra == "serving" +Requires-Dist: pydantic>=2; extra == "serving" +Requires-Dist: uvicorn; extra == "serving" +Requires-Dist: fastapi; extra == "serving" +Requires-Dist: starlette; extra == "serving" +Requires-Dist: torch>=2.2; extra == "serving" +Requires-Dist: accelerate>=0.26.0; extra == "serving" +Provides-Extra: audio +Requires-Dist: librosa; extra == "audio" +Requires-Dist: pyctcdecode>=0.4.0; extra == "audio" +Requires-Dist: phonemizer; extra == "audio" +Requires-Dist: kenlm; extra == "audio" +Provides-Extra: speech +Requires-Dist: torchaudio; extra == "speech" +Requires-Dist: librosa; extra == "speech" +Requires-Dist: pyctcdecode>=0.4.0; extra == "speech" +Requires-Dist: phonemizer; extra == "speech" +Requires-Dist: kenlm; extra == "speech" +Provides-Extra: torch-speech +Requires-Dist: torchaudio; extra == "torch-speech" +Requires-Dist: librosa; extra == "torch-speech" +Requires-Dist: pyctcdecode>=0.4.0; extra == "torch-speech" +Requires-Dist: phonemizer; extra == "torch-speech" +Requires-Dist: kenlm; extra == "torch-speech" +Provides-Extra: tf-speech +Requires-Dist: librosa; extra == "tf-speech" +Requires-Dist: pyctcdecode>=0.4.0; extra == "tf-speech" +Requires-Dist: phonemizer; extra == "tf-speech" +Requires-Dist: kenlm; extra == "tf-speech" +Provides-Extra: flax-speech +Requires-Dist: librosa; extra == "flax-speech" +Requires-Dist: pyctcdecode>=0.4.0; extra == "flax-speech" +Requires-Dist: phonemizer; extra == "flax-speech" +Requires-Dist: kenlm; extra == "flax-speech" +Provides-Extra: vision +Requires-Dist: Pillow<=15.0,>=10.0.1; extra == "vision" +Provides-Extra: timm +Requires-Dist: timm!=1.0.18,<=1.0.19; extra == "timm" +Provides-Extra: torch-vision +Requires-Dist: torchvision; extra == "torch-vision" +Requires-Dist: Pillow<=15.0,>=10.0.1; extra == "torch-vision" +Provides-Extra: natten +Requires-Dist: natten<0.15.0,>=0.14.6; extra == "natten" +Provides-Extra: codecarbon +Requires-Dist: codecarbon>=2.8.1; extra == "codecarbon" +Provides-Extra: video +Requires-Dist: av; extra == "video" +Provides-Extra: num2words +Requires-Dist: num2words; extra == "num2words" +Provides-Extra: sentencepiece +Requires-Dist: sentencepiece!=0.1.92,>=0.1.91; extra == "sentencepiece" +Requires-Dist: protobuf; extra == "sentencepiece" +Provides-Extra: tiktoken +Requires-Dist: tiktoken; extra == "tiktoken" +Requires-Dist: blobfile; extra == "tiktoken" +Provides-Extra: mistral-common +Requires-Dist: mistral-common[opencv]>=1.6.3; extra == "mistral-common" +Provides-Extra: chat-template +Requires-Dist: jinja2>=3.1.0; extra == "chat-template" +Provides-Extra: testing +Requires-Dist: pytest>=7.2.0; extra == "testing" +Requires-Dist: pytest-asyncio; extra == "testing" +Requires-Dist: pytest-rich; extra == "testing" +Requires-Dist: pytest-xdist; extra == "testing" +Requires-Dist: pytest-order; extra == "testing" +Requires-Dist: pytest-rerunfailures<16.0; extra == "testing" +Requires-Dist: timeout-decorator; extra == "testing" +Requires-Dist: parameterized>=0.9; extra == "testing" +Requires-Dist: psutil; extra == "testing" +Requires-Dist: datasets>=2.15.0; extra == "testing" +Requires-Dist: dill<0.3.5; extra == "testing" +Requires-Dist: evaluate>=0.2.0; extra == "testing" +Requires-Dist: pytest-timeout; extra == "testing" +Requires-Dist: ruff==0.13.1; extra == "testing" +Requires-Dist: rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1; extra == "testing" +Requires-Dist: nltk<=3.8.1; extra == "testing" +Requires-Dist: GitPython<3.1.19; extra == "testing" +Requires-Dist: sacremoses; extra == "testing" +Requires-Dist: rjieba; extra == "testing" +Requires-Dist: beautifulsoup4; extra == "testing" +Requires-Dist: tensorboard; extra == "testing" +Requires-Dist: pydantic>=2; extra == "testing" +Requires-Dist: sentencepiece!=0.1.92,>=0.1.91; extra == "testing" +Requires-Dist: sacrebleu<2.0.0,>=1.4.12; extra == "testing" +Requires-Dist: libcst; extra == "testing" +Requires-Dist: faiss-cpu; extra == "testing" +Requires-Dist: datasets>=2.15.0; extra == "testing" +Requires-Dist: cookiecutter==1.7.3; extra == "testing" +Requires-Dist: mistral-common[opencv]>=1.6.3; extra == "testing" +Requires-Dist: openai>=1.98.0; extra == "testing" +Requires-Dist: pydantic>=2; extra == "testing" +Requires-Dist: uvicorn; extra == "testing" +Requires-Dist: fastapi; extra == "testing" +Requires-Dist: starlette; extra == "testing" +Requires-Dist: torch>=2.2; extra == "testing" +Requires-Dist: accelerate>=0.26.0; extra == "testing" +Provides-Extra: deepspeed-testing +Requires-Dist: deepspeed>=0.9.3; extra == "deepspeed-testing" +Requires-Dist: accelerate>=0.26.0; extra == "deepspeed-testing" +Requires-Dist: pytest>=7.2.0; extra == "deepspeed-testing" +Requires-Dist: pytest-asyncio; extra == "deepspeed-testing" +Requires-Dist: pytest-rich; extra == "deepspeed-testing" +Requires-Dist: pytest-xdist; extra == "deepspeed-testing" +Requires-Dist: pytest-order; extra == "deepspeed-testing" +Requires-Dist: pytest-rerunfailures<16.0; extra == "deepspeed-testing" +Requires-Dist: timeout-decorator; extra == "deepspeed-testing" +Requires-Dist: parameterized>=0.9; extra == "deepspeed-testing" +Requires-Dist: psutil; extra == "deepspeed-testing" +Requires-Dist: datasets>=2.15.0; extra == "deepspeed-testing" +Requires-Dist: dill<0.3.5; extra == "deepspeed-testing" +Requires-Dist: evaluate>=0.2.0; extra == "deepspeed-testing" +Requires-Dist: pytest-timeout; extra == "deepspeed-testing" +Requires-Dist: ruff==0.13.1; extra == "deepspeed-testing" +Requires-Dist: rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1; extra == "deepspeed-testing" +Requires-Dist: nltk<=3.8.1; extra == "deepspeed-testing" +Requires-Dist: GitPython<3.1.19; extra == "deepspeed-testing" +Requires-Dist: sacremoses; extra == "deepspeed-testing" +Requires-Dist: rjieba; extra == "deepspeed-testing" +Requires-Dist: beautifulsoup4; extra == "deepspeed-testing" +Requires-Dist: tensorboard; extra == "deepspeed-testing" +Requires-Dist: pydantic>=2; extra == "deepspeed-testing" +Requires-Dist: sentencepiece!=0.1.92,>=0.1.91; extra == "deepspeed-testing" +Requires-Dist: sacrebleu<2.0.0,>=1.4.12; extra == "deepspeed-testing" +Requires-Dist: libcst; extra == "deepspeed-testing" +Requires-Dist: faiss-cpu; extra == "deepspeed-testing" +Requires-Dist: datasets>=2.15.0; extra == "deepspeed-testing" +Requires-Dist: cookiecutter==1.7.3; extra == "deepspeed-testing" +Requires-Dist: mistral-common[opencv]>=1.6.3; extra == "deepspeed-testing" +Requires-Dist: openai>=1.98.0; extra == "deepspeed-testing" +Requires-Dist: pydantic>=2; extra == "deepspeed-testing" +Requires-Dist: uvicorn; extra == "deepspeed-testing" +Requires-Dist: fastapi; extra == "deepspeed-testing" +Requires-Dist: starlette; extra == "deepspeed-testing" +Requires-Dist: torch>=2.2; extra == "deepspeed-testing" +Requires-Dist: accelerate>=0.26.0; extra == "deepspeed-testing" +Requires-Dist: optuna; extra == "deepspeed-testing" +Requires-Dist: sentencepiece!=0.1.92,>=0.1.91; extra == "deepspeed-testing" +Requires-Dist: protobuf; extra == "deepspeed-testing" +Provides-Extra: ruff +Requires-Dist: ruff==0.13.1; extra == "ruff" +Provides-Extra: quality +Requires-Dist: datasets>=2.15.0; extra == "quality" +Requires-Dist: ruff==0.13.1; extra == "quality" +Requires-Dist: GitPython<3.1.19; extra == "quality" +Requires-Dist: urllib3<2.0.0; extra == "quality" +Requires-Dist: libcst; extra == "quality" +Requires-Dist: rich; extra == "quality" +Requires-Dist: pandas<2.3.0; extra == "quality" +Provides-Extra: all +Requires-Dist: tensorflow<2.16,>2.9; extra == "all" +Requires-Dist: onnxconverter-common; extra == "all" +Requires-Dist: tf2onnx; extra == "all" +Requires-Dist: tensorflow-text<2.16; extra == "all" +Requires-Dist: keras-nlp<0.14.0,>=0.3.1; extra == "all" +Requires-Dist: torch>=2.2; extra == "all" +Requires-Dist: accelerate>=0.26.0; extra == "all" +Requires-Dist: jax<=0.4.13,>=0.4.1; extra == "all" +Requires-Dist: jaxlib<=0.4.13,>=0.4.1; extra == "all" +Requires-Dist: flax<=0.7.0,>=0.4.1; extra == "all" +Requires-Dist: optax<=0.1.4,>=0.0.8; extra == "all" +Requires-Dist: scipy<1.13.0; extra == "all" +Requires-Dist: sentencepiece!=0.1.92,>=0.1.91; extra == "all" +Requires-Dist: protobuf; extra == "all" +Requires-Dist: tokenizers<=0.23.0,>=0.22.0; extra == "all" +Requires-Dist: torchaudio; extra == "all" +Requires-Dist: librosa; extra == "all" +Requires-Dist: pyctcdecode>=0.4.0; extra == "all" +Requires-Dist: phonemizer; extra == "all" +Requires-Dist: kenlm; extra == "all" +Requires-Dist: Pillow<=15.0,>=10.0.1; extra == "all" +Requires-Dist: kernels<=0.9,>=0.6.1; extra == "all" +Requires-Dist: optuna; extra == "all" +Requires-Dist: ray[tune]>=2.7.0; extra == "all" +Requires-Dist: timm!=1.0.18,<=1.0.19; extra == "all" +Requires-Dist: torchvision; extra == "all" +Requires-Dist: Pillow<=15.0,>=10.0.1; extra == "all" +Requires-Dist: codecarbon>=2.8.1; extra == "all" +Requires-Dist: accelerate>=0.26.0; extra == "all" +Requires-Dist: av; extra == "all" +Requires-Dist: num2words; extra == "all" +Requires-Dist: mistral-common[opencv]>=1.6.3; extra == "all" +Requires-Dist: jinja2>=3.1.0; extra == "all" +Provides-Extra: dev-torch +Requires-Dist: pytest>=7.2.0; extra == "dev-torch" +Requires-Dist: pytest-asyncio; extra == "dev-torch" +Requires-Dist: pytest-rich; extra == "dev-torch" +Requires-Dist: pytest-xdist; extra == "dev-torch" +Requires-Dist: pytest-order; extra == "dev-torch" +Requires-Dist: pytest-rerunfailures<16.0; extra == "dev-torch" +Requires-Dist: timeout-decorator; extra == "dev-torch" +Requires-Dist: parameterized>=0.9; extra == "dev-torch" +Requires-Dist: psutil; extra == "dev-torch" +Requires-Dist: datasets>=2.15.0; extra == "dev-torch" +Requires-Dist: dill<0.3.5; extra == "dev-torch" +Requires-Dist: evaluate>=0.2.0; extra == "dev-torch" +Requires-Dist: pytest-timeout; extra == "dev-torch" +Requires-Dist: ruff==0.13.1; extra == "dev-torch" +Requires-Dist: rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1; extra == "dev-torch" +Requires-Dist: nltk<=3.8.1; extra == "dev-torch" +Requires-Dist: GitPython<3.1.19; extra == "dev-torch" +Requires-Dist: sacremoses; extra == "dev-torch" +Requires-Dist: rjieba; extra == "dev-torch" +Requires-Dist: beautifulsoup4; extra == "dev-torch" +Requires-Dist: tensorboard; extra == "dev-torch" +Requires-Dist: pydantic>=2; extra == "dev-torch" +Requires-Dist: sentencepiece!=0.1.92,>=0.1.91; extra == "dev-torch" +Requires-Dist: sacrebleu<2.0.0,>=1.4.12; extra == "dev-torch" +Requires-Dist: libcst; extra == "dev-torch" +Requires-Dist: faiss-cpu; extra == "dev-torch" +Requires-Dist: datasets>=2.15.0; extra == "dev-torch" +Requires-Dist: cookiecutter==1.7.3; extra == "dev-torch" +Requires-Dist: mistral-common[opencv]>=1.6.3; extra == "dev-torch" +Requires-Dist: openai>=1.98.0; extra == "dev-torch" +Requires-Dist: pydantic>=2; extra == "dev-torch" +Requires-Dist: uvicorn; extra == "dev-torch" +Requires-Dist: fastapi; extra == "dev-torch" +Requires-Dist: starlette; extra == "dev-torch" +Requires-Dist: torch>=2.2; extra == "dev-torch" +Requires-Dist: accelerate>=0.26.0; extra == "dev-torch" +Requires-Dist: torch>=2.2; extra == "dev-torch" +Requires-Dist: accelerate>=0.26.0; extra == "dev-torch" +Requires-Dist: sentencepiece!=0.1.92,>=0.1.91; extra == "dev-torch" +Requires-Dist: protobuf; extra == "dev-torch" +Requires-Dist: tokenizers<=0.23.0,>=0.22.0; extra == "dev-torch" +Requires-Dist: torchaudio; extra == "dev-torch" +Requires-Dist: librosa; extra == "dev-torch" +Requires-Dist: pyctcdecode>=0.4.0; extra == "dev-torch" +Requires-Dist: phonemizer; extra == "dev-torch" +Requires-Dist: kenlm; extra == "dev-torch" +Requires-Dist: Pillow<=15.0,>=10.0.1; extra == "dev-torch" +Requires-Dist: kernels<=0.9,>=0.6.1; extra == "dev-torch" +Requires-Dist: optuna; extra == "dev-torch" +Requires-Dist: ray[tune]>=2.7.0; extra == "dev-torch" +Requires-Dist: timm!=1.0.18,<=1.0.19; extra == "dev-torch" +Requires-Dist: torchvision; extra == "dev-torch" +Requires-Dist: Pillow<=15.0,>=10.0.1; extra == "dev-torch" +Requires-Dist: codecarbon>=2.8.1; extra == "dev-torch" +Requires-Dist: datasets>=2.15.0; extra == "dev-torch" +Requires-Dist: ruff==0.13.1; extra == "dev-torch" +Requires-Dist: GitPython<3.1.19; extra == "dev-torch" +Requires-Dist: urllib3<2.0.0; extra == "dev-torch" +Requires-Dist: libcst; extra == "dev-torch" +Requires-Dist: rich; extra == "dev-torch" +Requires-Dist: pandas<2.3.0; extra == "dev-torch" +Requires-Dist: fugashi>=1.0; extra == "dev-torch" +Requires-Dist: ipadic<2.0,>=1.0.0; extra == "dev-torch" +Requires-Dist: unidic_lite>=1.0.7; extra == "dev-torch" +Requires-Dist: unidic>=1.0.2; extra == "dev-torch" +Requires-Dist: sudachipy>=0.6.6; extra == "dev-torch" +Requires-Dist: sudachidict_core>=20220729; extra == "dev-torch" +Requires-Dist: rhoknp<1.3.1,>=1.1.0; extra == "dev-torch" +Requires-Dist: scikit-learn; extra == "dev-torch" +Requires-Dist: cookiecutter==1.7.3; extra == "dev-torch" +Requires-Dist: onnxruntime>=1.4.0; extra == "dev-torch" +Requires-Dist: onnxruntime-tools>=1.4.2; extra == "dev-torch" +Requires-Dist: num2words; extra == "dev-torch" +Provides-Extra: dev-tensorflow +Requires-Dist: pytest>=7.2.0; extra == "dev-tensorflow" +Requires-Dist: pytest-asyncio; extra == "dev-tensorflow" +Requires-Dist: pytest-rich; extra == "dev-tensorflow" +Requires-Dist: pytest-xdist; extra == "dev-tensorflow" +Requires-Dist: pytest-order; extra == "dev-tensorflow" +Requires-Dist: pytest-rerunfailures<16.0; extra == "dev-tensorflow" +Requires-Dist: timeout-decorator; extra == "dev-tensorflow" +Requires-Dist: parameterized>=0.9; extra == "dev-tensorflow" +Requires-Dist: psutil; extra == "dev-tensorflow" +Requires-Dist: datasets>=2.15.0; extra == "dev-tensorflow" +Requires-Dist: dill<0.3.5; extra == "dev-tensorflow" +Requires-Dist: evaluate>=0.2.0; extra == "dev-tensorflow" +Requires-Dist: pytest-timeout; extra == "dev-tensorflow" +Requires-Dist: ruff==0.13.1; extra == "dev-tensorflow" +Requires-Dist: rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1; extra == "dev-tensorflow" +Requires-Dist: nltk<=3.8.1; extra == "dev-tensorflow" +Requires-Dist: GitPython<3.1.19; extra == "dev-tensorflow" +Requires-Dist: sacremoses; extra == "dev-tensorflow" +Requires-Dist: rjieba; extra == "dev-tensorflow" +Requires-Dist: beautifulsoup4; extra == "dev-tensorflow" +Requires-Dist: tensorboard; extra == "dev-tensorflow" +Requires-Dist: pydantic>=2; extra == "dev-tensorflow" +Requires-Dist: sentencepiece!=0.1.92,>=0.1.91; extra == "dev-tensorflow" +Requires-Dist: sacrebleu<2.0.0,>=1.4.12; extra == "dev-tensorflow" +Requires-Dist: libcst; extra == "dev-tensorflow" +Requires-Dist: faiss-cpu; extra == "dev-tensorflow" +Requires-Dist: datasets>=2.15.0; extra == "dev-tensorflow" +Requires-Dist: cookiecutter==1.7.3; extra == "dev-tensorflow" +Requires-Dist: mistral-common[opencv]>=1.6.3; extra == "dev-tensorflow" +Requires-Dist: openai>=1.98.0; extra == "dev-tensorflow" +Requires-Dist: pydantic>=2; extra == "dev-tensorflow" +Requires-Dist: uvicorn; extra == "dev-tensorflow" +Requires-Dist: fastapi; extra == "dev-tensorflow" +Requires-Dist: starlette; extra == "dev-tensorflow" +Requires-Dist: torch>=2.2; extra == "dev-tensorflow" +Requires-Dist: accelerate>=0.26.0; extra == "dev-tensorflow" +Requires-Dist: tensorflow<2.16,>2.9; extra == "dev-tensorflow" +Requires-Dist: onnxconverter-common; extra == "dev-tensorflow" +Requires-Dist: tf2onnx; extra == "dev-tensorflow" +Requires-Dist: tensorflow-text<2.16; extra == "dev-tensorflow" +Requires-Dist: keras-nlp<0.14.0,>=0.3.1; extra == "dev-tensorflow" +Requires-Dist: sentencepiece!=0.1.92,>=0.1.91; extra == "dev-tensorflow" +Requires-Dist: protobuf; extra == "dev-tensorflow" +Requires-Dist: tokenizers<=0.23.0,>=0.22.0; extra == "dev-tensorflow" +Requires-Dist: Pillow<=15.0,>=10.0.1; extra == "dev-tensorflow" +Requires-Dist: datasets>=2.15.0; extra == "dev-tensorflow" +Requires-Dist: ruff==0.13.1; extra == "dev-tensorflow" +Requires-Dist: GitPython<3.1.19; extra == "dev-tensorflow" +Requires-Dist: urllib3<2.0.0; extra == "dev-tensorflow" +Requires-Dist: libcst; extra == "dev-tensorflow" +Requires-Dist: rich; extra == "dev-tensorflow" +Requires-Dist: pandas<2.3.0; extra == "dev-tensorflow" +Requires-Dist: scikit-learn; extra == "dev-tensorflow" +Requires-Dist: cookiecutter==1.7.3; extra == "dev-tensorflow" +Requires-Dist: onnxconverter-common; extra == "dev-tensorflow" +Requires-Dist: tf2onnx; extra == "dev-tensorflow" +Requires-Dist: onnxruntime>=1.4.0; extra == "dev-tensorflow" +Requires-Dist: onnxruntime-tools>=1.4.2; extra == "dev-tensorflow" +Requires-Dist: librosa; extra == "dev-tensorflow" +Requires-Dist: pyctcdecode>=0.4.0; extra == "dev-tensorflow" +Requires-Dist: phonemizer; extra == "dev-tensorflow" +Requires-Dist: kenlm; extra == "dev-tensorflow" +Provides-Extra: dev +Requires-Dist: tensorflow<2.16,>2.9; extra == "dev" +Requires-Dist: onnxconverter-common; extra == "dev" +Requires-Dist: tf2onnx; extra == "dev" +Requires-Dist: tensorflow-text<2.16; extra == "dev" +Requires-Dist: keras-nlp<0.14.0,>=0.3.1; extra == "dev" +Requires-Dist: torch>=2.2; extra == "dev" +Requires-Dist: accelerate>=0.26.0; extra == "dev" +Requires-Dist: jax<=0.4.13,>=0.4.1; extra == "dev" +Requires-Dist: jaxlib<=0.4.13,>=0.4.1; extra == "dev" +Requires-Dist: flax<=0.7.0,>=0.4.1; extra == "dev" +Requires-Dist: optax<=0.1.4,>=0.0.8; extra == "dev" +Requires-Dist: scipy<1.13.0; extra == "dev" +Requires-Dist: sentencepiece!=0.1.92,>=0.1.91; extra == "dev" +Requires-Dist: protobuf; extra == "dev" +Requires-Dist: tokenizers<=0.23.0,>=0.22.0; extra == "dev" +Requires-Dist: torchaudio; extra == "dev" +Requires-Dist: librosa; extra == "dev" +Requires-Dist: pyctcdecode>=0.4.0; extra == "dev" +Requires-Dist: phonemizer; extra == "dev" +Requires-Dist: kenlm; extra == "dev" +Requires-Dist: Pillow<=15.0,>=10.0.1; extra == "dev" +Requires-Dist: kernels<=0.9,>=0.6.1; extra == "dev" +Requires-Dist: optuna; extra == "dev" +Requires-Dist: ray[tune]>=2.7.0; extra == "dev" +Requires-Dist: timm!=1.0.18,<=1.0.19; extra == "dev" +Requires-Dist: torchvision; extra == "dev" +Requires-Dist: Pillow<=15.0,>=10.0.1; extra == "dev" +Requires-Dist: codecarbon>=2.8.1; extra == "dev" +Requires-Dist: accelerate>=0.26.0; extra == "dev" +Requires-Dist: av; extra == "dev" +Requires-Dist: num2words; extra == "dev" +Requires-Dist: mistral-common[opencv]>=1.6.3; extra == "dev" +Requires-Dist: jinja2>=3.1.0; extra == "dev" +Requires-Dist: pytest>=7.2.0; extra == "dev" +Requires-Dist: pytest-asyncio; extra == "dev" +Requires-Dist: pytest-rich; extra == "dev" +Requires-Dist: pytest-xdist; extra == "dev" +Requires-Dist: pytest-order; extra == "dev" +Requires-Dist: pytest-rerunfailures<16.0; extra == "dev" +Requires-Dist: timeout-decorator; extra == "dev" +Requires-Dist: parameterized>=0.9; extra == "dev" +Requires-Dist: psutil; extra == "dev" +Requires-Dist: datasets>=2.15.0; extra == "dev" +Requires-Dist: dill<0.3.5; extra == "dev" +Requires-Dist: evaluate>=0.2.0; extra == "dev" +Requires-Dist: pytest-timeout; extra == "dev" +Requires-Dist: ruff==0.13.1; extra == "dev" +Requires-Dist: rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1; extra == "dev" +Requires-Dist: nltk<=3.8.1; extra == "dev" +Requires-Dist: GitPython<3.1.19; extra == "dev" +Requires-Dist: sacremoses; extra == "dev" +Requires-Dist: rjieba; extra == "dev" +Requires-Dist: beautifulsoup4; extra == "dev" +Requires-Dist: tensorboard; extra == "dev" +Requires-Dist: pydantic>=2; extra == "dev" +Requires-Dist: sentencepiece!=0.1.92,>=0.1.91; extra == "dev" +Requires-Dist: sacrebleu<2.0.0,>=1.4.12; extra == "dev" +Requires-Dist: libcst; extra == "dev" +Requires-Dist: faiss-cpu; extra == "dev" +Requires-Dist: datasets>=2.15.0; extra == "dev" +Requires-Dist: cookiecutter==1.7.3; extra == "dev" +Requires-Dist: mistral-common[opencv]>=1.6.3; extra == "dev" +Requires-Dist: openai>=1.98.0; extra == "dev" +Requires-Dist: pydantic>=2; extra == "dev" +Requires-Dist: uvicorn; extra == "dev" +Requires-Dist: fastapi; extra == "dev" +Requires-Dist: starlette; extra == "dev" +Requires-Dist: torch>=2.2; extra == "dev" +Requires-Dist: accelerate>=0.26.0; extra == "dev" +Requires-Dist: datasets>=2.15.0; extra == "dev" +Requires-Dist: ruff==0.13.1; extra == "dev" +Requires-Dist: GitPython<3.1.19; extra == "dev" +Requires-Dist: urllib3<2.0.0; extra == "dev" +Requires-Dist: libcst; extra == "dev" +Requires-Dist: rich; extra == "dev" +Requires-Dist: pandas<2.3.0; extra == "dev" +Requires-Dist: fugashi>=1.0; extra == "dev" +Requires-Dist: ipadic<2.0,>=1.0.0; extra == "dev" +Requires-Dist: unidic_lite>=1.0.7; extra == "dev" +Requires-Dist: unidic>=1.0.2; extra == "dev" +Requires-Dist: sudachipy>=0.6.6; extra == "dev" +Requires-Dist: sudachidict_core>=20220729; extra == "dev" +Requires-Dist: rhoknp<1.3.1,>=1.1.0; extra == "dev" +Requires-Dist: scikit-learn; extra == "dev" +Requires-Dist: cookiecutter==1.7.3; extra == "dev" +Provides-Extra: torchhub +Requires-Dist: filelock; extra == "torchhub" +Requires-Dist: huggingface-hub<1.0,>=0.34.0; extra == "torchhub" +Requires-Dist: importlib_metadata; extra == "torchhub" +Requires-Dist: numpy>=1.17; extra == "torchhub" +Requires-Dist: packaging>=20.0; extra == "torchhub" +Requires-Dist: protobuf; extra == "torchhub" +Requires-Dist: regex!=2019.12.17; extra == "torchhub" +Requires-Dist: requests; extra == "torchhub" +Requires-Dist: sentencepiece!=0.1.92,>=0.1.91; extra == "torchhub" +Requires-Dist: torch>=2.2; extra == "torchhub" +Requires-Dist: tokenizers<=0.23.0,>=0.22.0; extra == "torchhub" +Requires-Dist: tqdm>=4.27; extra == "torchhub" +Provides-Extra: benchmark +Requires-Dist: optimum-benchmark>=0.3.0; extra == "benchmark" +Provides-Extra: open-telemetry +Requires-Dist: opentelemetry-api; extra == "open-telemetry" +Requires-Dist: opentelemetry-exporter-otlp; extra == "open-telemetry" +Requires-Dist: opentelemetry-sdk; extra == "open-telemetry" +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: description-content-type +Dynamic: home-page +Dynamic: keywords +Dynamic: license +Dynamic: license-file +Dynamic: provides-extra +Dynamic: requires-dist +Dynamic: requires-python +Dynamic: summary + + + +

+ + + + Hugging Face Transformers Library + +
+
+

+ +

+ Checkpoints on Hub + Build + GitHub + Documentation + GitHub release + Contributor Covenant + DOI +

+ +

+

+ English | + 简体中文 | + 繁體中文 | + 한국어 | + Español | + 日本語 | + हिन्दी | + Русский | + Português | + తెలుగు | + Français | + Deutsch | + Italiano | + Tiếng Việt | + العربية | + اردو | + বাংলা | +

+

+ +

+

State-of-the-art pretrained models for inference and training

+

+ +

+ +

+ +Transformers acts as the model-definition framework for state-of-the-art machine learning models in text, computer +vision, audio, video, and multimodal model, for both inference and training. + +It centralizes the model definition so that this definition is agreed upon across the ecosystem. `transformers` is the +pivot across frameworks: if a model definition is supported, it will be compatible with the majority of training +frameworks (Axolotl, Unsloth, DeepSpeed, FSDP, PyTorch-Lightning, ...), inference engines (vLLM, SGLang, TGI, ...), +and adjacent modeling libraries (llama.cpp, mlx, ...) which leverage the model definition from `transformers`. + +We pledge to help support new state-of-the-art models and democratize their usage by having their model definition be +simple, customizable, and efficient. + +There are over 1M+ Transformers [model checkpoints](https://huggingface.co/models?library=transformers&sort=trending) on the [Hugging Face Hub](https://huggingface.com/models) you can use. + +Explore the [Hub](https://huggingface.com/) today to find a model and use Transformers to help you get started right away. + +## Installation + +Transformers works with Python 3.9+ [PyTorch](https://pytorch.org/get-started/locally/) 2.1+, [TensorFlow](https://www.tensorflow.org/install/pip) 2.6+, and [Flax](https://flax.readthedocs.io/en/latest/) 0.4.1+. + +Create and activate a virtual environment with [venv](https://docs.python.org/3/library/venv.html) or [uv](https://docs.astral.sh/uv/), a fast Rust-based Python package and project manager. + +```py +# venv +python -m venv .my-env +source .my-env/bin/activate +# uv +uv venv .my-env +source .my-env/bin/activate +``` + +Install Transformers in your virtual environment. + +```py +# pip +pip install "transformers[torch]" + +# uv +uv pip install "transformers[torch]" +``` + +Install Transformers from source if you want the latest changes in the library or are interested in contributing. However, the *latest* version may not be stable. Feel free to open an [issue](https://github.com/huggingface/transformers/issues) if you encounter an error. + +```shell +git clone https://github.com/huggingface/transformers.git +cd transformers + +# pip +pip install '.[torch]' + +# uv +uv pip install '.[torch]' +``` + +## Quickstart + +Get started with Transformers right away with the [Pipeline](https://huggingface.co/docs/transformers/pipeline_tutorial) API. The `Pipeline` is a high-level inference class that supports text, audio, vision, and multimodal tasks. It handles preprocessing the input and returns the appropriate output. + +Instantiate a pipeline and specify model to use for text generation. The model is downloaded and cached so you can easily reuse it again. Finally, pass some text to prompt the model. + +```py +from transformers import pipeline + +pipeline = pipeline(task="text-generation", model="Qwen/Qwen2.5-1.5B") +pipeline("the secret to baking a really good cake is ") +[{'generated_text': 'the secret to baking a really good cake is 1) to use the right ingredients and 2) to follow the recipe exactly. the recipe for the cake is as follows: 1 cup of sugar, 1 cup of flour, 1 cup of milk, 1 cup of butter, 1 cup of eggs, 1 cup of chocolate chips. if you want to make 2 cakes, how much sugar do you need? To make 2 cakes, you will need 2 cups of sugar.'}] +``` + +To chat with a model, the usage pattern is the same. The only difference is you need to construct a chat history (the input to `Pipeline`) between you and the system. + +> [!TIP] +> You can also chat with a model directly from the command line. +> ```shell +> transformers chat Qwen/Qwen2.5-0.5B-Instruct +> ``` + +```py +import torch +from transformers import pipeline + +chat = [ + {"role": "system", "content": "You are a sassy, wise-cracking robot as imagined by Hollywood circa 1986."}, + {"role": "user", "content": "Hey, can you tell me any fun things to do in New York?"} +] + +pipeline = pipeline(task="text-generation", model="meta-llama/Meta-Llama-3-8B-Instruct", dtype=torch.bfloat16, device_map="auto") +response = pipeline(chat, max_new_tokens=512) +print(response[0]["generated_text"][-1]["content"]) +``` + +Expand the examples below to see how `Pipeline` works for different modalities and tasks. + +
+Automatic speech recognition + +```py +from transformers import pipeline + +pipeline = pipeline(task="automatic-speech-recognition", model="openai/whisper-large-v3") +pipeline("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac") +{'text': ' I have a dream that one day this nation will rise up and live out the true meaning of its creed.'} +``` + +
+ +
+Image classification + +

+ +

+ +```py +from transformers import pipeline + +pipeline = pipeline(task="image-classification", model="facebook/dinov2-small-imagenet1k-1-layer") +pipeline("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png") +[{'label': 'macaw', 'score': 0.997848391532898}, + {'label': 'sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita', + 'score': 0.0016551691805943847}, + {'label': 'lorikeet', 'score': 0.00018523589824326336}, + {'label': 'African grey, African gray, Psittacus erithacus', + 'score': 7.85409429227002e-05}, + {'label': 'quail', 'score': 5.502637941390276e-05}] +``` + +
+ +
+Visual question answering + +

+ +

+ +```py +from transformers import pipeline + +pipeline = pipeline(task="visual-question-answering", model="Salesforce/blip-vqa-base") +pipeline( + image="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/idefics-few-shot.jpg", + question="What is in the image?", +) +[{'answer': 'statue of liberty'}] +``` + +
+ +## Why should I use Transformers? + +1. Easy-to-use state-of-the-art models: + - High performance on natural language understanding & generation, computer vision, audio, video, and multimodal tasks. + - Low barrier to entry for researchers, engineers, and developers. + - Few user-facing abstractions with just three classes to learn. + - A unified API for using all our pretrained models. + +1. Lower compute costs, smaller carbon footprint: + - Share trained models instead of training from scratch. + - Reduce compute time and production costs. + - Dozens of model architectures with 1M+ pretrained checkpoints across all modalities. + +1. Choose the right framework for every part of a models lifetime: + - Train state-of-the-art models in 3 lines of code. + - Move a single model between PyTorch/JAX/TF2.0 frameworks at will. + - Pick the right framework for training, evaluation, and production. + +1. Easily customize a model or an example to your needs: + - We provide examples for each architecture to reproduce the results published by its original authors. + - Model internals are exposed as consistently as possible. + - Model files can be used independently of the library for quick experiments. + + + Hugging Face Enterprise Hub +
+ +## Why shouldn't I use Transformers? + +- This library is not a modular toolbox of building blocks for neural nets. The code in the model files is not refactored with additional abstractions on purpose, so that researchers can quickly iterate on each of the models without diving into additional abstractions/files. +- The training API is optimized to work with PyTorch models provided by Transformers. For generic machine learning loops, you should use another library like [Accelerate](https://huggingface.co/docs/accelerate). +- The [example scripts](https://github.com/huggingface/transformers/tree/main/examples) are only *examples*. They may not necessarily work out-of-the-box on your specific use case and you'll need to adapt the code for it to work. + +## 100 projects using Transformers + +Transformers is more than a toolkit to use pretrained models, it's a community of projects built around it and the +Hugging Face Hub. We want Transformers to enable developers, researchers, students, professors, engineers, and anyone +else to build their dream projects. + +In order to celebrate Transformers 100,000 stars, we wanted to put the spotlight on the +community with the [awesome-transformers](./awesome-transformers.md) page which lists 100 +incredible projects built with Transformers. + +If you own or use a project that you believe should be part of the list, please open a PR to add it! + +## Example models + +You can test most of our models directly on their [Hub model pages](https://huggingface.co/models). + +Expand each modality below to see a few example models for various use cases. + +
+Audio + +- Audio classification with [Whisper](https://huggingface.co/openai/whisper-large-v3-turbo) +- Automatic speech recognition with [Moonshine](https://huggingface.co/UsefulSensors/moonshine) +- Keyword spotting with [Wav2Vec2](https://huggingface.co/superb/wav2vec2-base-superb-ks) +- Speech to speech generation with [Moshi](https://huggingface.co/kyutai/moshiko-pytorch-bf16) +- Text to audio with [MusicGen](https://huggingface.co/facebook/musicgen-large) +- Text to speech with [Bark](https://huggingface.co/suno/bark) + +
+ +
+Computer vision + +- Automatic mask generation with [SAM](https://huggingface.co/facebook/sam-vit-base) +- Depth estimation with [DepthPro](https://huggingface.co/apple/DepthPro-hf) +- Image classification with [DINO v2](https://huggingface.co/facebook/dinov2-base) +- Keypoint detection with [SuperPoint](https://huggingface.co/magic-leap-community/superpoint) +- Keypoint matching with [SuperGlue](https://huggingface.co/magic-leap-community/superglue_outdoor) +- Object detection with [RT-DETRv2](https://huggingface.co/PekingU/rtdetr_v2_r50vd) +- Pose Estimation with [VitPose](https://huggingface.co/usyd-community/vitpose-base-simple) +- Universal segmentation with [OneFormer](https://huggingface.co/shi-labs/oneformer_ade20k_swin_large) +- Video classification with [VideoMAE](https://huggingface.co/MCG-NJU/videomae-large) + +
+ +
+Multimodal + +- Audio or text to text with [Qwen2-Audio](https://huggingface.co/Qwen/Qwen2-Audio-7B) +- Document question answering with [LayoutLMv3](https://huggingface.co/microsoft/layoutlmv3-base) +- Image or text to text with [Qwen-VL](https://huggingface.co/Qwen/Qwen2.5-VL-3B-Instruct) +- Image captioning [BLIP-2](https://huggingface.co/Salesforce/blip2-opt-2.7b) +- OCR-based document understanding with [GOT-OCR2](https://huggingface.co/stepfun-ai/GOT-OCR-2.0-hf) +- Table question answering with [TAPAS](https://huggingface.co/google/tapas-base) +- Unified multimodal understanding and generation with [Emu3](https://huggingface.co/BAAI/Emu3-Gen) +- Vision to text with [Llava-OneVision](https://huggingface.co/llava-hf/llava-onevision-qwen2-0.5b-ov-hf) +- Visual question answering with [Llava](https://huggingface.co/llava-hf/llava-1.5-7b-hf) +- Visual referring expression segmentation with [Kosmos-2](https://huggingface.co/microsoft/kosmos-2-patch14-224) + +
+ +
+NLP + +- Masked word completion with [ModernBERT](https://huggingface.co/answerdotai/ModernBERT-base) +- Named entity recognition with [Gemma](https://huggingface.co/google/gemma-2-2b) +- Question answering with [Mixtral](https://huggingface.co/mistralai/Mixtral-8x7B-v0.1) +- Summarization with [BART](https://huggingface.co/facebook/bart-large-cnn) +- Translation with [T5](https://huggingface.co/google-t5/t5-base) +- Text generation with [Llama](https://huggingface.co/meta-llama/Llama-3.2-1B) +- Text classification with [Qwen](https://huggingface.co/Qwen/Qwen2.5-0.5B) + +
+ +## Citation + +We now have a [paper](https://www.aclweb.org/anthology/2020.emnlp-demos.6/) you can cite for the 🤗 Transformers library: +```bibtex +@inproceedings{wolf-etal-2020-transformers, + title = "Transformers: State-of-the-Art Natural Language Processing", + author = "Thomas Wolf and Lysandre Debut and Victor Sanh and Julien Chaumond and Clement Delangue and Anthony Moi and Pierric Cistac and Tim Rault and Rémi Louf and Morgan Funtowicz and Joe Davison and Sam Shleifer and Patrick von Platen and Clara Ma and Yacine Jernite and Julien Plu and Canwen Xu and Teven Le Scao and Sylvain Gugger and Mariama Drame and Quentin Lhoest and Alexander M. Rush", + booktitle = "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing: System Demonstrations", + month = oct, + year = "2020", + address = "Online", + publisher = "Association for Computational Linguistics", + url = "https://www.aclweb.org/anthology/2020.emnlp-demos.6", + pages = "38--45" +} +``` diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers-4.57.6.dist-info/RECORD b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers-4.57.6.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..82857860babe867f2f91dfeca28f882ce06ba77d --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers-4.57.6.dist-info/RECORD @@ -0,0 +1,4463 @@ +../../../bin/transformers,sha256=AufuXtrDnN12vRh3hHo_RXrfuyyUweNHINrx14zpys0,271 +../../../bin/transformers-cli,sha256=WgJZXsz3vGhPA1eQ_DP-g5PThorxj-FOpICsjCexeC8,279 +transformers-4.57.6.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +transformers-4.57.6.dist-info/METADATA,sha256=kWAQRKdP4CVxqCU1Z1Tbuqnh0-PdPCI3JUwV6QPkIeM,43991 +transformers-4.57.6.dist-info/RECORD,, +transformers-4.57.6.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91 +transformers-4.57.6.dist-info/entry_points.txt,sha256=Zra3dVQyt6Q3fU_suoD3gF81JV3WeV8gH66vzoev408,144 +transformers-4.57.6.dist-info/licenses/LICENSE,sha256=d_1HEN757DwPYiWADgI18VpCWr1KiwNVkSf814JhIEk,11418 +transformers-4.57.6.dist-info/top_level.txt,sha256=GLBaeTo_CSdhnHvbxQ0kzpEHdlLuA_33foIogaWxntI,13 +transformers/__init__.py,sha256=qoy1TaSIz0O6N7mVW7bA2E0gANsDBval8cILaEJILQQ,47000 +transformers/__pycache__/__init__.cpython-310.pyc,, +transformers/__pycache__/activations.cpython-310.pyc,, +transformers/__pycache__/activations_tf.cpython-310.pyc,, +transformers/__pycache__/audio_utils.cpython-310.pyc,, +transformers/__pycache__/cache_utils.cpython-310.pyc,, +transformers/__pycache__/configuration_utils.cpython-310.pyc,, +transformers/__pycache__/convert_graph_to_onnx.cpython-310.pyc,, +transformers/__pycache__/convert_slow_tokenizer.cpython-310.pyc,, +transformers/__pycache__/convert_slow_tokenizers_checkpoints_to_fast.cpython-310.pyc,, +transformers/__pycache__/convert_tf_hub_seq_to_seq_bert_to_pytorch.cpython-310.pyc,, +transformers/__pycache__/debug_utils.cpython-310.pyc,, +transformers/__pycache__/dependency_versions_check.cpython-310.pyc,, +transformers/__pycache__/dependency_versions_table.cpython-310.pyc,, +transformers/__pycache__/dynamic_module_utils.cpython-310.pyc,, +transformers/__pycache__/feature_extraction_sequence_utils.cpython-310.pyc,, +transformers/__pycache__/feature_extraction_utils.cpython-310.pyc,, +transformers/__pycache__/file_utils.cpython-310.pyc,, +transformers/__pycache__/hf_argparser.cpython-310.pyc,, +transformers/__pycache__/hyperparameter_search.cpython-310.pyc,, +transformers/__pycache__/image_processing_base.cpython-310.pyc,, +transformers/__pycache__/image_processing_utils.cpython-310.pyc,, +transformers/__pycache__/image_processing_utils_fast.cpython-310.pyc,, +transformers/__pycache__/image_transforms.cpython-310.pyc,, +transformers/__pycache__/image_utils.cpython-310.pyc,, +transformers/__pycache__/keras_callbacks.cpython-310.pyc,, +transformers/__pycache__/masking_utils.cpython-310.pyc,, +transformers/__pycache__/model_debugging_utils.cpython-310.pyc,, +transformers/__pycache__/modelcard.cpython-310.pyc,, +transformers/__pycache__/modeling_attn_mask_utils.cpython-310.pyc,, +transformers/__pycache__/modeling_flash_attention_utils.cpython-310.pyc,, +transformers/__pycache__/modeling_flax_outputs.cpython-310.pyc,, +transformers/__pycache__/modeling_flax_pytorch_utils.cpython-310.pyc,, +transformers/__pycache__/modeling_flax_utils.cpython-310.pyc,, +transformers/__pycache__/modeling_gguf_pytorch_utils.cpython-310.pyc,, +transformers/__pycache__/modeling_layers.cpython-310.pyc,, +transformers/__pycache__/modeling_outputs.cpython-310.pyc,, +transformers/__pycache__/modeling_rope_utils.cpython-310.pyc,, +transformers/__pycache__/modeling_tf_outputs.cpython-310.pyc,, +transformers/__pycache__/modeling_tf_pytorch_utils.cpython-310.pyc,, +transformers/__pycache__/modeling_tf_utils.cpython-310.pyc,, +transformers/__pycache__/modeling_utils.cpython-310.pyc,, +transformers/__pycache__/optimization.cpython-310.pyc,, +transformers/__pycache__/optimization_tf.cpython-310.pyc,, +transformers/__pycache__/processing_utils.cpython-310.pyc,, +transformers/__pycache__/pytorch_utils.cpython-310.pyc,, +transformers/__pycache__/safetensors_conversion.cpython-310.pyc,, +transformers/__pycache__/testing_utils.cpython-310.pyc,, +transformers/__pycache__/tf_utils.cpython-310.pyc,, +transformers/__pycache__/time_series_utils.cpython-310.pyc,, +transformers/__pycache__/tokenization_mistral_common.cpython-310.pyc,, +transformers/__pycache__/tokenization_utils.cpython-310.pyc,, +transformers/__pycache__/tokenization_utils_base.cpython-310.pyc,, +transformers/__pycache__/tokenization_utils_fast.cpython-310.pyc,, +transformers/__pycache__/trainer.cpython-310.pyc,, +transformers/__pycache__/trainer_callback.cpython-310.pyc,, +transformers/__pycache__/trainer_pt_utils.cpython-310.pyc,, +transformers/__pycache__/trainer_seq2seq.cpython-310.pyc,, +transformers/__pycache__/trainer_utils.cpython-310.pyc,, +transformers/__pycache__/training_args.cpython-310.pyc,, +transformers/__pycache__/training_args_seq2seq.cpython-310.pyc,, +transformers/__pycache__/training_args_tf.cpython-310.pyc,, +transformers/__pycache__/video_processing_utils.cpython-310.pyc,, +transformers/__pycache__/video_utils.cpython-310.pyc,, +transformers/activations.py,sha256=PdWoGx5eDFNxJW8A7-wZ31IlVCAxhzfbHgNDCpjPQmQ,13109 +transformers/activations_tf.py,sha256=TGmah3loMs_pERwxpjWb5-AUeHLoBAyDxFYWVuLC7FU,4729 +transformers/audio_utils.py,sha256=wDhFAweo28mpXu2OQTdw80gU-jgFgSHKny7ujdDfqVg,54284 +transformers/cache_utils.py,sha256=9OEcrxTHW976XjADuT7w6Ll_thAzdXBa2USws0TX2oo,67772 +transformers/commands/__init__.py,sha256=aFO3I7C6G9OLA9JZSc_yMaZl0glOQtjNPjqMFfu9wfQ,923 +transformers/commands/__pycache__/__init__.cpython-310.pyc,, +transformers/commands/__pycache__/add_fast_image_processor.cpython-310.pyc,, +transformers/commands/__pycache__/add_new_model_like.cpython-310.pyc,, +transformers/commands/__pycache__/chat.cpython-310.pyc,, +transformers/commands/__pycache__/convert.cpython-310.pyc,, +transformers/commands/__pycache__/download.cpython-310.pyc,, +transformers/commands/__pycache__/env.cpython-310.pyc,, +transformers/commands/__pycache__/run.cpython-310.pyc,, +transformers/commands/__pycache__/serving.cpython-310.pyc,, +transformers/commands/__pycache__/train.cpython-310.pyc,, +transformers/commands/__pycache__/transformers_cli.cpython-310.pyc,, +transformers/commands/add_fast_image_processor.py,sha256=HIVXaU8NERWdsSJuyjnSp8bAnXxHojrwPCegX9IcfYU,24141 +transformers/commands/add_new_model_like.py,sha256=LPGqUn8NQ0hT8IGFpCH4Vp2JcDjLI_UsZUJ7Dq7rngM,33366 +transformers/commands/chat.py,sha256=n8rguI-62QvOKLw_UlSi-ejPoR_B1MfKG0MCzo_YqcU,32326 +transformers/commands/convert.py,sha256=IhyqKqO33anJiIwneOBCogxREJkfH7qIP_3At2xnoVE,7064 +transformers/commands/download.py,sha256=GKPadx-YGBL7dHJSEcUp-QNOP3R2L71-gPGP0z6NNQI,2395 +transformers/commands/env.py,sha256=Y9yncwQsl6QnHpoJ3iiL40hN2STocBzyN46MYyt1vVA,6668 +transformers/commands/run.py,sha256=nyEe2lOoj6e0EOxjKeF08hdW9WVWa101r9hWXl9v3Jo,4249 +transformers/commands/serving.py,sha256=Yq3PZLWdQeKNLSR7gMihl2TtRMh4Wy6sVtHLuFBH3WE,70902 +transformers/commands/train.py,sha256=SDGD_DF2-y9n2sqW2c77j5a4B9Lj8sRWHZ-VU4bnx_U,6337 +transformers/commands/transformers_cli.py,sha256=cFlXM_DHUCFgf6KnjpAcvebihZL5UKKIOlZtixopBVw,2281 +transformers/configuration_utils.py,sha256=CKOInBuKc9NAo3yT9yNG7g44XjObenKgO1wCbUlDuvc,65603 +transformers/convert_graph_to_onnx.py,sha256=g-BvJuYIq2wDmHxQ0Ng2DrpwqNshxAbQNk4zjegX4nw,20130 +transformers/convert_slow_tokenizer.py,sha256=8xMzmAR4DOVMZzISg4tUXYt8OsKY0pMjgLwWa6oi_N8,68698 +transformers/convert_slow_tokenizers_checkpoints_to_fast.py,sha256=Sa8NS-oVEYDgqYEhUfg-WuB4a8RsLReIu067twp8uCA,5061 +transformers/convert_tf_hub_seq_to_seq_bert_to_pytorch.py,sha256=02fwRNsiK3zmmL9O_hgsduomBuTDHWh8vcTyk2GOlz8,2895 +transformers/data/__init__.py,sha256=MuXSchTzRSaUtUDC1uSeDkHiSbjtrQZg4IoKeKHoH6A,1490 +transformers/data/__pycache__/__init__.cpython-310.pyc,, +transformers/data/__pycache__/data_collator.cpython-310.pyc,, +transformers/data/data_collator.py,sha256=IWfYlv3cM6KGQqGeaGzedLf0gIjyEVUw7_u_W605hPQ,105604 +transformers/data/datasets/__init__.py,sha256=PGzUJjdmTPOPMyjV4-Tj3sNrmmh-lspjyxrVbrfJoX8,909 +transformers/data/datasets/__pycache__/__init__.cpython-310.pyc,, +transformers/data/datasets/__pycache__/glue.cpython-310.pyc,, +transformers/data/datasets/__pycache__/language_modeling.cpython-310.pyc,, +transformers/data/datasets/__pycache__/squad.cpython-310.pyc,, +transformers/data/datasets/glue.py,sha256=d2ys4oU49fQJ3ZXLpGGyou54lWOY2UJMUbZcdqaBNxg,6245 +transformers/data/datasets/language_modeling.py,sha256=tNZvgig_gzJzuEjc0wGVQa86Jx2wUaQMATDCBrqN-z8,23709 +transformers/data/datasets/squad.py,sha256=O3g7HTnVqCRNYfmDG_gj5KqwEe2oi2pw5QH7jjOtMPw,9275 +transformers/data/metrics/__init__.py,sha256=o9t_VTQtqU3lEhqvocDzFMm7OvAKD-uxrjPWy0r74BI,3632 +transformers/data/metrics/__pycache__/__init__.cpython-310.pyc,, +transformers/data/metrics/__pycache__/squad_metrics.cpython-310.pyc,, +transformers/data/metrics/squad_metrics.py,sha256=__cjdPU1qt3bjnXq3k6CC2_p_5DxbU8p6I5EL40unrg,29685 +transformers/data/processors/__init__.py,sha256=lvN5mp9mdrr5v6QvZT6VcoZ78zZUvXiumTm6Gdvlgvo,1014 +transformers/data/processors/__pycache__/__init__.cpython-310.pyc,, +transformers/data/processors/__pycache__/glue.cpython-310.pyc,, +transformers/data/processors/__pycache__/squad.cpython-310.pyc,, +transformers/data/processors/__pycache__/utils.cpython-310.pyc,, +transformers/data/processors/__pycache__/xnli.cpython-310.pyc,, +transformers/data/processors/glue.py,sha256=IGwrYOn1sg6mztFzwfA_Eb9KyuvIYL4iYBDe5b-m83Y,23214 +transformers/data/processors/squad.py,sha256=aKeAhkB_zAZliI0n8V4rYHFPGJChND3OZ0AN9wHs2c8,33303 +transformers/data/processors/utils.py,sha256=tljqv-RDmkbfutIo2cUYbJuL75PfXMB3IP2mOM4gQJA,13823 +transformers/data/processors/xnli.py,sha256=sgcYz9YSfHY9NS0LO_YeFRRjq-nJFsDhFUP4NJeu-Q4,3481 +transformers/debug_utils.py,sha256=6m6Ks51IXFlIhEPdbXbsFi_3ZWjM34kpxV5l7-LR4bU,12891 +transformers/dependency_versions_check.py,sha256=6HbgtT2Wp-QZGOAdyUOklHvNA4rOVITGHrX34dtMOqg,2115 +transformers/dependency_versions_table.py,sha256=0rU7PttV_nc9e4Q6NYaxfHW-thBJDwCt8497mqqgWPk,3855 +transformers/distributed/__init__.py,sha256=ds-xiU6Hko8BN-XiIF2cJZPCjrQ-JFlodRARkPK8g-0,978 +transformers/distributed/__pycache__/__init__.cpython-310.pyc,, +transformers/distributed/__pycache__/configuration_utils.cpython-310.pyc,, +transformers/distributed/configuration_utils.py,sha256=rBPisXQ4szdnjxqxtFWOJYjOtnQ7JSCdbWs4_3xA1fU,4438 +transformers/dynamic_module_utils.py,sha256=TNUsqcfh-iJNfXARW50i6io__Y9DzE6pAo28h2oHJg0,36401 +transformers/feature_extraction_sequence_utils.py,sha256=U60TIDSbdFI_MD0Jxoe_aEGrwjoqEafP6eGMYKpF9jE,18273 +transformers/feature_extraction_utils.py,sha256=aGEAnlqhlmdsWzgnrb1ksDwhe8b1HxVg4Nvsvpo2Ht8,30754 +transformers/file_utils.py,sha256=iLp699qwOJKgEAtf1lLU_v26J8jAWC8q5FZ24fpdUd0,3677 +transformers/generation/__init__.py,sha256=KigBJf1VOUTzDzHAZjADHd3lTwt6c9H8vwFGsZxIAFg,12338 +transformers/generation/__pycache__/__init__.cpython-310.pyc,, +transformers/generation/__pycache__/beam_constraints.cpython-310.pyc,, +transformers/generation/__pycache__/beam_search.cpython-310.pyc,, +transformers/generation/__pycache__/candidate_generator.cpython-310.pyc,, +transformers/generation/__pycache__/configuration_utils.cpython-310.pyc,, +transformers/generation/__pycache__/flax_logits_process.cpython-310.pyc,, +transformers/generation/__pycache__/flax_utils.cpython-310.pyc,, +transformers/generation/__pycache__/logits_process.cpython-310.pyc,, +transformers/generation/__pycache__/stopping_criteria.cpython-310.pyc,, +transformers/generation/__pycache__/streamers.cpython-310.pyc,, +transformers/generation/__pycache__/tf_logits_process.cpython-310.pyc,, +transformers/generation/__pycache__/tf_utils.cpython-310.pyc,, +transformers/generation/__pycache__/utils.cpython-310.pyc,, +transformers/generation/__pycache__/watermarking.cpython-310.pyc,, +transformers/generation/beam_constraints.py,sha256=9sxTCZKDyllla5fviGdxYhoNs3LzkfWjZkLSJM4nRJE,19697 +transformers/generation/beam_search.py,sha256=kYMggx0DErcNcJyhQk5k1ZcdqeuZaQ4OxqjtdpeKZhI,48619 +transformers/generation/candidate_generator.py,sha256=mAmghyDWHLDnu5mGheb7mMSw52o_c8wM8HYD1poAlQs,63997 +transformers/generation/configuration_utils.py,sha256=2D8igfk5QCvhYzop88dg4p9dLyhCWNjtmWk7hzdEB0s,76547 +transformers/generation/continuous_batching/__init__.py,sha256=wtrHtJTWy3KgXKgS_HVTLb_fp4jc49HIJ9im4BSy9w8,904 +transformers/generation/continuous_batching/__pycache__/__init__.cpython-310.pyc,, +transformers/generation/continuous_batching/__pycache__/cache.cpython-310.pyc,, +transformers/generation/continuous_batching/__pycache__/cache_manager.cpython-310.pyc,, +transformers/generation/continuous_batching/__pycache__/continuous_api.cpython-310.pyc,, +transformers/generation/continuous_batching/__pycache__/requests.cpython-310.pyc,, +transformers/generation/continuous_batching/__pycache__/scheduler.cpython-310.pyc,, +transformers/generation/continuous_batching/cache.py,sha256=cfJCyUrB6lwVSolTf1HHYFeNBsqRyszkAScZgL37-uI,31301 +transformers/generation/continuous_batching/cache_manager.py,sha256=5pQSxyCFtaxVWSo2v25p4QlaTKg9ThsFwBm-jvN4Nzo,11924 +transformers/generation/continuous_batching/continuous_api.py,sha256=vXAxb04jsIoOze2MKHn--IXF8nUHuR1TOGI0tT92YRk,45598 +transformers/generation/continuous_batching/requests.py,sha256=UM7p9Gxr-C8UOYL_LH_AgIER_g9ASVFQo9UIGHSyWkA,8538 +transformers/generation/continuous_batching/scheduler.py,sha256=O1zh9JHCmXwmEjFY6_oNvt5aSOPqB-1LVH9mvbOxtJs,13833 +transformers/generation/flax_logits_process.py,sha256=d9K9Np1169WLpcXRnS_MwtWVKNAgDzKSA2fq5rom9FI,23008 +transformers/generation/flax_utils.py,sha256=09KCRqcCYW-BSbvgRDdmFSz1JL39INSnvKicKZ42T64,50642 +transformers/generation/logits_process.py,sha256=ZIFQZin_bwIRV-iT_GTE57WwanIHJ3GAnWeTh8tUpLE,152357 +transformers/generation/stopping_criteria.py,sha256=SVYo5Mh39mf7vZ7UzIO2gN6erCq8l-w5A_bpIZrz7NI,28930 +transformers/generation/streamers.py,sha256=Mj_bPFPCh4225Z_oFLc5wLegJPCUzF83ppojDdh19mA,12985 +transformers/generation/tf_logits_process.py,sha256=q9KY6Fx6pfQ15_7Lm_oAD4_Eyr3ApM4pmhjeNcNeF4M,28639 +transformers/generation/tf_utils.py,sha256=6B48u3CpCO7AEtSdhSxOjNVfqDpzcIIQqNR9NmTUCbo,175687 +transformers/generation/utils.py,sha256=Vf1cUKp4XiJq-gPkUHuNJ8AyhxTAvQSLxgr56IE6EXM,210172 +transformers/generation/watermarking.py,sha256=dX_al3SIfnORmQrZMgkEzVahdI8WLpW7d4i2rdwakAM,24497 +transformers/hf_argparser.py,sha256=OHuQjhZ-v_xC7-yQ0byk4clszsAdTe4KSCgpOWyOkTY,19814 +transformers/hyperparameter_search.py,sha256=1PGHNbFHqQD8Y0FSWgDec6OxbzJWJCJe2uWDX5r4vwE,4194 +transformers/image_processing_base.py,sha256=w3Zq2w3wjKrG8nj1N4wYZCBa87ldie86zdhmyABw8k8,24947 +transformers/image_processing_utils.py,sha256=dA0f7L3ySYNThEOyTZIVtQxJS4q-1GA0a82PPD1p0kk,13787 +transformers/image_processing_utils_fast.py,sha256=A4pKqeV3Fr5GoYgi9fL5d8iludDpzD22PwMs3a_X0aw,32864 +transformers/image_transforms.py,sha256=iOVfcNSUBNhbTMo7CCa_niljDrCvuCjTf0NHwfsHmG4,41515 +transformers/image_utils.py,sha256=TuSwPrm8nZstiCwOw5ctgooPwa-WIPNKydGW3cgWxH0,37886 +transformers/integrations/__init__.py,sha256=wZwGxaqGuJQ3nXPwOudGvKy0ZxIpQ0IjGIjz86JeM64,9565 +transformers/integrations/__pycache__/__init__.cpython-310.pyc,, +transformers/integrations/__pycache__/accelerate.cpython-310.pyc,, +transformers/integrations/__pycache__/aqlm.cpython-310.pyc,, +transformers/integrations/__pycache__/awq.cpython-310.pyc,, +transformers/integrations/__pycache__/bitnet.cpython-310.pyc,, +transformers/integrations/__pycache__/bitsandbytes.cpython-310.pyc,, +transformers/integrations/__pycache__/deepspeed.cpython-310.pyc,, +transformers/integrations/__pycache__/eager_paged.cpython-310.pyc,, +transformers/integrations/__pycache__/eetq.cpython-310.pyc,, +transformers/integrations/__pycache__/executorch.cpython-310.pyc,, +transformers/integrations/__pycache__/fbgemm_fp8.cpython-310.pyc,, +transformers/integrations/__pycache__/finegrained_fp8.cpython-310.pyc,, +transformers/integrations/__pycache__/flash_attention.cpython-310.pyc,, +transformers/integrations/__pycache__/flash_paged.cpython-310.pyc,, +transformers/integrations/__pycache__/flex_attention.cpython-310.pyc,, +transformers/integrations/__pycache__/fp_quant.cpython-310.pyc,, +transformers/integrations/__pycache__/fsdp.cpython-310.pyc,, +transformers/integrations/__pycache__/ggml.cpython-310.pyc,, +transformers/integrations/__pycache__/higgs.cpython-310.pyc,, +transformers/integrations/__pycache__/hqq.cpython-310.pyc,, +transformers/integrations/__pycache__/hub_kernels.cpython-310.pyc,, +transformers/integrations/__pycache__/integration_utils.cpython-310.pyc,, +transformers/integrations/__pycache__/mistral.cpython-310.pyc,, +transformers/integrations/__pycache__/mxfp4.cpython-310.pyc,, +transformers/integrations/__pycache__/npu_flash_attention.cpython-310.pyc,, +transformers/integrations/__pycache__/peft.cpython-310.pyc,, +transformers/integrations/__pycache__/quanto.cpython-310.pyc,, +transformers/integrations/__pycache__/sdpa_attention.cpython-310.pyc,, +transformers/integrations/__pycache__/sdpa_paged.cpython-310.pyc,, +transformers/integrations/__pycache__/spqr.cpython-310.pyc,, +transformers/integrations/__pycache__/tensor_parallel.cpython-310.pyc,, +transformers/integrations/__pycache__/tiktoken.cpython-310.pyc,, +transformers/integrations/__pycache__/tpu.cpython-310.pyc,, +transformers/integrations/__pycache__/vptq.cpython-310.pyc,, +transformers/integrations/accelerate.py,sha256=nEQ-TMOFaXomnuKMogrzU_J4PNCZM-Bs6GPddPGbuW0,7351 +transformers/integrations/aqlm.py,sha256=T2gpCoj62L5hkyJzm6tJlP_emhJlepezKN4y1HWueVI,4535 +transformers/integrations/awq.py,sha256=gIAEOj3Tepd_eQadBbPkeMpRlHc3it4tDFzQf8XOKF4,20579 +transformers/integrations/bitnet.py,sha256=-AQ7JCa7cOcuq4tGreVgyME_k7i3D5BVUT9OYM-tg-w,15718 +transformers/integrations/bitsandbytes.py,sha256=UR7BOYCcnYDgiyrmzXzLQ5EIdTK8HxtNlDtZMNqeVHo,23901 +transformers/integrations/deepspeed.py,sha256=MFlCBFGbgjAxVhLmfwzJhNjfXB5zbZHIkuWIQjZqbq8,21947 +transformers/integrations/eager_paged.py,sha256=g7xiagZUuQ8Q2KUBx93GaOO9KEl5rtUlxP9efJB4MFk,3103 +transformers/integrations/eetq.py,sha256=wpofdy55HcvaTaOXrO_VMbmG1Rfly-kN1JfzOxw5X0U,5364 +transformers/integrations/executorch.py,sha256=fMMR8i5MIlnKf2WdV0d51SwwGUFEi80GJ5diLAo-Wc8,52326 +transformers/integrations/fbgemm_fp8.py,sha256=jwTi8hC_Y12YSKktXqUktCCtl_qO-Ncx3uvIyFcni1o,12441 +transformers/integrations/finegrained_fp8.py,sha256=AlhRxjh7bjn-0DwonNrWhiXtBQiClrrF3hHJf3dlYLw,15120 +transformers/integrations/flash_attention.py,sha256=hQqmP5RzORGIw1dFTPtqiTOTlNJvYCTMviRvAPY0QUQ,3125 +transformers/integrations/flash_paged.py,sha256=PM-_ZnoakIdt2wvHzTACkypYB8od_Vw2hemTZByj0yw,4207 +transformers/integrations/flex_attention.py,sha256=5SAf4xKtGRQvfRTPPiVrLIL0WuFOcz-i5H6Kc7vPQVg,13705 +transformers/integrations/fp_quant.py,sha256=0Sx__hSavZ03loZVojEt5deAOzCmuYNn_5aa59zSlFI,1803 +transformers/integrations/fsdp.py,sha256=Fs0aCRYb5JZqKhzWPbL8Jgy4VRbgduhhqLdAjzKCqrs,1545 +transformers/integrations/ggml.py,sha256=jM8LXEYkwteFwJRIhonrgME1lMcMB2C_plHB9B7LrOM,30350 +transformers/integrations/higgs.py,sha256=1pVz1EMhoRj-ro2ls8BY_dS2TfaJ_TrXyBg6J6LWH5Q,31542 +transformers/integrations/hqq.py,sha256=GeTogGSqPyrgTvTHzxwt5TZhpc1vRj_lb2DdWy5BKkI,5075 +transformers/integrations/hub_kernels.py,sha256=hF8z7ya-kV9i76gqrzaVvybm4WXrXkmiVCrk_GnqFUs,8290 +transformers/integrations/integration_utils.py,sha256=UwY2zNLq_kXUu8nIrbUjZgqD1y41NtHLPP8wY5LdsQM,113012 +transformers/integrations/mistral.py,sha256=9xon0VjpAnoOcHhsBhQgEiLSN7ptBkNeXBqN9mI4O3s,3970 +transformers/integrations/mxfp4.py,sha256=GvdwUiBPtmpszxRY4S6G-g2zutZR2qg6c5UaUqSAe1U,18439 +transformers/integrations/npu_flash_attention.py,sha256=5YBiW6jSW1dlYP-0dLfQJ0XFcX5zqLRUS6qRlESf5s4,4189 +transformers/integrations/peft.py,sha256=5XIr8Jd_JuNZx4VUTZKZRpyi7TQ8bRqJ6cFfLi6RVkw,28965 +transformers/integrations/quanto.py,sha256=m3tz7fCciceEe3mJc1i8GNVWcKTQ--GopPGwU4ctZ4I,4377 +transformers/integrations/sdpa_attention.py,sha256=3Fq-SamN7DuQJnOd-_LpqPPlJyspFrPC1ARyeskxoBM,5163 +transformers/integrations/sdpa_paged.py,sha256=h58QJ-6ftXQbw0XCFy2L8-KZpJww0eynvJQMkzvJ-KA,2193 +transformers/integrations/spqr.py,sha256=nHTdlyfkCc5vJO60TMZuE9pUiTTPfaqYV7kVLF6PMd0,5525 +transformers/integrations/tensor_parallel.py,sha256=c6Y8fE4XC9wvsE9Km_Z9TdnBogBf4KAqVDnSBEUHv2o,49481 +transformers/integrations/tiktoken.py,sha256=2s3O3_3dsA7pbsz1Lu_eLA2SrloMZWVpg0NklRxPMlY,1627 +transformers/integrations/tpu.py,sha256=JtzQLGX0mnci_xKVxoXPDqrAT_YLSCaw2WK-4IssCu4,1394 +transformers/integrations/vptq.py,sha256=he6YX2nhHu0kBzA9-F6QU-WEjEMi0B7v__zEJTn66X8,4540 +transformers/keras_callbacks.py,sha256=M9ZvQaJ52k79RlgM7WNootiXoD_hNirmiMNaPxI3tik,20611 +transformers/kernels/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +transformers/kernels/__pycache__/__init__.cpython-310.pyc,, +transformers/kernels/deta/cpu/ms_deform_attn_cpu.cpp,sha256=VcCGm9IrvgVvmyZt0KyP16Q-ONmbeg6bKwccP6KadL0,1255 +transformers/kernels/deta/cpu/ms_deform_attn_cpu.h,sha256=nvVsKj9nabQ7IaNY4di5xVx6u-0lIifQvLg2JCoxiik,1138 +transformers/kernels/deta/cuda/ms_deform_attn_cuda.cu,sha256=M5-bW9g5z-upTFMNPIfnyLAqKTxGMCjAPqBr0GmWHX8,7360 +transformers/kernels/deta/cuda/ms_deform_attn_cuda.cuh,sha256=hygB20Vh3RttOSdCuTFz8V0d3CXNp-Q89x22rYmD258,61433 +transformers/kernels/deta/cuda/ms_deform_attn_cuda.h,sha256=rPWOOMo3QyFdB5kMiexpApLFZ4dnRtx4CluEAGwsfO8,1139 +transformers/kernels/deta/cuda/ms_deform_im2col_cuda.cuh,sha256=BRN8-yfSHY8ChLij8jFl2_z2LL0LEFKuVF6Byi-YLAY,54695 +transformers/kernels/deta/ms_deform_attn.h,sha256=H2bBXGyl0R-v2DqGVz11asoRvxbjZ9iWB9djomZTpgY,1837 +transformers/kernels/deta/vision.cpp,sha256=8RvZy7P_MMx5QEszo_MwNODddJLQ8mKcmmMfgLYC_HA,798 +transformers/kernels/falcon_mamba/__init__.py,sha256=bt0j851F1uuH7flSsTvIqdh9zdKVTOVKWt3datb15SI,721 +transformers/kernels/falcon_mamba/__pycache__/__init__.cpython-310.pyc,, +transformers/kernels/falcon_mamba/__pycache__/selective_scan_with_ln_interface.cpython-310.pyc,, +transformers/kernels/falcon_mamba/selective_scan_with_ln_interface.py,sha256=649oJD0sox1I-TCkZuRMjYm3tWQkQ3VoPXLNeOcN_ss,19731 +transformers/kernels/mra/cuda_kernel.cu,sha256=LxxRYTymSoBEQpWXHA0PMzwZwpolcwX7mFAjwU8-ZMc,11678 +transformers/kernels/mra/cuda_kernel.h,sha256=UJvYq_MDzhcp07bZpYcOBn8ZGFcf_Ax1dynuiVTBvmA,1682 +transformers/kernels/mra/cuda_launch.cu,sha256=Ox5MTACriC30CGyn-g1Kb5EgQSMAZSaN6fpit3xLFWc,4072 +transformers/kernels/mra/cuda_launch.h,sha256=RVCkN_euasvgPK0zADNRvRYGWd4ah5l9X-7UG_AcdH8,707 +transformers/kernels/mra/torch_extension.cpp,sha256=N0YdBLVX0lZabckJzV_RYTHS2atCNvn13E4Ivobt25g,1405 +transformers/kernels/rwkv/wkv_cuda.cu,sha256=EvaUrEnw_qr2EjMKP-Pq7VPzFfGlMJnFhdHNLtn1fPU,6219 +transformers/kernels/rwkv/wkv_cuda_bf16.cu,sha256=DG9hTtOAlrnpDFahjt-MmnOxjMuhGU55GPsmV21HtrQ,6633 +transformers/kernels/rwkv/wkv_op.cpp,sha256=qSExhKdT6p3hyaTv5SypCnH_c7EmaX6HbhTcCntvZWg,4022 +transformers/kernels/yoso/common.h,sha256=Tq2rOUtE8Y4DRAUrRISvwIwVI3u8JBf21WgWSAYiDlQ,273 +transformers/kernels/yoso/common_cuda.h,sha256=Sji70AuVcuZSotLF7Gotmun9MJuOHo8wEkxizKXLRtc,258 +transformers/kernels/yoso/common_cuda_device.h,sha256=y6WUgAiapnMKqthRMS5s-DMSWNVkar_i8g4KPFvqiuk,2063 +transformers/kernels/yoso/fast_lsh_cumulation.cu,sha256=LA4LGNgyXT3osIyQtFBcRanSyNQWm8yqmpz7AeLP7cw,19061 +transformers/kernels/yoso/fast_lsh_cumulation.h,sha256=1cTWZjOm751HGiEB5P-UPJ8SE1VO7XRyXmBgyxYDyjI,1575 +transformers/kernels/yoso/fast_lsh_cumulation_cuda.cu,sha256=ryU4sksYZhucllzxUT_gBYlNcKbMr00QggD4S4-LmLY,32875 +transformers/kernels/yoso/fast_lsh_cumulation_cuda.h,sha256=_KGI8HQbVFtCN5KAcSGpyiJ2foGi26RKen138CUc2fY,5490 +transformers/kernels/yoso/fast_lsh_cumulation_torch.cpp,sha256=-Rh7o39Z3rtOPwNnEM-c51TCqywpVdK0WVaA7VRrXbQ,3154 +transformers/loss/__init__.py,sha256=qETsqCwayu6Ymj_J4_A_eiwiaMRHQ0noWKM35naanzc,606 +transformers/loss/__pycache__/__init__.cpython-310.pyc,, +transformers/loss/__pycache__/loss_d_fine.cpython-310.pyc,, +transformers/loss/__pycache__/loss_deformable_detr.cpython-310.pyc,, +transformers/loss/__pycache__/loss_for_object_detection.cpython-310.pyc,, +transformers/loss/__pycache__/loss_grounding_dino.cpython-310.pyc,, +transformers/loss/__pycache__/loss_rt_detr.cpython-310.pyc,, +transformers/loss/__pycache__/loss_utils.cpython-310.pyc,, +transformers/loss/loss_d_fine.py,sha256=pyVihlU1CQraOzUjFLrPXIsVSHxHhCun2SIzvOZFEDs,15881 +transformers/loss/loss_deformable_detr.py,sha256=pUwwrAVxEwa2qamyoTIqlxpll_rBTXCOn67bW73ZKuc,7321 +transformers/loss/loss_for_object_detection.py,sha256=fZuLWKzaCtGvCmlpevpHnIGp4BFIPJIIU4GcFqDO7r0,24581 +transformers/loss/loss_grounding_dino.py,sha256=Efh5GmRzZHjK3ZoNCNCRhU1GV9pcBtHDKxFbrJwr3K0,11190 +transformers/loss/loss_rt_detr.py,sha256=rGk8fFh1qoPgsRL0-vHw3FrjL3wRNV81-XQTFrElTeM,22130 +transformers/loss/loss_utils.py,sha256=-mXxizFn9FmJ16i6hkMqQdMiM4-XicyJsI1dfyDxELc,7046 +transformers/masking_utils.py,sha256=epY_7tgXO4JlKY3SQ1DBZiIs5rRxlEL85Iq0FNBHimo,60515 +transformers/model_debugging_utils.py,sha256=KTIsIVjUcBl1U_VfwLSXUvWEwX1HAJtERjdO93hEfoQ,17090 +transformers/modelcard.py,sha256=CExU8KMQ06EWzVz5APvfYo2WZcvkQXsh5KD53gRTf-o,35828 +transformers/modeling_attn_mask_utils.py,sha256=oIEM72sNYJO_2qNJs63eLmM_06a-UHPYC14IsvEsNUs,21517 +transformers/modeling_flash_attention_utils.py,sha256=KT_oHGvTiqyKO8auCG_yG5aVs0npfJZQsf5h5Co21xA,30112 +transformers/modeling_flax_outputs.py,sha256=1RQh6VTIIVgh2OME-EkUdJc2NdBi5TEXBHCFCupFASs,42188 +transformers/modeling_flax_pytorch_utils.py,sha256=DF0Bi7EoOoH_XTypcePLg8MqLGCvqBgAwtzy_d-Xl_U,21555 +transformers/modeling_flax_utils.py,sha256=TbaDBlsD6A4nh9xkeBW1H7bxYcxsQXA4ZesXY2ReJSc,61240 +transformers/modeling_gguf_pytorch_utils.py,sha256=WFBWZtKwM5G1XD97hsUJX_SX0NGeDAIk8vj-6tW8j4g,22318 +transformers/modeling_layers.py,sha256=vSYvNkrya5k4HbI1g8puGpdB2MOJS8OqCPIE_mp_aO4,11566 +transformers/modeling_outputs.py,sha256=Ltzkmwp_n61TtSOVvs5fsg49D4PDBfOGY1TRnXkKXRQ,109647 +transformers/modeling_rope_utils.py,sha256=VcwMjLdvWSqxeLRmKty99K1QErsLQknAqWYDFB8Y6aw,43192 +transformers/modeling_tf_outputs.py,sha256=6THINWzeA-DZyxAdvE3lu3p3h4ZpeBl8sjrOhj9wb9Y,56248 +transformers/modeling_tf_pytorch_utils.py,sha256=Q7-5aDeI2ec3-NYgH6Fp9OpAMmymqyp1mDZGWYve_Io,27982 +transformers/modeling_tf_utils.py,sha256=Rqc7BVljDxocTRTXu2IuiUtpMAFijjtxXx46dZIDsbE,166141 +transformers/modeling_utils.py,sha256=vxxrKkPPfDb7efN8mBQk3Wrnjrhj_KpdKjfnbJgoYR0,308964 +transformers/models/__init__.py,sha256=0qgVdBF2S0qHhJQDVKZDcTHVh09JH8Zb3G2vZXxV_GI,11385 +transformers/models/__pycache__/__init__.cpython-310.pyc,, +transformers/models/aimv2/__init__.py,sha256=cDli19QT_YABtn4DPLYfoWHtkmOQYGipAgPKGuRje4c,991 +transformers/models/aimv2/__pycache__/__init__.cpython-310.pyc,, +transformers/models/aimv2/__pycache__/configuration_aimv2.cpython-310.pyc,, +transformers/models/aimv2/__pycache__/modeling_aimv2.cpython-310.pyc,, +transformers/models/aimv2/__pycache__/modular_aimv2.cpython-310.pyc,, +transformers/models/aimv2/configuration_aimv2.py,sha256=K0yaVDpIlBtlYi8xDfhpU7ndTASqTu8nV_rCoWAAAyM,13740 +transformers/models/aimv2/modeling_aimv2.py,sha256=uuhyjxaxsGH7H8bS8Zas5o6SLPB5tA723CZGxDQ4Oyk,29017 +transformers/models/aimv2/modular_aimv2.py,sha256=fRGrWR58k611s1Uo7kbp6SsOpbKLIgaRNoUmAeAVsC8,28190 +transformers/models/albert/__init__.py,sha256=WjQ4NtNxKNj7Hvk9lA2OXmdgD_SNFp1wLS2eeL3-WoE,1154 +transformers/models/albert/__pycache__/__init__.cpython-310.pyc,, +transformers/models/albert/__pycache__/configuration_albert.cpython-310.pyc,, +transformers/models/albert/__pycache__/modeling_albert.cpython-310.pyc,, +transformers/models/albert/__pycache__/modeling_flax_albert.cpython-310.pyc,, +transformers/models/albert/__pycache__/modeling_tf_albert.cpython-310.pyc,, +transformers/models/albert/__pycache__/tokenization_albert.cpython-310.pyc,, +transformers/models/albert/__pycache__/tokenization_albert_fast.cpython-310.pyc,, +transformers/models/albert/configuration_albert.py,sha256=1jz6sQm_Ki_o_EHJj7mzULanRt3xFoPv3tt_rQg6Ct4,8162 +transformers/models/albert/modeling_albert.py,sha256=WfQVwAz1_INOKBMAnjE5K0qIA__DUV6PHpkki2J7E-8,57681 +transformers/models/albert/modeling_flax_albert.py,sha256=-QrqU89tM44jANMS-haQlSARp2uxVuUXCpUnlE8lT58,41035 +transformers/models/albert/modeling_tf_albert.py,sha256=nfIkDUf5d0ORzk1vG-3F-PWTyLSt-7uIUsBpdR9r_wg,68993 +transformers/models/albert/tokenization_albert.py,sha256=kV5S_i-EPu2mZ8f1tr7T-IRsd_W_eshGVGO_veSgQi8,13391 +transformers/models/albert/tokenization_albert_fast.py,sha256=m4Xl3Pb038gBQzlGPAvWFf2G3LrEDdPWhASLBrLucz8,7609 +transformers/models/align/__init__.py,sha256=QqTKk-Z4BylY6EkBSlYvKXVhT2te-m2Al626OUAz-r4,1027 +transformers/models/align/__pycache__/__init__.cpython-310.pyc,, +transformers/models/align/__pycache__/configuration_align.cpython-310.pyc,, +transformers/models/align/__pycache__/modeling_align.cpython-310.pyc,, +transformers/models/align/__pycache__/processing_align.cpython-310.pyc,, +transformers/models/align/configuration_align.py,sha256=T3yiaW_5C9VNHouwd-FGLgwFJd8M8h-a9gBIod0Ys2c,15999 +transformers/models/align/modeling_align.py,sha256=9jX2CuQVURXOkZk0c61kO4CP2Umw437JFFbbpKQwXvE,50953 +transformers/models/align/processing_align.py,sha256=oKA2Nsn_NM1Lp5VNuvQNYWQU0Yfzw0KrO2QewAz8cmQ,2526 +transformers/models/altclip/__init__.py,sha256=405IijUCYr1EGvOqg1xzds_GHOlxCl0HCsf1rI0wtPY,1033 +transformers/models/altclip/__pycache__/__init__.cpython-310.pyc,, +transformers/models/altclip/__pycache__/configuration_altclip.cpython-310.pyc,, +transformers/models/altclip/__pycache__/modeling_altclip.cpython-310.pyc,, +transformers/models/altclip/__pycache__/processing_altclip.cpython-310.pyc,, +transformers/models/altclip/configuration_altclip.py,sha256=rxz2vZSDIUBaflQRk31pKKYgfx0vrNu-ZJ2KuJtkz38,18486 +transformers/models/altclip/modeling_altclip.py,sha256=420Q8nX80hx6_O1DNJF86-BGFezU76DDwmiI5FUxuz8,59827 +transformers/models/altclip/processing_altclip.py,sha256=5-gEYEM1fGpG-4bwj1NViJ2c5XNhcbXO-2pELR-7gSQ,1902 +transformers/models/apertus/__init__.py,sha256=zY0UTl5pr-BSjXXoYMrQRQm0vhGnSykqKJ2n7mxl_ig,1271 +transformers/models/apertus/__pycache__/__init__.cpython-310.pyc,, +transformers/models/apertus/__pycache__/configuration_apertus.cpython-310.pyc,, +transformers/models/apertus/__pycache__/modeling_apertus.cpython-310.pyc,, +transformers/models/apertus/__pycache__/modular_apertus.cpython-310.pyc,, +transformers/models/apertus/configuration_apertus.py,sha256=1Hcuelq3r20FYICxtEqyEBut6FlO8BMUdGa203DFfhs,11922 +transformers/models/apertus/modeling_apertus.py,sha256=3pErV25SDDlZWU86uPGrMgFiKRa-xBcY4BhKzbAMFLw,21169 +transformers/models/apertus/modular_apertus.py,sha256=PfZfJ4CY3UXq7JxxPyYYDNERoyOi_Eu1YFNZWWVTcy0,16833 +transformers/models/arcee/__init__.py,sha256=bysIumYEa1Z1bCLBaaP_SCT_6poh8zFLgxt_4Ib-Diw,1009 +transformers/models/arcee/__pycache__/__init__.cpython-310.pyc,, +transformers/models/arcee/__pycache__/configuration_arcee.cpython-310.pyc,, +transformers/models/arcee/__pycache__/modeling_arcee.cpython-310.pyc,, +transformers/models/arcee/__pycache__/modular_arcee.cpython-310.pyc,, +transformers/models/arcee/configuration_arcee.py,sha256=S4OeiCsHV_Qbow6q6X-ZPwg5UFz7jvpK6r06Gf3KCZw,10764 +transformers/models/arcee/modeling_arcee.py,sha256=eD_mj6MFABbwPxUFVI4i8ZZB0YkjUGIzy6PULji7yu0,21243 +transformers/models/arcee/modular_arcee.py,sha256=pcUF5I9TfPIPjrJpWJKf_odVorR_pLwgKhvSqLMwWpA,10133 +transformers/models/aria/__init__.py,sha256=I3vYPjV-sDl0OAILLADGZ7hUkk9ZsmyZ8CEf9tie_dY,1066 +transformers/models/aria/__pycache__/__init__.cpython-310.pyc,, +transformers/models/aria/__pycache__/configuration_aria.cpython-310.pyc,, +transformers/models/aria/__pycache__/image_processing_aria.cpython-310.pyc,, +transformers/models/aria/__pycache__/modeling_aria.cpython-310.pyc,, +transformers/models/aria/__pycache__/modular_aria.cpython-310.pyc,, +transformers/models/aria/__pycache__/processing_aria.cpython-310.pyc,, +transformers/models/aria/configuration_aria.py,sha256=OfA722tTQm4EEsYxmZM-Wm12cnoH8sQ702bHQSBSBEw,16425 +transformers/models/aria/image_processing_aria.py,sha256=Th8DM67DRmZKNRmZ-c0AeVK4Z-Zm0xkNxX1LX99Ht08,24833 +transformers/models/aria/modeling_aria.py,sha256=QPsUnmHHUavTFw4v4Fg0Wk2HYhe6JQwutRdpiP0Zx4s,52243 +transformers/models/aria/modular_aria.py,sha256=hqTwYC2YEZdDiiTr6_ghUhSmkTpHWiqz05iG4wmZr3w,70858 +transformers/models/aria/processing_aria.py,sha256=mb4Si17gdG4NyCxmfWS0WTRkvp6nDF9D3JoKvm6ky5c,9291 +transformers/models/audio_spectrogram_transformer/__init__.py,sha256=a_YVwB1p4_PPeqPFWqFsGSGSQVTaSUXY0xsOd_Gflqs,1107 +transformers/models/audio_spectrogram_transformer/__pycache__/__init__.cpython-310.pyc,, +transformers/models/audio_spectrogram_transformer/__pycache__/configuration_audio_spectrogram_transformer.cpython-310.pyc,, +transformers/models/audio_spectrogram_transformer/__pycache__/feature_extraction_audio_spectrogram_transformer.cpython-310.pyc,, +transformers/models/audio_spectrogram_transformer/__pycache__/modeling_audio_spectrogram_transformer.cpython-310.pyc,, +transformers/models/audio_spectrogram_transformer/configuration_audio_spectrogram_transformer.py,sha256=HAhLugn_E6Ajr3-3n3qohG5ifAPqNfSuucQ0B2S7tCM,5901 +transformers/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.py,sha256=vPBynKfjgNCc2c6T3kd5AKxsstjKBI5Z-oNwtRAH7VY,9929 +transformers/models/audio_spectrogram_transformer/modeling_audio_spectrogram_transformer.py,sha256=L0CB-iY2UVoVVo25wDdRQEkgyDOW85PwlO7a4TOsP34,20588 +transformers/models/auto/__init__.py,sha256=wX3m7QJXMmkNMTL6ef7HH18vXdZ0cgUIkHgpVLpGZ_4,1292 +transformers/models/auto/__pycache__/__init__.cpython-310.pyc,, +transformers/models/auto/__pycache__/auto_factory.cpython-310.pyc,, +transformers/models/auto/__pycache__/configuration_auto.cpython-310.pyc,, +transformers/models/auto/__pycache__/feature_extraction_auto.cpython-310.pyc,, +transformers/models/auto/__pycache__/image_processing_auto.cpython-310.pyc,, +transformers/models/auto/__pycache__/modeling_auto.cpython-310.pyc,, +transformers/models/auto/__pycache__/modeling_flax_auto.cpython-310.pyc,, +transformers/models/auto/__pycache__/modeling_tf_auto.cpython-310.pyc,, +transformers/models/auto/__pycache__/processing_auto.cpython-310.pyc,, +transformers/models/auto/__pycache__/tokenization_auto.cpython-310.pyc,, +transformers/models/auto/__pycache__/video_processing_auto.cpython-310.pyc,, +transformers/models/auto/auto_factory.py,sha256=BMC2EJfFM0Wez3Tui51zCr1P67v6Sp9zhB-3_0nI7uI,47212 +transformers/models/auto/configuration_auto.py,sha256=EgtizU4T3RVXYqzRTPZPyLyhegaPXdAE3f0w-8su9Ks,55606 +transformers/models/auto/feature_extraction_auto.py,sha256=P8qIocXJZJN4aTv7rwC61uKk-62EN1v1KDA5jSS_k0o,20502 +transformers/models/auto/image_processing_auto.py,sha256=NOBKovx-W6s_bpGNjhRHYK9et8nguRBkHgm77PIowns,39079 +transformers/models/auto/modeling_auto.py,sha256=bk-mfIjgKouE1G17FxnnYPGXBzt7IzvPMO61lvWl8Ho,98580 +transformers/models/auto/modeling_flax_auto.py,sha256=jljyZ4H_wWjcxuVbLUDtO0acB104wm78aXyVNeGu_Zk,15709 +transformers/models/auto/modeling_tf_auto.py,sha256=YWaGWUmrGNg5eieun1OTG_EmtzWy8CU_Ebt9gw6mxyw,30313 +transformers/models/auto/processing_auto.py,sha256=6XWA3hic1-XqM3ipbgEnmTnzBcaKAkWpFguAyxqTiWE,20853 +transformers/models/auto/tokenization_auto.py,sha256=UmXm3vWoPBs3hx-kb_KllEDvgLN3wkm8DCE1NTFX9zA,58505 +transformers/models/auto/video_processing_auto.py,sha256=6-1v3ujwY9xgp4qJPUdmS3LpBC6J5Hz4uJbu64T-7Mo,19346 +transformers/models/autoformer/__init__.py,sha256=EzGIA8hECx9XytdzTifaGyGp7hrXqlyP0slqAq8xBNY,1001 +transformers/models/autoformer/__pycache__/__init__.cpython-310.pyc,, +transformers/models/autoformer/__pycache__/configuration_autoformer.cpython-310.pyc,, +transformers/models/autoformer/__pycache__/modeling_autoformer.cpython-310.pyc,, +transformers/models/autoformer/configuration_autoformer.py,sha256=hSn6Waq6CuyDFOxAecr9IhFaq4fEAEHn0uiaC_tsa3s,12192 +transformers/models/autoformer/modeling_autoformer.py,sha256=r2w2SBBn-9-HwAfIh9_PBPCqb9tZqPGOb4zUbu5Pulc,106139 +transformers/models/aya_vision/__init__.py,sha256=-DIHmMjkXOyNGbMtZJkHtLiOzdxOYSrKq4_mmR09cfk,1042 +transformers/models/aya_vision/__pycache__/__init__.cpython-310.pyc,, +transformers/models/aya_vision/__pycache__/configuration_aya_vision.cpython-310.pyc,, +transformers/models/aya_vision/__pycache__/modeling_aya_vision.cpython-310.pyc,, +transformers/models/aya_vision/__pycache__/modular_aya_vision.cpython-310.pyc,, +transformers/models/aya_vision/__pycache__/processing_aya_vision.cpython-310.pyc,, +transformers/models/aya_vision/configuration_aya_vision.py,sha256=oW_qdNAfXS5UnxCVQRtGM8ALI5XzBGRHa3Frx-ECr9s,4790 +transformers/models/aya_vision/modeling_aya_vision.py,sha256=G4kyPNfMcGrp1kUZeVR4vrxKQs3eUBRyMaQqYX-hsjw,22640 +transformers/models/aya_vision/modular_aya_vision.py,sha256=tQd76LY9qg5w1RAqQLSBClvVowhzEqtQtQSczH6p6Vs,12865 +transformers/models/aya_vision/processing_aya_vision.py,sha256=voI-Z4FtSKIlEGyQGqkZu3L4aOh22bTX_V9OUVAucWc,11961 +transformers/models/bamba/__init__.py,sha256=gtebRUrAdiwq-rJmlM5qpbtbGEg-xxA3pjivOHJvaRs,1040 +transformers/models/bamba/__pycache__/__init__.cpython-310.pyc,, +transformers/models/bamba/__pycache__/configuration_bamba.cpython-310.pyc,, +transformers/models/bamba/__pycache__/modeling_bamba.cpython-310.pyc,, +transformers/models/bamba/__pycache__/modular_bamba.cpython-310.pyc,, +transformers/models/bamba/configuration_bamba.py,sha256=zo-wvX5wz8wWepdJLwQnm2yyZdpHx0lMsE85Quf8RYE,10134 +transformers/models/bamba/modeling_bamba.py,sha256=v_kOAgtiGNEpIplxDNd_uvTxoaV4IIMInMDFre5aNDw,69530 +transformers/models/bamba/modular_bamba.py,sha256=fOqRuWzszr3vJn0_ivWevFfreCn3ci1gM3gIY4ankMI,55398 +transformers/models/bark/__init__.py,sha256=fIlOQ6RPBARVhUKdjNx2Nvf09azEI6AiPv3lyWjk0Gc,1024 +transformers/models/bark/__pycache__/__init__.cpython-310.pyc,, +transformers/models/bark/__pycache__/configuration_bark.cpython-310.pyc,, +transformers/models/bark/__pycache__/generation_configuration_bark.cpython-310.pyc,, +transformers/models/bark/__pycache__/modeling_bark.cpython-310.pyc,, +transformers/models/bark/__pycache__/processing_bark.cpython-310.pyc,, +transformers/models/bark/configuration_bark.py,sha256=p9Upfi8NXf4bHj9d2C75qseupR7X7F3JYWFATkVFh7c,11907 +transformers/models/bark/generation_configuration_bark.py,sha256=cI5vwf3ll9YIBKiXpb7HKZwu1-wDrhnlktpYy8i9X94,14955 +transformers/models/bark/modeling_bark.py,sha256=gnaJnZP1Pg5pVCAYAy-sAsn7gIGErCf4jd5qzyM-G1o,72124 +transformers/models/bark/processing_bark.py,sha256=z9rHKILwkJtiCPWY5LTOeJv8F8Zc73T2RGsNqmzguU8,15669 +transformers/models/bart/__init__.py,sha256=1_kCOlvj4hcCbNiAsAhH0PYAK4zopuVKAYKZ_64O3_c,1142 +transformers/models/bart/__pycache__/__init__.cpython-310.pyc,, +transformers/models/bart/__pycache__/configuration_bart.cpython-310.pyc,, +transformers/models/bart/__pycache__/modeling_bart.cpython-310.pyc,, +transformers/models/bart/__pycache__/modeling_flax_bart.cpython-310.pyc,, +transformers/models/bart/__pycache__/modeling_tf_bart.cpython-310.pyc,, +transformers/models/bart/__pycache__/tokenization_bart.cpython-310.pyc,, +transformers/models/bart/__pycache__/tokenization_bart_fast.cpython-310.pyc,, +transformers/models/bart/configuration_bart.py,sha256=0BemB9DKkzjpDV-39iIC96OkQHY9sevzmYUmWdG5fHg,18871 +transformers/models/bart/modeling_bart.py,sha256=6C5SWNKoH73NG6-c5mSSw7wr0LloBramAzTIGbazaA8,89905 +transformers/models/bart/modeling_flax_bart.py,sha256=T8dSDHTYEZBOhc5MAgmtCal_ns_hFCOn98b9dPS3Tho,83070 +transformers/models/bart/modeling_tf_bart.py,sha256=Kb_NgfqI4LdvaLE4Ji6vzTqc9P7zdY7ijjr0osDd0lQ,80645 +transformers/models/bart/tokenization_bart.py,sha256=kSDfbiku7CuiLkGRu2WN4rvk4Ub-fIyM7h1tw8W4Ids,16265 +transformers/models/bart/tokenization_bart_fast.py,sha256=KT0ISbLlAUn8i77zti_Oe3yebxVSM65gXGMFS3PaeU8,11275 +transformers/models/barthez/__init__.py,sha256=21WBGVafx-0kV-K_2jBdpBg0NBWsRKJqJowo03g2S9A,1003 +transformers/models/barthez/__pycache__/__init__.cpython-310.pyc,, +transformers/models/barthez/__pycache__/tokenization_barthez.cpython-310.pyc,, +transformers/models/barthez/__pycache__/tokenization_barthez_fast.cpython-310.pyc,, +transformers/models/barthez/tokenization_barthez.py,sha256=_uwi3euB_QpCr9lakhVXRWMK0G-RYTD5WyLhbI4qF6Y,12160 +transformers/models/barthez/tokenization_barthez_fast.py,sha256=7gExI5ls2M0YNtk7Dp5AHW1PAggk5zMzz2tKtQ3x54s,7721 +transformers/models/bartpho/__init__.py,sha256=DN0zgU4dM841Kqqo6wN8FpWFeWYHCBxIq3lxrg5vUoU,958 +transformers/models/bartpho/__pycache__/__init__.cpython-310.pyc,, +transformers/models/bartpho/__pycache__/tokenization_bartpho.cpython-310.pyc,, +transformers/models/bartpho/tokenization_bartpho.py,sha256=fpW_x46y9RWaXd3i1aWRWZN-hAeXnph8DzzLwPWwf10,13619 +transformers/models/beit/__init__.py,sha256=t99cV1TicuPrQlZaHjwkrEi5d7tMQeK7TTooGJIn6-Q,1157 +transformers/models/beit/__pycache__/__init__.cpython-310.pyc,, +transformers/models/beit/__pycache__/configuration_beit.cpython-310.pyc,, +transformers/models/beit/__pycache__/feature_extraction_beit.cpython-310.pyc,, +transformers/models/beit/__pycache__/image_processing_beit.cpython-310.pyc,, +transformers/models/beit/__pycache__/image_processing_beit_fast.cpython-310.pyc,, +transformers/models/beit/__pycache__/modeling_beit.cpython-310.pyc,, +transformers/models/beit/__pycache__/modeling_flax_beit.cpython-310.pyc,, +transformers/models/beit/configuration_beit.py,sha256=zT9actpT-E-p_5LLb6aDvYM8xClvu2pddJWK6wlIfgU,11602 +transformers/models/beit/feature_extraction_beit.py,sha256=I3Hxy2MRCaAr0m4taNn5y8_9_fAXCNpcYZi6gQa5tXY,1284 +transformers/models/beit/image_processing_beit.py,sha256=UW3XGGN7f6NOzQUT2NVskNu0yUPa8b2LBOQ56wzdEAI,24129 +transformers/models/beit/image_processing_beit_fast.py,sha256=NosO8FiZzozJSESNYCfr2woT32YBMGHpOa2CN-c_PE4,8967 +transformers/models/beit/modeling_beit.py,sha256=6cSIUZbuZQlEc02WLF6DeVGa3eTvpdcK-eTcW8tOEXs,64444 +transformers/models/beit/modeling_flax_beit.py,sha256=g6QwQOBdYd5kheWIzaO7Xpok4MFPJWwtopojVj5jLfU,37136 +transformers/models/bert/__init__.py,sha256=8IqoRT5cO4DU3GmQHsJgW-n6MclOZTmho5VYkKDMbnU,1182 +transformers/models/bert/__pycache__/__init__.cpython-310.pyc,, +transformers/models/bert/__pycache__/configuration_bert.cpython-310.pyc,, +transformers/models/bert/__pycache__/modeling_bert.cpython-310.pyc,, +transformers/models/bert/__pycache__/modeling_flax_bert.cpython-310.pyc,, +transformers/models/bert/__pycache__/modeling_tf_bert.cpython-310.pyc,, +transformers/models/bert/__pycache__/tokenization_bert.cpython-310.pyc,, +transformers/models/bert/__pycache__/tokenization_bert_fast.cpython-310.pyc,, +transformers/models/bert/__pycache__/tokenization_bert_tf.cpython-310.pyc,, +transformers/models/bert/configuration_bert.py,sha256=dv6OswIVpNUrWtI7WmM3XaAA8C8ZB-S3Lzs5Jl9LkVk,7314 +transformers/models/bert/modeling_bert.py,sha256=ieXlCYuYogbIg1xsALUrQNbQeKWZTEDzAPmBc5aRN8I,78330 +transformers/models/bert/modeling_flax_bert.py,sha256=xhjDVfsHDHsdFNHwjNRwjHq9wQW5usH-iKpINjBQ7SQ,64027 +transformers/models/bert/modeling_tf_bert.py,sha256=e7HT05UokKQ8fhpOwvksEcSGY0HDsoBAc7Nzb64xOik,94415 +transformers/models/bert/tokenization_bert.py,sha256=Ffkso5F6UuKyFQ_4Ao4op0k9o1Df90qeA9IJpYj2t98,19766 +transformers/models/bert/tokenization_bert_fast.py,sha256=QE60mWbUbQf8D96L5evCqqrN0hRbKz6LKXhg2Hf8T_A,6557 +transformers/models/bert/tokenization_bert_tf.py,sha256=jmvu68QDk-uMMGM3cHF_1n4PtAMf-PLmgk3xtMBzC90,12060 +transformers/models/bert_generation/__init__.py,sha256=sLEyyFf2yI6QflP1lTI9LXUF5PvWBvu-fsaFbjund5I,1059 +transformers/models/bert_generation/__pycache__/__init__.cpython-310.pyc,, +transformers/models/bert_generation/__pycache__/configuration_bert_generation.cpython-310.pyc,, +transformers/models/bert_generation/__pycache__/modeling_bert_generation.cpython-310.pyc,, +transformers/models/bert_generation/__pycache__/tokenization_bert_generation.cpython-310.pyc,, +transformers/models/bert_generation/configuration_bert_generation.py,sha256=KHse7kMgoXgcldz0LMonkb6mmNoVRbQ2U07Q3_p6_fI,6393 +transformers/models/bert_generation/modeling_bert_generation.py,sha256=tK49HE4BS_PeHhgnA4BTj6wcET3kQV07t9-2B2pKXHE,39877 +transformers/models/bert_generation/tokenization_bert_generation.py,sha256=yu2PgCmCenfHfutzdLJioGoI2_8r8dbqBL7WmJ6JTZs,7179 +transformers/models/bert_japanese/__init__.py,sha256=94xfgVPnIQuHQxvmc55_EedJlJQTnHiL4va6Ry6x3LE,964 +transformers/models/bert_japanese/__pycache__/__init__.cpython-310.pyc,, +transformers/models/bert_japanese/__pycache__/tokenization_bert_japanese.cpython-310.pyc,, +transformers/models/bert_japanese/tokenization_bert_japanese.py,sha256=-ehwXShgMWynj6owRC5JCJJOusGVpUFCejcuvbVxPrU,37815 +transformers/models/bertweet/__init__.py,sha256=EZegs0rWTTCiOC_eY-M8eV7bCcwU60dB0HsM1S1VDzQ,959 +transformers/models/bertweet/__pycache__/__init__.cpython-310.pyc,, +transformers/models/bertweet/__pycache__/tokenization_bertweet.cpython-310.pyc,, +transformers/models/bertweet/tokenization_bertweet.py,sha256=9WQZwFonhHf2CvY-r7Xa4TG3x_eLY4BZrNHvmA1hdKg,27007 +transformers/models/big_bird/__init__.py,sha256=3rloOuQNKURURWgk5Td4OBQBAzBdTJ2_fM_CI6yPrV0,1126 +transformers/models/big_bird/__pycache__/__init__.cpython-310.pyc,, +transformers/models/big_bird/__pycache__/configuration_big_bird.cpython-310.pyc,, +transformers/models/big_bird/__pycache__/modeling_big_bird.cpython-310.pyc,, +transformers/models/big_bird/__pycache__/modeling_flax_big_bird.cpython-310.pyc,, +transformers/models/big_bird/__pycache__/tokenization_big_bird.cpython-310.pyc,, +transformers/models/big_bird/__pycache__/tokenization_big_bird_fast.cpython-310.pyc,, +transformers/models/big_bird/configuration_big_bird.py,sha256=qb_lyze6oqg-PSGaAOSUQkHyeg8ApLGP0c76lZ-aFMI,7892 +transformers/models/big_bird/modeling_big_bird.py,sha256=yCfNqleJY-N5gHA9SpO3KcyLXUNQPB6fsX_Zy51yb98,130121 +transformers/models/big_bird/modeling_flax_big_bird.py,sha256=ZNo_0dB2U0PWW2sX_sbg3PBC7DpQv5RMfdpES-ZzTUM,109894 +transformers/models/big_bird/tokenization_big_bird.py,sha256=h0RLGmqUBycIt1lo1gMDd3DNVP4dEz__sF5E4XY23yw,13249 +transformers/models/big_bird/tokenization_big_bird_fast.py,sha256=EmJBuqogH76ZeE9ZjX3DIAloL-MyT-Bl7PpmozcntfA,8946 +transformers/models/bigbird_pegasus/__init__.py,sha256=7zOl1EhO8W2S9jE0FsyEoW8kV6yn5bLA0dspGFM1mLQ,1011 +transformers/models/bigbird_pegasus/__pycache__/__init__.cpython-310.pyc,, +transformers/models/bigbird_pegasus/__pycache__/configuration_bigbird_pegasus.cpython-310.pyc,, +transformers/models/bigbird_pegasus/__pycache__/modeling_bigbird_pegasus.cpython-310.pyc,, +transformers/models/bigbird_pegasus/configuration_bigbird_pegasus.py,sha256=KCIddfmLPMNb3LIrJY9xSCMasUjRHP6WB-jnedBOeNI,19323 +transformers/models/bigbird_pegasus/modeling_bigbird_pegasus.py,sha256=TZrKUlEZPJ3qMfu9JbHiyFGAOliSFiOu1UZcb5yRcLw,142103 +transformers/models/biogpt/__init__.py,sha256=pZxVjmVzt7FXlkMO_5fMg01eyPvvHYXmDA33MKhp6Yk,1032 +transformers/models/biogpt/__pycache__/__init__.cpython-310.pyc,, +transformers/models/biogpt/__pycache__/configuration_biogpt.cpython-310.pyc,, +transformers/models/biogpt/__pycache__/modeling_biogpt.cpython-310.pyc,, +transformers/models/biogpt/__pycache__/modular_biogpt.cpython-310.pyc,, +transformers/models/biogpt/__pycache__/tokenization_biogpt.cpython-310.pyc,, +transformers/models/biogpt/configuration_biogpt.py,sha256=t544SePN3AO-BjY3nzMW4CH-lMAdxs1TombK682z4fI,6215 +transformers/models/biogpt/modeling_biogpt.py,sha256=6xfgWMFljwl7KoaseFyrVGTXkUZEqsJnIFuA4Gq5KUs,42387 +transformers/models/biogpt/modular_biogpt.py,sha256=M2u1Ela5E761p1QfsSK4b3vz0tHwG25fKu71idZyWs4,33693 +transformers/models/biogpt/tokenization_biogpt.py,sha256=8Lh_IRa00R-tyz6kAF4zTr48Yl6AcCfvG54ysueGsVU,12157 +transformers/models/bit/__init__.py,sha256=I9z2RYsPRokD1ycMBRLaesbyMKK4MwLPM5oTles2KmQ,1072 +transformers/models/bit/__pycache__/__init__.cpython-310.pyc,, +transformers/models/bit/__pycache__/configuration_bit.cpython-310.pyc,, +transformers/models/bit/__pycache__/image_processing_bit.cpython-310.pyc,, +transformers/models/bit/__pycache__/image_processing_bit_fast.cpython-310.pyc,, +transformers/models/bit/__pycache__/modeling_bit.cpython-310.pyc,, +transformers/models/bit/configuration_bit.py,sha256=wZFP76CJYV7Hn-M4aSRmXn-SxXAsmUUHOLNHP6By6lI,6295 +transformers/models/bit/image_processing_bit.py,sha256=Q3X6zFqJse0xqu_HQYH1FqB9nNKS58fiZ5j_F-coqW0,15932 +transformers/models/bit/image_processing_bit_fast.py,sha256=JY4UL4OH2nQ8S66PyIYQaLFFjfhc7rIPaA-hCgmAo6Y,1327 +transformers/models/bit/modeling_bit.py,sha256=j9KE1ZGt5_ZHxt901CuIbzmqJxCv8NVQ--oM3yPGg_E,28529 +transformers/models/bitnet/__init__.py,sha256=0u3B40Xd6dJ7J7TBxJzSQWcyUe2ZWJTbT6iaWVod_-A,1018 +transformers/models/bitnet/__pycache__/__init__.cpython-310.pyc,, +transformers/models/bitnet/__pycache__/configuration_bitnet.cpython-310.pyc,, +transformers/models/bitnet/__pycache__/modeling_bitnet.cpython-310.pyc,, +transformers/models/bitnet/__pycache__/modular_bitnet.cpython-310.pyc,, +transformers/models/bitnet/configuration_bitnet.py,sha256=H5hN7Qc_TWBcMr3xmF04oRrg36gd_IIs_X-wUMTs47k,6652 +transformers/models/bitnet/modeling_bitnet.py,sha256=TGL5PMhvHp1di-ujQ-pNmkeRYhghfXuMjxwL1i30-V4,21443 +transformers/models/bitnet/modular_bitnet.py,sha256=5VncHTdQ1vaLC6KxEjUPT0q9eZhc5IFomIzzMaF0gLg,5857 +transformers/models/blenderbot/__init__.py,sha256=kdNRND4x54J18VhDVLH6usun5IblSN_9NYaLZfvaysc,1178 +transformers/models/blenderbot/__pycache__/__init__.cpython-310.pyc,, +transformers/models/blenderbot/__pycache__/configuration_blenderbot.cpython-310.pyc,, +transformers/models/blenderbot/__pycache__/modeling_blenderbot.cpython-310.pyc,, +transformers/models/blenderbot/__pycache__/modeling_flax_blenderbot.cpython-310.pyc,, +transformers/models/blenderbot/__pycache__/modeling_tf_blenderbot.cpython-310.pyc,, +transformers/models/blenderbot/__pycache__/tokenization_blenderbot.cpython-310.pyc,, +transformers/models/blenderbot/__pycache__/tokenization_blenderbot_fast.cpython-310.pyc,, +transformers/models/blenderbot/configuration_blenderbot.py,sha256=NRqxofcj8VdtIozBg7xniPOiyFy1fb3MX4STphPVB8A,18881 +transformers/models/blenderbot/modeling_blenderbot.py,sha256=rR3lMa9PPPfVYp4iD0i96yfDNs6XFHLXRdZhBHz2iY8,73596 +transformers/models/blenderbot/modeling_flax_blenderbot.py,sha256=ETs29jtKfDjSBL-y7VJcdnHPHu_OGsvr4U5vmeVtRo8,65181 +transformers/models/blenderbot/modeling_tf_blenderbot.py,sha256=zzZt4rlKifDEhE7H-EsSDbavzBRCZl2XJE6mQgOe7-4,72662 +transformers/models/blenderbot/tokenization_blenderbot.py,sha256=sfqSGJEl-owb9-MHxG97G4BQdB6rSv9d17y7xlbLJCw,18223 +transformers/models/blenderbot/tokenization_blenderbot_fast.py,sha256=Bn6KZaUr2-LwmvHQmOMo6TfqwLxbm_-AXarQw4iP9bQ,12448 +transformers/models/blenderbot_small/__init__.py,sha256=QsmmBSPdTC43EIyYBwo-xTyJjLLVqm4Cx-KFJ9O2mfE,1214 +transformers/models/blenderbot_small/__pycache__/__init__.cpython-310.pyc,, +transformers/models/blenderbot_small/__pycache__/configuration_blenderbot_small.cpython-310.pyc,, +transformers/models/blenderbot_small/__pycache__/modeling_blenderbot_small.cpython-310.pyc,, +transformers/models/blenderbot_small/__pycache__/modeling_flax_blenderbot_small.cpython-310.pyc,, +transformers/models/blenderbot_small/__pycache__/modeling_tf_blenderbot_small.cpython-310.pyc,, +transformers/models/blenderbot_small/__pycache__/tokenization_blenderbot_small.cpython-310.pyc,, +transformers/models/blenderbot_small/__pycache__/tokenization_blenderbot_small_fast.cpython-310.pyc,, +transformers/models/blenderbot_small/configuration_blenderbot_small.py,sha256=mok0lacLLkSC3LlQ6C6UxDBHZRBWW1pEUGyjAbamVco,18323 +transformers/models/blenderbot_small/modeling_blenderbot_small.py,sha256=eLWgMtmCxKgg-fwRZj6p6UIG0HY3fQ271NIDRejVFL4,71842 +transformers/models/blenderbot_small/modeling_flax_blenderbot_small.py,sha256=4gn7JguFgvff3qE1Yspggo998Ai1ycs6CwJFXJv9zok,66171 +transformers/models/blenderbot_small/modeling_tf_blenderbot_small.py,sha256=9yF-h3X3_ZH-YC4R_WTi4VuQRV8vupHwP6AaNrrs3B4,71604 +transformers/models/blenderbot_small/tokenization_blenderbot_small.py,sha256=ygaUGnIJLrPKz1jOJY9tgL97t9-OUMFegcNJXm9wnRU,7945 +transformers/models/blenderbot_small/tokenization_blenderbot_small_fast.py,sha256=v28mfjk2dPGKH3YLRhol45ZsYFqXTfTCXlPtk4MK9-A,3361 +transformers/models/blip/__init__.py,sha256=aWgKd8B53KWjNBpR7xREMajO43tIo4sRcEjZUGMt8TI,1226 +transformers/models/blip/__pycache__/__init__.cpython-310.pyc,, +transformers/models/blip/__pycache__/configuration_blip.cpython-310.pyc,, +transformers/models/blip/__pycache__/image_processing_blip.cpython-310.pyc,, +transformers/models/blip/__pycache__/image_processing_blip_fast.cpython-310.pyc,, +transformers/models/blip/__pycache__/modeling_blip.cpython-310.pyc,, +transformers/models/blip/__pycache__/modeling_blip_text.cpython-310.pyc,, +transformers/models/blip/__pycache__/modeling_tf_blip.cpython-310.pyc,, +transformers/models/blip/__pycache__/modeling_tf_blip_text.cpython-310.pyc,, +transformers/models/blip/__pycache__/processing_blip.cpython-310.pyc,, +transformers/models/blip/configuration_blip.py,sha256=_i_EKea4_h_16az8_o0jL9-Os0nXbP6iNwQaqrlnz44,14430 +transformers/models/blip/image_processing_blip.py,sha256=-fUxQF6H5f7uyqG-Lfn_xmmvCYIv-RL_Ip4PXbJAqXY,15330 +transformers/models/blip/image_processing_blip_fast.py,sha256=0gEkLRg06PJYQk6gpm15N3nQsPZtstosy_kxMkY8CS8,1312 +transformers/models/blip/modeling_blip.py,sha256=zh9EUjmpmOq0tVgJJt9xCrcjunyzD_P1gYoRtT8O0uk,51405 +transformers/models/blip/modeling_blip_text.py,sha256=bxBV_kL5igbuII8wFAcA_8hob7LT32nDpZ0RcBwiEEY,45452 +transformers/models/blip/modeling_tf_blip.py,sha256=M1B1RZxL9JDZIvhM05QMI0VL6Y3tKqwZdvT9FJM58xE,71427 +transformers/models/blip/modeling_tf_blip_text.py,sha256=asEmINloo3IGhWYpwzPsj7IxjMlOlxe5cDGO3yZpHXU,49960 +transformers/models/blip/processing_blip.py,sha256=JH1-wa01uCvuRSDmCJxBvPNZclZLlPKd0vEmZicjiPc,5377 +transformers/models/blip_2/__init__.py,sha256=kj_6H0rQ7dLoQk-COIb06LlDRnbORu3GLU3m4EdMkAM,1030 +transformers/models/blip_2/__pycache__/__init__.cpython-310.pyc,, +transformers/models/blip_2/__pycache__/configuration_blip_2.cpython-310.pyc,, +transformers/models/blip_2/__pycache__/modeling_blip_2.cpython-310.pyc,, +transformers/models/blip_2/__pycache__/processing_blip_2.cpython-310.pyc,, +transformers/models/blip_2/configuration_blip_2.py,sha256=gIYt9Djj-DlOx0pGWTfQxRocguyX4xFajk_CoKNjL2E,16247 +transformers/models/blip_2/modeling_blip_2.py,sha256=-5DyTDvDg5sv4nnMnX_CGFeh5jx8dsuZKhRQuz7QIKE,94118 +transformers/models/blip_2/processing_blip_2.py,sha256=J1d2x4IDU7FwOkbAII3hKujAFBLVhR6R8kuQLh6bDY8,7097 +transformers/models/bloom/__init__.py,sha256=lcq09Py2vSezUf26aaBG4yp2DpLZ-mAPt-fybvY_C-Q,1073 +transformers/models/bloom/__pycache__/__init__.cpython-310.pyc,, +transformers/models/bloom/__pycache__/configuration_bloom.cpython-310.pyc,, +transformers/models/bloom/__pycache__/modeling_bloom.cpython-310.pyc,, +transformers/models/bloom/__pycache__/modeling_flax_bloom.cpython-310.pyc,, +transformers/models/bloom/__pycache__/tokenization_bloom_fast.cpython-310.pyc,, +transformers/models/bloom/configuration_bloom.py,sha256=O9X_juvNPqEuxlwJQN-jPJqj8d0SROTHERYlSCEf_C4,10216 +transformers/models/bloom/modeling_bloom.py,sha256=Avn4PCiY_L_XH5BMqPMFkMK5k7MiTVWCtWo-zWMv6fw,56073 +transformers/models/bloom/modeling_flax_bloom.py,sha256=JRj-42JcNa40WjWRnQ6Q-aAsZVxd1zuNN59lf1MGinM,30197 +transformers/models/bloom/tokenization_bloom_fast.py,sha256=ViQsNhssK_0gFtEHraJXLRJyHVgjAbBp0tmRbIsviVg,6277 +transformers/models/blt/__init__.py,sha256=Eg5lWtgdEQ8Yld6WH0R7-x3R6hnVQJFqUMEuAooZOyo,1023 +transformers/models/blt/__pycache__/__init__.cpython-310.pyc,, +transformers/models/blt/__pycache__/configuration_blt.cpython-310.pyc,, +transformers/models/blt/__pycache__/modeling_blt.cpython-310.pyc,, +transformers/models/blt/__pycache__/modular_blt.cpython-310.pyc,, +transformers/models/blt/configuration_blt.py,sha256=1BB49KBpUmKqOheBkZCRhKp_pxAUyTx70HRzxM9f1n4,18512 +transformers/models/blt/modeling_blt.py,sha256=rHzhmvzS2bkBMUODe3oG8jnqF57Q_tiQZAMa6GUhSPM,57666 +transformers/models/blt/modular_blt.py,sha256=D6VVi5nFhkkNAKvuKMUMRVvUqL-55D8dj_alRuUCiRQ,41124 +transformers/models/bridgetower/__init__.py,sha256=S9u22GAHi1LVcS3OYGBzfBVTjDvk_WU9JZGPTEo6zxw,1146 +transformers/models/bridgetower/__pycache__/__init__.cpython-310.pyc,, +transformers/models/bridgetower/__pycache__/configuration_bridgetower.cpython-310.pyc,, +transformers/models/bridgetower/__pycache__/image_processing_bridgetower.cpython-310.pyc,, +transformers/models/bridgetower/__pycache__/image_processing_bridgetower_fast.cpython-310.pyc,, +transformers/models/bridgetower/__pycache__/modeling_bridgetower.cpython-310.pyc,, +transformers/models/bridgetower/__pycache__/processing_bridgetower.cpython-310.pyc,, +transformers/models/bridgetower/configuration_bridgetower.py,sha256=EtrVtgjiemvmV-CjJnnl98BQGepG77YRYUrK1lMsORU,14416 +transformers/models/bridgetower/image_processing_bridgetower.py,sha256=ZnzyoXhyBxaCVHGXYhNxbjIRHNZGTcSFVjygDwTDfOM,26382 +transformers/models/bridgetower/image_processing_bridgetower_fast.py,sha256=jyj-S-apeUXEblGb4X81ukT1cp_fB4XnNFGv2_eGdG4,10243 +transformers/models/bridgetower/modeling_bridgetower.py,sha256=FY6HCoJUA-cBGZNyyDTsF5M9A8IN0lcLpp0-2O38xvE,85207 +transformers/models/bridgetower/processing_bridgetower.py,sha256=7tHuo9JYsmlcwydROiw7d2iDzPlAND4J_QRjHovc41Q,2612 +transformers/models/bros/__init__.py,sha256=wT0avJ_J50-WK6jOB-6UbgN5kjHiBwG-NNT_iefMXr8,1024 +transformers/models/bros/__pycache__/__init__.cpython-310.pyc,, +transformers/models/bros/__pycache__/configuration_bros.cpython-310.pyc,, +transformers/models/bros/__pycache__/modeling_bros.cpython-310.pyc,, +transformers/models/bros/__pycache__/processing_bros.cpython-310.pyc,, +transformers/models/bros/configuration_bros.py,sha256=9Vgmvk3hZ-VccsOGhB8OlUPjM5ojPufSIBHa2oY4I5I,6418 +transformers/models/bros/modeling_bros.py,sha256=zooxl7vaPiy4pRutRhosGdWBtJIgaxsXK39Fd6ighYI,49220 +transformers/models/bros/processing_bros.py,sha256=_ICaTNW2U3KvBf4aL-k6yspJmQ3n4Kgvxn6HK_MXcNg,1936 +transformers/models/byt5/__init__.py,sha256=O7yXvHyqMZ7stkKX67knnddmJ81pPHoKrY_7NCAauU4,955 +transformers/models/byt5/__pycache__/__init__.cpython-310.pyc,, +transformers/models/byt5/__pycache__/tokenization_byt5.cpython-310.pyc,, +transformers/models/byt5/tokenization_byt5.py,sha256=ALgzHke0kQEe_3bopDv8r2TXfkaq2tQAM61DmzmQ8MU,10046 +transformers/models/camembert/__init__.py,sha256=hfxYgJYchvXLwio03yWsATGmrU2hgKOoiw7gaNoVgj8,1129 +transformers/models/camembert/__pycache__/__init__.cpython-310.pyc,, +transformers/models/camembert/__pycache__/configuration_camembert.cpython-310.pyc,, +transformers/models/camembert/__pycache__/modeling_camembert.cpython-310.pyc,, +transformers/models/camembert/__pycache__/modeling_tf_camembert.cpython-310.pyc,, +transformers/models/camembert/__pycache__/tokenization_camembert.cpython-310.pyc,, +transformers/models/camembert/__pycache__/tokenization_camembert_fast.cpython-310.pyc,, +transformers/models/camembert/configuration_camembert.py,sha256=kf91zHJLL5_C_1OnJwPthKDj_636CNffChcfRs-epqg,7429 +transformers/models/camembert/modeling_camembert.py,sha256=1KxNKOUu94ka8r6o05rLb-lZ8h75e4dnA9jAaUdxSk4,72486 +transformers/models/camembert/modeling_tf_camembert.py,sha256=onjWfIs2bL12BpsnRUkjmBlGUCbDJ_2zsFYd89q6uEQ,81596 +transformers/models/camembert/tokenization_camembert.py,sha256=OaoBvDD4XRNLdCgRGCJCFnjznbVNt_ApfKkGj76WxHM,14075 +transformers/models/camembert/tokenization_camembert_fast.py,sha256=dDsFP_EvbYbt3kDWcj5BXEf-mbYQ-i4VNordbhOk5_E,8159 +transformers/models/canine/__init__.py,sha256=ThkEqO6wPzWCnAplx0EWCUqVaKKsNYQKXQhWfTblEBU,1032 +transformers/models/canine/__pycache__/__init__.cpython-310.pyc,, +transformers/models/canine/__pycache__/configuration_canine.cpython-310.pyc,, +transformers/models/canine/__pycache__/modeling_canine.cpython-310.pyc,, +transformers/models/canine/__pycache__/tokenization_canine.cpython-310.pyc,, +transformers/models/canine/configuration_canine.py,sha256=8Rlt-y-lkY4Jwzi4Aa7NXN4TJtDoQylbogUOjt_q9IA,6584 +transformers/models/canine/modeling_canine.py,sha256=zjvzvge-hXp5EEBU4VSZ9pxo4-pVNG4eTSxbKlXes20,68532 +transformers/models/canine/tokenization_canine.py,sha256=hgz1yAdqqYWg6LkijfpzgataobP19GiOqwcUhQJZvtI,8194 +transformers/models/chameleon/__init__.py,sha256=EJ5kOvTyCFQjjWv9h4CMGHDRjQZ3CJ6j9Ygk2bEylA0,1136 +transformers/models/chameleon/__pycache__/__init__.cpython-310.pyc,, +transformers/models/chameleon/__pycache__/configuration_chameleon.cpython-310.pyc,, +transformers/models/chameleon/__pycache__/image_processing_chameleon.cpython-310.pyc,, +transformers/models/chameleon/__pycache__/image_processing_chameleon_fast.cpython-310.pyc,, +transformers/models/chameleon/__pycache__/modeling_chameleon.cpython-310.pyc,, +transformers/models/chameleon/__pycache__/processing_chameleon.cpython-310.pyc,, +transformers/models/chameleon/configuration_chameleon.py,sha256=hZwZ8pOjKFZa-urI7HFe-Nsk_4rWDKCDxDP-o3NjzvE,13413 +transformers/models/chameleon/image_processing_chameleon.py,sha256=4OTeuwTs678xCTSGsvI72ul7e1jGcUgHdDaAURJKnoU,16937 +transformers/models/chameleon/image_processing_chameleon_fast.py,sha256=4AHafFApd7TobFhfi1mk6xZv8sQD-HTxaxRA6mMzJhM,4042 +transformers/models/chameleon/modeling_chameleon.py,sha256=J9_qPn8mYJYdcGs9Zh2BSJX4eTImaqkZ_u7iOJTxTcM,51113 +transformers/models/chameleon/processing_chameleon.py,sha256=vkwvAURVFBK3if6FCEC5Bx7i9rdF4A_hvQDXJ-djIJw,9170 +transformers/models/chinese_clip/__init__.py,sha256=-koN80ZGdGEDnTkLDGSDlzQ3fZcahTtaOgjtl3sddSE,1202 +transformers/models/chinese_clip/__pycache__/__init__.cpython-310.pyc,, +transformers/models/chinese_clip/__pycache__/configuration_chinese_clip.cpython-310.pyc,, +transformers/models/chinese_clip/__pycache__/feature_extraction_chinese_clip.cpython-310.pyc,, +transformers/models/chinese_clip/__pycache__/image_processing_chinese_clip.cpython-310.pyc,, +transformers/models/chinese_clip/__pycache__/image_processing_chinese_clip_fast.cpython-310.pyc,, +transformers/models/chinese_clip/__pycache__/modeling_chinese_clip.cpython-310.pyc,, +transformers/models/chinese_clip/__pycache__/processing_chinese_clip.cpython-310.pyc,, +transformers/models/chinese_clip/configuration_chinese_clip.py,sha256=4VEBKh2M7m9X6htGKwwiord7klW7QLjR8FS3GoVvfDw,20298 +transformers/models/chinese_clip/feature_extraction_chinese_clip.py,sha256=hZDBWu4SqNaqbxgA6EE-WZd4Qs8tmqPgXQjveRB5bnU,1366 +transformers/models/chinese_clip/image_processing_chinese_clip.py,sha256=CCcoYIcookC5PoPjlUN5kyNl09GSJt6im6yh8g_V7js,15568 +transformers/models/chinese_clip/image_processing_chinese_clip_fast.py,sha256=XkNJybi8fcwuB7_uN33KN61wDRJcNvXSuY7yUKKSr2k,1347 +transformers/models/chinese_clip/modeling_chinese_clip.py,sha256=bc0e6Ncfvkhcymyg0Ny-Pj5Hq4B7b_myREyZO67J_Fg,52243 +transformers/models/chinese_clip/processing_chinese_clip.py,sha256=CgmF_XZu29YZJcYPMoTjsYBFtVzui424BEJ4seTTFV8,2580 +transformers/models/clap/__init__.py,sha256=751udHbsD7FBLGAByjx_8Z4XPLly1MaQQ4wKN_9vbOY,1067 +transformers/models/clap/__pycache__/__init__.cpython-310.pyc,, +transformers/models/clap/__pycache__/configuration_clap.cpython-310.pyc,, +transformers/models/clap/__pycache__/feature_extraction_clap.cpython-310.pyc,, +transformers/models/clap/__pycache__/modeling_clap.cpython-310.pyc,, +transformers/models/clap/__pycache__/processing_clap.cpython-310.pyc,, +transformers/models/clap/configuration_clap.py,sha256=jTnfuJQv3FHs0rP7nfJPMRk4bz6MtsjHXdS1ZL_um-I,18343 +transformers/models/clap/feature_extraction_clap.py,sha256=yQu0PMzMMCfIaP5ZOP3VoNGCHY7auqbZLOLnZ1kW1D8,18836 +transformers/models/clap/modeling_clap.py,sha256=ZpcPwAUCd-hIwAv7YlCfrrZkBFmfxSyhzJv5DvIul1U,82585 +transformers/models/clap/processing_clap.py,sha256=kFR0NoO-uyn6Fy1frJHr6WzQWpcOKr7IXA4rpVKPGh8,2904 +transformers/models/clip/__init__.py,sha256=bkfM4LH7u_ab8C6cctpvdgySHyQmUaSlWphG4CkcQtg,1307 +transformers/models/clip/__pycache__/__init__.cpython-310.pyc,, +transformers/models/clip/__pycache__/configuration_clip.cpython-310.pyc,, +transformers/models/clip/__pycache__/feature_extraction_clip.cpython-310.pyc,, +transformers/models/clip/__pycache__/image_processing_clip.cpython-310.pyc,, +transformers/models/clip/__pycache__/image_processing_clip_fast.cpython-310.pyc,, +transformers/models/clip/__pycache__/modeling_clip.cpython-310.pyc,, +transformers/models/clip/__pycache__/modeling_flax_clip.cpython-310.pyc,, +transformers/models/clip/__pycache__/modeling_tf_clip.cpython-310.pyc,, +transformers/models/clip/__pycache__/processing_clip.cpython-310.pyc,, +transformers/models/clip/__pycache__/tokenization_clip.cpython-310.pyc,, +transformers/models/clip/__pycache__/tokenization_clip_fast.cpython-310.pyc,, +transformers/models/clip/configuration_clip.py,sha256=HNLMByhpe6KnDBrOzMUcyFUYwKMIZXKdMVhrkVG52vs,18888 +transformers/models/clip/feature_extraction_clip.py,sha256=45gMszIrxGAwWmVEjEOF7GmpoWAkUnG9YQnb60wT_7I,1284 +transformers/models/clip/image_processing_clip.py,sha256=0sYNbCguBzHBUXHUQjZcbQbKaIXzUjx5HSk5DW80bso,17029 +transformers/models/clip/image_processing_clip_fast.py,sha256=19Xm-DXHVL7IU8xmCwJJEuiiIMDFwWw0uBQFaVAi4So,1407 +transformers/models/clip/modeling_clip.py,sha256=PneamYJ2GNbm1XWD7E9cDXZTId-lBUpP_Kala7AE1Jk,50315 +transformers/models/clip/modeling_flax_clip.py,sha256=LrZPnOAh57jEZwhEMXzX1hsPf_RliNPYtjsnMYk_TOg,50791 +transformers/models/clip/modeling_tf_clip.py,sha256=NP2F259L4n_ZQ8ZwRlhgAVVZAk3v8AhbyCuXLs2Dd8s,60318 +transformers/models/clip/processing_clip.py,sha256=IfG-k1WbxMIWeKp2ALOZalXC5GVFvv8eBgodVCrmaYM,2606 +transformers/models/clip/tokenization_clip.py,sha256=-WrPr-t8Kr-HXnL3tdXbj_FFladaDPLMNk78I7ROK5Y,20554 +transformers/models/clip/tokenization_clip_fast.py,sha256=Z9_w8hpW0NwYpF-HZPP6-gLuKwrq_rcHYcliP5EU3VM,6766 +transformers/models/clipseg/__init__.py,sha256=12Y-b3sRDKM3Hy8-6rK4GUF2a91V1S3nLUF7559AALw,1033 +transformers/models/clipseg/__pycache__/__init__.cpython-310.pyc,, +transformers/models/clipseg/__pycache__/configuration_clipseg.cpython-310.pyc,, +transformers/models/clipseg/__pycache__/modeling_clipseg.cpython-310.pyc,, +transformers/models/clipseg/__pycache__/processing_clipseg.cpython-310.pyc,, +transformers/models/clipseg/configuration_clipseg.py,sha256=QZ_ztGrVTi66G9yZNkLPlBiSzqbXgF1IBh_w-57H5Hk,18843 +transformers/models/clipseg/modeling_clipseg.py,sha256=zNnNRCWFEMSbuDlARKREFBVAI5sWizu-AMtlKvRsGm4,57753 +transformers/models/clipseg/processing_clipseg.py,sha256=D93N18jf-fY0eca3gODLMTZOWEkTpWTRYBlf2IsMPFw,7033 +transformers/models/clvp/__init__.py,sha256=RRnPofxkr_llgSxCP9tcAhu3xCR7E_m1PkrHv7KLMzo,1104 +transformers/models/clvp/__pycache__/__init__.cpython-310.pyc,, +transformers/models/clvp/__pycache__/configuration_clvp.cpython-310.pyc,, +transformers/models/clvp/__pycache__/feature_extraction_clvp.cpython-310.pyc,, +transformers/models/clvp/__pycache__/modeling_clvp.cpython-310.pyc,, +transformers/models/clvp/__pycache__/number_normalizer.cpython-310.pyc,, +transformers/models/clvp/__pycache__/processing_clvp.cpython-310.pyc,, +transformers/models/clvp/__pycache__/tokenization_clvp.cpython-310.pyc,, +transformers/models/clvp/configuration_clvp.py,sha256=-coBzCPB5o6HbwdQ-b0JWxMERxkAWPFM4mTI5fazcQs,20257 +transformers/models/clvp/feature_extraction_clvp.py,sha256=hkNsHttIXyTgcApA4nFAPMN6cVpSkRPKue1e8lDdYiA,10997 +transformers/models/clvp/modeling_clvp.py,sha256=EioYV6nROj2IpPWNopwtel_xus-u49ncztVNBaSdXxs,86704 +transformers/models/clvp/number_normalizer.py,sha256=0zNI1TWJCMJ4i9VxrirCDeX_wjEV02G0_Ig8xdmD-LY,8933 +transformers/models/clvp/processing_clvp.py,sha256=3ObNqP0yjmgXTqQLsggFloJ_LS3rxHd1mRkcbtscMxE,2310 +transformers/models/clvp/tokenization_clvp.py,sha256=G5O6ykpxfuJLaej8mgkjty3UNEnTL47e5RfvVVJ7P8Q,14808 +transformers/models/code_llama/__init__.py,sha256=aZJA9qTifG-RGtJKMzfspfxuQkaBryVva7Ah_uGNMoM,1009 +transformers/models/code_llama/__pycache__/__init__.cpython-310.pyc,, +transformers/models/code_llama/__pycache__/tokenization_code_llama.cpython-310.pyc,, +transformers/models/code_llama/__pycache__/tokenization_code_llama_fast.cpython-310.pyc,, +transformers/models/code_llama/tokenization_code_llama.py,sha256=BLEp72WT3fN8px65zzBn9bcwv30ThoDflE2267TJ8Xk,19314 +transformers/models/code_llama/tokenization_code_llama_fast.py,sha256=1ca69b8iic_Q61Fy9frmt6maw8DnQxxSBhBexILkltw,15832 +transformers/models/codegen/__init__.py,sha256=NeUIbS8szfu5R9-7CX_G6730RHOODzTfmrapJH2ApMk,1080 +transformers/models/codegen/__pycache__/__init__.cpython-310.pyc,, +transformers/models/codegen/__pycache__/configuration_codegen.cpython-310.pyc,, +transformers/models/codegen/__pycache__/modeling_codegen.cpython-310.pyc,, +transformers/models/codegen/__pycache__/tokenization_codegen.cpython-310.pyc,, +transformers/models/codegen/__pycache__/tokenization_codegen_fast.cpython-310.pyc,, +transformers/models/codegen/configuration_codegen.py,sha256=c0KsyyBNKsPFMf2TL_5lOS_DztoS-cOphRasNOI2e5I,9574 +transformers/models/codegen/modeling_codegen.py,sha256=nvJ4MbCPQYvzzpQyo7Jj8zaR85cdSjxp8PYJRvV6PuA,29290 +transformers/models/codegen/tokenization_codegen.py,sha256=ih2YU6A9RW2oPI6dyXsxx8WUHeKcibwmtyWOu3vbuHY,15365 +transformers/models/codegen/tokenization_codegen_fast.py,sha256=wiHxam7coCyQR5L1LAgcYCBgwCUUhaLZwyF2lr7WK7w,9650 +transformers/models/cohere/__init__.py,sha256=1Tg-6WGc5wgGduSR__N-jGZvPje9kNs92DW78vN0Auo,1037 +transformers/models/cohere/__pycache__/__init__.cpython-310.pyc,, +transformers/models/cohere/__pycache__/configuration_cohere.cpython-310.pyc,, +transformers/models/cohere/__pycache__/modeling_cohere.cpython-310.pyc,, +transformers/models/cohere/__pycache__/modular_cohere.cpython-310.pyc,, +transformers/models/cohere/__pycache__/tokenization_cohere_fast.cpython-310.pyc,, +transformers/models/cohere/configuration_cohere.py,sha256=cuNOpFFmlh-aqWbY7M771gr1Efo4ScohzJ7AXN1cXAs,11162 +transformers/models/cohere/modeling_cohere.py,sha256=lUYUEGJK-E-P_vu-WzdWxES1BDiNaJTv2KBoznQKG3s,24351 +transformers/models/cohere/modular_cohere.py,sha256=5tyCfCQa3dIATUA7-Vizwgqkhhp_L410b8KBZgrJt50,16189 +transformers/models/cohere/tokenization_cohere_fast.py,sha256=XJdkistG_oFiEQv-5Eyq5Sw2hiTrob-7EnCb3cwFmuU,28790 +transformers/models/cohere2/__init__.py,sha256=6Cx_c-uTSNopbO3NLWCgMmEB2-5hzkrunUWmMrb8YSU,1011 +transformers/models/cohere2/__pycache__/__init__.cpython-310.pyc,, +transformers/models/cohere2/__pycache__/configuration_cohere2.cpython-310.pyc,, +transformers/models/cohere2/__pycache__/modeling_cohere2.cpython-310.pyc,, +transformers/models/cohere2/__pycache__/modular_cohere2.cpython-310.pyc,, +transformers/models/cohere2/configuration_cohere2.py,sha256=UZRlLA6reKjnY30TWxFAdVCoS7UfHAAT2EMc5bbCsNs,12648 +transformers/models/cohere2/modeling_cohere2.py,sha256=qqehxvvZ3y1dAonhbzsR_-Lc6ApwR0BBsaJsrXGlNMw,23693 +transformers/models/cohere2/modular_cohere2.py,sha256=z6NFZWrQ4FeQNkxe0TrFjElmLrIxlIS-CzoLv1f7uW0,20589 +transformers/models/cohere2_vision/__init__.py,sha256=VZPnI0ugmeUt8tHNLXhSF1X4maFa0T4pqnm3VAPEyo0,1110 +transformers/models/cohere2_vision/__pycache__/__init__.cpython-310.pyc,, +transformers/models/cohere2_vision/__pycache__/configuration_cohere2_vision.cpython-310.pyc,, +transformers/models/cohere2_vision/__pycache__/image_processing_cohere2_vision_fast.cpython-310.pyc,, +transformers/models/cohere2_vision/__pycache__/modeling_cohere2_vision.cpython-310.pyc,, +transformers/models/cohere2_vision/__pycache__/modular_cohere2_vision.cpython-310.pyc,, +transformers/models/cohere2_vision/__pycache__/processing_cohere2_vision.cpython-310.pyc,, +transformers/models/cohere2_vision/configuration_cohere2_vision.py,sha256=-TEQe4n_754S1-kA224CiSpwDccDWeqAgBRQiN6zZZ8,3516 +transformers/models/cohere2_vision/image_processing_cohere2_vision_fast.py,sha256=4YW3e9YyVNhGeEBvZcOIxF-7bN96GDm5pXRdRwr9Ev4,13715 +transformers/models/cohere2_vision/modeling_cohere2_vision.py,sha256=dvkwvhtBscFcVFYwknt8yXoxO4J66CvKATIZh4unqbk,18295 +transformers/models/cohere2_vision/modular_cohere2_vision.py,sha256=ncqkqaj2oXCwenMl1Ez6vMXv0zGy1ZHeSYtG2qTJeok,12987 +transformers/models/cohere2_vision/processing_cohere2_vision.py,sha256=V12UAVRARxMMXrp9uQC16mkdYxGp_LanFeCoEc_Pzrw,9865 +transformers/models/colpali/__init__.py,sha256=eG-nOojo-DPkgZJACn6hbJqqfnGE97uKmLkpWVin66A,1033 +transformers/models/colpali/__pycache__/__init__.cpython-310.pyc,, +transformers/models/colpali/__pycache__/configuration_colpali.cpython-310.pyc,, +transformers/models/colpali/__pycache__/modeling_colpali.cpython-310.pyc,, +transformers/models/colpali/__pycache__/modular_colpali.cpython-310.pyc,, +transformers/models/colpali/__pycache__/processing_colpali.cpython-310.pyc,, +transformers/models/colpali/configuration_colpali.py,sha256=ejhl_-iGVK5Sk7jw2e0p_0JA7RfYUVlt63R_eOZ6LNg,4300 +transformers/models/colpali/modeling_colpali.py,sha256=7fV_cF70INbO3hlI_eCyL1Snh0vGuyuJie5VAU0O03Q,8579 +transformers/models/colpali/modular_colpali.py,sha256=3zgydZWrbU4YUxcPdlY_it1YLYGCSmk9xdgY2HdFHuk,15881 +transformers/models/colpali/processing_colpali.py,sha256=JmOoHe5JAdwXSSvV4yi6C5qCII-0getna25Orxil6Zo,19360 +transformers/models/colqwen2/__init__.py,sha256=GBrOYGkXcXTOuCd6AhVMss6TVb2igEKFcrAkgJbbg-Q,1036 +transformers/models/colqwen2/__pycache__/__init__.cpython-310.pyc,, +transformers/models/colqwen2/__pycache__/configuration_colqwen2.cpython-310.pyc,, +transformers/models/colqwen2/__pycache__/modeling_colqwen2.cpython-310.pyc,, +transformers/models/colqwen2/__pycache__/modular_colqwen2.cpython-310.pyc,, +transformers/models/colqwen2/__pycache__/processing_colqwen2.cpython-310.pyc,, +transformers/models/colqwen2/configuration_colqwen2.py,sha256=nPtBtiR57sOIGsOuzTR694zFDWU1nFWvweT_Gz68Sgg,3664 +transformers/models/colqwen2/modeling_colqwen2.py,sha256=M2mVEf9CX9T12UcpTRmpJDsp3ppgBa2diMqPgaFArA8,10925 +transformers/models/colqwen2/modular_colqwen2.py,sha256=VEoStvbsJbA2UEOcl4lqUUF7M3ZIRw4p2U9PCyA_WOs,18936 +transformers/models/colqwen2/processing_colqwen2.py,sha256=HbD73OrOfu_5D5QYHFkXgjVbIUkViYgDOAzjP1_7o6s,19753 +transformers/models/conditional_detr/__init__.py,sha256=p8luCb38qMZvKdI7GLvBTx1eiKGFMv8Obd5iKaqoVe8,1179 +transformers/models/conditional_detr/__pycache__/__init__.cpython-310.pyc,, +transformers/models/conditional_detr/__pycache__/configuration_conditional_detr.cpython-310.pyc,, +transformers/models/conditional_detr/__pycache__/feature_extraction_conditional_detr.cpython-310.pyc,, +transformers/models/conditional_detr/__pycache__/image_processing_conditional_detr.cpython-310.pyc,, +transformers/models/conditional_detr/__pycache__/image_processing_conditional_detr_fast.cpython-310.pyc,, +transformers/models/conditional_detr/__pycache__/modeling_conditional_detr.cpython-310.pyc,, +transformers/models/conditional_detr/__pycache__/modular_conditional_detr.cpython-310.pyc,, +transformers/models/conditional_detr/configuration_conditional_detr.py,sha256=J0SMZqyKvQ0Bu_og74WVqwm2MuxmYOZQFe1Iw-fVliE,13739 +transformers/models/conditional_detr/feature_extraction_conditional_detr.py,sha256=QwZ7PwpcYVGjSFPluSXbT5oTGM4UgeYSL_q-sybwHgY,1676 +transformers/models/conditional_detr/image_processing_conditional_detr.py,sha256=snpIICT7p1T0M5vQ2PgzOfwoxqAbpt5sg4yVlH8CFfg,85851 +transformers/models/conditional_detr/image_processing_conditional_detr_fast.py,sha256=EwJ6_AjJQTjIkwyaFzoTSE1a_N8G_i7X4Ex3u7J12es,47135 +transformers/models/conditional_detr/modeling_conditional_detr.py,sha256=HWEg5Get6oWAyGazkv2Kb7HKeu29G2cvCy_z2qfvfsY,93497 +transformers/models/conditional_detr/modular_conditional_detr.py,sha256=MjXfARyyPMw0WHVw0tTzI5ZibAUt3mwnn5G_ryazj2E,6040 +transformers/models/convbert/__init__.py,sha256=x1Rv5-rurTKFifp3w8N_CNcZ3sHvuFwqpw_Zn1BAenw,1124 +transformers/models/convbert/__pycache__/__init__.cpython-310.pyc,, +transformers/models/convbert/__pycache__/configuration_convbert.cpython-310.pyc,, +transformers/models/convbert/__pycache__/modeling_convbert.cpython-310.pyc,, +transformers/models/convbert/__pycache__/modeling_tf_convbert.cpython-310.pyc,, +transformers/models/convbert/__pycache__/tokenization_convbert.cpython-310.pyc,, +transformers/models/convbert/__pycache__/tokenization_convbert_fast.cpython-310.pyc,, +transformers/models/convbert/configuration_convbert.py,sha256=Ml8UytHYCv4-BAeyPTUzUY5ynnX8dIkCIGoumPTqaCc,6895 +transformers/models/convbert/modeling_convbert.py,sha256=joIep9a30otg9vaivmayReL8uZtEke5ZZF8-CZNdZrs,58353 +transformers/models/convbert/modeling_tf_convbert.py,sha256=mvR9901jo5L-GOvp6QtoY0nORRpwRURQpSxEs3T5X5c,61487 +transformers/models/convbert/tokenization_convbert.py,sha256=nt9KjwTDvJV-IGV_7PsznPWF1_uZj2aR3oL9-Ie56VM,20170 +transformers/models/convbert/tokenization_convbert_fast.py,sha256=3TKalVIkHf4iWJ5mxhbdjS7s6svBsEQUWVdhLSK07G8,6686 +transformers/models/convnext/__init__.py,sha256=QAUm2k3PH0pqhHzPXIhkEmqzMWKYCs4bo0gNVnH_bBw,1179 +transformers/models/convnext/__pycache__/__init__.cpython-310.pyc,, +transformers/models/convnext/__pycache__/configuration_convnext.cpython-310.pyc,, +transformers/models/convnext/__pycache__/feature_extraction_convnext.cpython-310.pyc,, +transformers/models/convnext/__pycache__/image_processing_convnext.cpython-310.pyc,, +transformers/models/convnext/__pycache__/image_processing_convnext_fast.cpython-310.pyc,, +transformers/models/convnext/__pycache__/modeling_convnext.cpython-310.pyc,, +transformers/models/convnext/__pycache__/modeling_tf_convnext.cpython-310.pyc,, +transformers/models/convnext/configuration_convnext.py,sha256=9m5oXY9Vx3BdADw0k7EeM4n3KrkCb3JA-WOPUlbtr74,6192 +transformers/models/convnext/feature_extraction_convnext.py,sha256=7oC8UpEVxpiIhXIC8Rc3I5YnJExAPEEezSdAUnn1hnw,1316 +transformers/models/convnext/image_processing_convnext.py,sha256=Q3BqeXX2Ykr-jCDDdyu0aGnQSMIOo8nB5s-cUrQJxmE,16035 +transformers/models/convnext/image_processing_convnext_fast.py,sha256=QLmJ_Le-RbJP8ffBoWewA9aR09mcMqUpfXOCLJH2Y90,6954 +transformers/models/convnext/modeling_convnext.py,sha256=L8Uv2r8bwyLt1PAtTIndqFKX552S4tG7roiBO160S3Q,17059 +transformers/models/convnext/modeling_tf_convnext.py,sha256=ff7TMHAtYN0Isoaivj1T34Mhzbvx_94YRFZqi8C3u5A,27197 +transformers/models/convnextv2/__init__.py,sha256=kOl9JbYIk9ioImF_hd0BS_mGDC8SG2k5LvO0-7WroRo,1043 +transformers/models/convnextv2/__pycache__/__init__.cpython-310.pyc,, +transformers/models/convnextv2/__pycache__/configuration_convnextv2.cpython-310.pyc,, +transformers/models/convnextv2/__pycache__/modeling_convnextv2.cpython-310.pyc,, +transformers/models/convnextv2/__pycache__/modeling_tf_convnextv2.cpython-310.pyc,, +transformers/models/convnextv2/configuration_convnextv2.py,sha256=bUeneirJLhh_eL1rQZ1Mk_ZSCCzJlg-CwcNNEk0fVjY,5564 +transformers/models/convnextv2/modeling_convnextv2.py,sha256=dgIhYU2Qyi5CyGslL2te76QGgVxUaPtAu1wl7XgKlFc,18548 +transformers/models/convnextv2/modeling_tf_convnextv2.py,sha256=KwiYjUc4VGEjurV9SsGN_V28RiGYPn7g7v1MgRgOQ5A,27603 +transformers/models/cpm/__init__.py,sha256=5Oz79wRruzXHciBLUAOGeo6PIH70Vs4ta8ffsMyT1Yg,995 +transformers/models/cpm/__pycache__/__init__.cpython-310.pyc,, +transformers/models/cpm/__pycache__/tokenization_cpm.cpython-310.pyc,, +transformers/models/cpm/__pycache__/tokenization_cpm_fast.cpython-310.pyc,, +transformers/models/cpm/tokenization_cpm.py,sha256=G96H4tqTADmXfKU2Qc4JEd_17nQIfNQCR20AURA1InQ,15125 +transformers/models/cpm/tokenization_cpm_fast.py,sha256=HHWhb-2cny2nXVnR3EIS4FTK8uXQI2o6c1fNzkLnAK8,10310 +transformers/models/cpmant/__init__.py,sha256=RfkbbhNqdbioJ5XVaTtxBLnZRt1GFnXugS3UFXHYV0c,1032 +transformers/models/cpmant/__pycache__/__init__.cpython-310.pyc,, +transformers/models/cpmant/__pycache__/configuration_cpmant.cpython-310.pyc,, +transformers/models/cpmant/__pycache__/modeling_cpmant.cpython-310.pyc,, +transformers/models/cpmant/__pycache__/tokenization_cpmant.cpython-310.pyc,, +transformers/models/cpmant/configuration_cpmant.py,sha256=RvgmQH8lQazRopzpfK5-Hf4eePtXXfvMJ3ar1VQC2vE,5145 +transformers/models/cpmant/modeling_cpmant.py,sha256=dEJ3bpkh4RfX8v6Erm5IjJYLv9N86P7ahaYR4AsP7as,33547 +transformers/models/cpmant/tokenization_cpmant.py,sha256=gQFg95hgeqMgArOTSG1xT-JHXxKZfF_EZRzH9f5szYI,9744 +transformers/models/csm/__init__.py,sha256=n-AQHwxZwD8imEHipiQoTDRf_OMo5zJhQ0tKKWMCPYs,1021 +transformers/models/csm/__pycache__/__init__.cpython-310.pyc,, +transformers/models/csm/__pycache__/configuration_csm.cpython-310.pyc,, +transformers/models/csm/__pycache__/generation_csm.cpython-310.pyc,, +transformers/models/csm/__pycache__/modeling_csm.cpython-310.pyc,, +transformers/models/csm/__pycache__/modular_csm.cpython-310.pyc,, +transformers/models/csm/__pycache__/processing_csm.cpython-310.pyc,, +transformers/models/csm/configuration_csm.py,sha256=xhRBdgZbc76V3OMJAcF4EL9wQEi9FVQV8g3f_ZuwxGo,23791 +transformers/models/csm/generation_csm.py,sha256=gOHz4xDLglsvYr3wm2laGk8eoLC64oTPVHUeOEOfqhc,25683 +transformers/models/csm/modeling_csm.py,sha256=M2oDzxPoPOedInY-g4AKF2_I9Luy_Y0UKBpVus3beIc,50907 +transformers/models/csm/modular_csm.py,sha256=TOq2Ybe1vy66cC4wkJn3kTx0XF4uLnSZ6NSmBZTK4dY,35452 +transformers/models/csm/processing_csm.py,sha256=yyKywlzmATo-kDMRWAIWT4WYLwO96GNs4OI-NqmlcVk,16569 +transformers/models/ctrl/__init__.py,sha256=bVtGijL4n9ewNyhcJt7lpsRhXU8yo4nY0xIlRbpismk,1062 +transformers/models/ctrl/__pycache__/__init__.cpython-310.pyc,, +transformers/models/ctrl/__pycache__/configuration_ctrl.cpython-310.pyc,, +transformers/models/ctrl/__pycache__/modeling_ctrl.cpython-310.pyc,, +transformers/models/ctrl/__pycache__/modeling_tf_ctrl.cpython-310.pyc,, +transformers/models/ctrl/__pycache__/tokenization_ctrl.cpython-310.pyc,, +transformers/models/ctrl/configuration_ctrl.py,sha256=Vg6ZFqal5MCr-t2K5pp5mtN2TJSeojgKL8IgbZkd81k,4684 +transformers/models/ctrl/modeling_ctrl.py,sha256=RiE6fmDL2LD_l5b7EAVXEOmVaTZjBl8hHkh861v9CBc,32482 +transformers/models/ctrl/modeling_tf_ctrl.py,sha256=7C954SzmkF6m4uraWukQ2Q_vhD3slx7usn9AXI26YsE,39279 +transformers/models/ctrl/tokenization_ctrl.py,sha256=N6D_85X_YHRvhltFZMVdR5M4ahJWyUvCuUvcFYOL5Lw,8080 +transformers/models/cvt/__init__.py,sha256=i1847SsjrXEIbrXsDEAiUlrtgLZRHtCSVG0rvCPXE9I,1022 +transformers/models/cvt/__pycache__/__init__.cpython-310.pyc,, +transformers/models/cvt/__pycache__/configuration_cvt.cpython-310.pyc,, +transformers/models/cvt/__pycache__/modeling_cvt.cpython-310.pyc,, +transformers/models/cvt/__pycache__/modeling_tf_cvt.cpython-310.pyc,, +transformers/models/cvt/configuration_cvt.py,sha256=zVX0Ht69OHm8ttnbAYbzxtV0kNDKV_qpbSDwToqJMKI,6684 +transformers/models/cvt/modeling_cvt.py,sha256=is4hLVrsOTLO7fEbc_EWzrBwaVzC6W8eVmK0ZoULOKc,25868 +transformers/models/cvt/modeling_tf_cvt.py,sha256=cytBTMqcUMvyCbJnEtZY3att6LkoJqDlAN-iX8ucyAQ,43455 +transformers/models/d_fine/__init__.py,sha256=1gNscomeWytwZT7K2GJBwyXxDkfVNLhRjuDwyde2A0s,995 +transformers/models/d_fine/__pycache__/__init__.cpython-310.pyc,, +transformers/models/d_fine/__pycache__/configuration_d_fine.cpython-310.pyc,, +transformers/models/d_fine/__pycache__/modeling_d_fine.cpython-310.pyc,, +transformers/models/d_fine/__pycache__/modular_d_fine.cpython-310.pyc,, +transformers/models/d_fine/configuration_d_fine.py,sha256=mFg_xcD2t7-evibX5REKeCKg3RKZIdBQsSRtGWnYN6E,22689 +transformers/models/d_fine/modeling_d_fine.py,sha256=1YobSISkhsj7hsTblLPNFk2NTh-rjHaY-FLzNlKkuE0,105555 +transformers/models/d_fine/modular_d_fine.py,sha256=EhO8F0myWi1z7gPH7J2UsoR6Wi6Ohav2KvAqZaIgsGo,57065 +transformers/models/dab_detr/__init__.py,sha256=ZvNYPQyXWplaRQIxFR8CURcsnu_HRPXrwojF5nTmGd4,998 +transformers/models/dab_detr/__pycache__/__init__.cpython-310.pyc,, +transformers/models/dab_detr/__pycache__/configuration_dab_detr.cpython-310.pyc,, +transformers/models/dab_detr/__pycache__/modeling_dab_detr.cpython-310.pyc,, +transformers/models/dab_detr/configuration_dab_detr.py,sha256=LOpJZP2nJtYS9yU2tshuqgtEWWNIojY__pl6Vuekkgg,13756 +transformers/models/dab_detr/modeling_dab_detr.py,sha256=nAuMXGiFl35XdGyyAZF0eRZwuOHGDJ8qAHkbfVPUoMM,74773 +transformers/models/dac/__init__.py,sha256=UpwXPmSOQOwvbIvklM21-y5HKY7MEIInmTt65xMX6Hw,1029 +transformers/models/dac/__pycache__/__init__.cpython-310.pyc,, +transformers/models/dac/__pycache__/configuration_dac.cpython-310.pyc,, +transformers/models/dac/__pycache__/feature_extraction_dac.cpython-310.pyc,, +transformers/models/dac/__pycache__/modeling_dac.cpython-310.pyc,, +transformers/models/dac/configuration_dac.py,sha256=Exf0bhzmsEvxLxSJTOpdjPL6Pc30SHKW1MZ23aVdt1M,4581 +transformers/models/dac/feature_extraction_dac.py,sha256=P7duIMDqPBeXD-LXJwims_O6ZBCFZaDDGTR1AIOkU_k,8059 +transformers/models/dac/modeling_dac.py,sha256=DCnmUdaDWotLu7NAkymap4ZcxM9EUE6EMC8iBD6VN2A,28784 +transformers/models/data2vec/__init__.py,sha256=-2iFF1Rb8eF9cccBNLA29zgeFV1ADYaSLoQgf6K6KB8,1238 +transformers/models/data2vec/__pycache__/__init__.cpython-310.pyc,, +transformers/models/data2vec/__pycache__/configuration_data2vec_audio.cpython-310.pyc,, +transformers/models/data2vec/__pycache__/configuration_data2vec_text.cpython-310.pyc,, +transformers/models/data2vec/__pycache__/configuration_data2vec_vision.cpython-310.pyc,, +transformers/models/data2vec/__pycache__/modeling_data2vec_audio.cpython-310.pyc,, +transformers/models/data2vec/__pycache__/modeling_data2vec_text.cpython-310.pyc,, +transformers/models/data2vec/__pycache__/modeling_data2vec_vision.cpython-310.pyc,, +transformers/models/data2vec/__pycache__/modeling_tf_data2vec_vision.cpython-310.pyc,, +transformers/models/data2vec/__pycache__/modular_data2vec_audio.cpython-310.pyc,, +transformers/models/data2vec/configuration_data2vec_audio.py,sha256=SmJMa0tBoQZudlxPe1RvpSq0YwB10GjTCify0NwL6mg,16373 +transformers/models/data2vec/configuration_data2vec_text.py,sha256=EJRVy6uJcVoDFVdMJfGaIOx_cIIW03A58N5X849i7G4,7361 +transformers/models/data2vec/configuration_data2vec_vision.py,sha256=8LsGPjPhFaBXpMF6LrtndMoXTE33pTnfZ1p9Lz06c7k,9314 +transformers/models/data2vec/modeling_data2vec_audio.py,sha256=q2RKNuqtdsxTCa3SKPoq7jG_J1ZxX0V5Aw5t8bvdvAA,59332 +transformers/models/data2vec/modeling_data2vec_text.py,sha256=lTKlMp3shNiw_oxJ0aKAflFEb5n7A3q7SyOLBICpP0c,60803 +transformers/models/data2vec/modeling_data2vec_vision.py,sha256=abpnJeWUYobkfjq_V2hd7eNHXaVviQ7Y1NnIbw8DBEQ,58534 +transformers/models/data2vec/modeling_tf_data2vec_vision.py,sha256=GO5cK8C7P1jtULl88FYw0T8Thao7E09IMx4whTzq6H0,73392 +transformers/models/data2vec/modular_data2vec_audio.py,sha256=y_ux_oMsO0Gul9oyTl_KJmGwC8nfKkNXPQE_nfviuaA,9355 +transformers/models/dbrx/__init__.py,sha256=Kzn3gm0QHW9RKEmog_IfdCGam5TXSCzkOs_WHC43sgM,989 +transformers/models/dbrx/__pycache__/__init__.cpython-310.pyc,, +transformers/models/dbrx/__pycache__/configuration_dbrx.cpython-310.pyc,, +transformers/models/dbrx/__pycache__/modeling_dbrx.cpython-310.pyc,, +transformers/models/dbrx/configuration_dbrx.py,sha256=URihH21WVlyfVL-hRw1YhQ2PtIvQXY77Ig1AiWTsT0o,9946 +transformers/models/dbrx/modeling_dbrx.py,sha256=SSD_vv3sGSOPqLACybzJCoKAoIp-5U7GVMh9TPULnPg,55353 +transformers/models/deberta/__init__.py,sha256=diL764eL8gu80XkBDQU9nI6Zy39ArO0d85MtcZ4_NPw,1119 +transformers/models/deberta/__pycache__/__init__.cpython-310.pyc,, +transformers/models/deberta/__pycache__/configuration_deberta.cpython-310.pyc,, +transformers/models/deberta/__pycache__/modeling_deberta.cpython-310.pyc,, +transformers/models/deberta/__pycache__/modeling_tf_deberta.cpython-310.pyc,, +transformers/models/deberta/__pycache__/tokenization_deberta.cpython-310.pyc,, +transformers/models/deberta/__pycache__/tokenization_deberta_fast.cpython-310.pyc,, +transformers/models/deberta/configuration_deberta.py,sha256=GFkrPn9TgA3QRrRTYsxFnQRsFRzFHPlpDJwS_HCo9Go,9024 +transformers/models/deberta/modeling_deberta.py,sha256=uNJFMuaQQlSJBw5i1qrhULMSIuN_uMZOx6eW4A9X4bs,48785 +transformers/models/deberta/modeling_tf_deberta.py,sha256=6rH8jdCWMoxKnurItq1ilWZ8KbaM-IbUGkPECrUMR9M,69231 +transformers/models/deberta/tokenization_deberta.py,sha256=sEbB4J8F0BdwyxfkOnkwPc4AWBHcwRyVE7Ql9AN8R-Q,15951 +transformers/models/deberta/tokenization_deberta_fast.py,sha256=uoJE9AssyGms5uRMxIy3awKj0W8nJ7sYFB0XiZXz47k,9121 +transformers/models/deberta_v2/__init__.py,sha256=N6wcSGakSmmHDW_QelFsn58zuDFTuvbctgkyC0OfQ5Y,1134 +transformers/models/deberta_v2/__pycache__/__init__.cpython-310.pyc,, +transformers/models/deberta_v2/__pycache__/configuration_deberta_v2.cpython-310.pyc,, +transformers/models/deberta_v2/__pycache__/modeling_deberta_v2.cpython-310.pyc,, +transformers/models/deberta_v2/__pycache__/modeling_tf_deberta_v2.cpython-310.pyc,, +transformers/models/deberta_v2/__pycache__/tokenization_deberta_v2.cpython-310.pyc,, +transformers/models/deberta_v2/__pycache__/tokenization_deberta_v2_fast.cpython-310.pyc,, +transformers/models/deberta_v2/configuration_deberta_v2.py,sha256=96TOPpbrNSW2e-Mvs2D3S-AuKyb8r_kLtStv0TRH_rY,8964 +transformers/models/deberta_v2/modeling_deberta_v2.py,sha256=8ZQ-fvLRecV7Aji0o5ClBISkkBU5_sQeM_47nOiDFlI,56711 +transformers/models/deberta_v2/modeling_tf_deberta_v2.py,sha256=3eJKDG8GQCcDXSKO8AWikBsCQuUZzOOC-tYO1j3yaL0,81610 +transformers/models/deberta_v2/tokenization_deberta_v2.py,sha256=WhRgGdG440RsyEZp6yV9IudKT0F2W8uXf2zLuTvcdY4,19731 +transformers/models/deberta_v2/tokenization_deberta_v2_fast.py,sha256=_i28i-MLIDWhqACnNKhrDcDOopjy2ulJb3R0HYqxBtc,8593 +transformers/models/decision_transformer/__init__.py,sha256=8XAHnFrFv8IFz495cQLTeaAk2G1AVRT7roauVHCGoJs,1021 +transformers/models/decision_transformer/__pycache__/__init__.cpython-310.pyc,, +transformers/models/decision_transformer/__pycache__/configuration_decision_transformer.cpython-310.pyc,, +transformers/models/decision_transformer/__pycache__/modeling_decision_transformer.cpython-310.pyc,, +transformers/models/decision_transformer/configuration_decision_transformer.py,sha256=hKOOb_TuM0XU7fDQu9sl2o6iNYYt16Dll3JUCKecFB4,7029 +transformers/models/decision_transformer/modeling_decision_transformer.py,sha256=wkFGMQqkzE70n4A_iORkOkt9sKPVXJqf0MpKvUX7eVY,42639 +transformers/models/deepseek_v2/__init__.py,sha256=cRpNT946KLnKXl4i2mGlImi9QLOe2a1ocnWNjBSbK68,1005 +transformers/models/deepseek_v2/__pycache__/__init__.cpython-310.pyc,, +transformers/models/deepseek_v2/__pycache__/configuration_deepseek_v2.cpython-310.pyc,, +transformers/models/deepseek_v2/__pycache__/modeling_deepseek_v2.cpython-310.pyc,, +transformers/models/deepseek_v2/__pycache__/modular_deepseek_v2.cpython-310.pyc,, +transformers/models/deepseek_v2/configuration_deepseek_v2.py,sha256=8snqY9qX7eRSMd28UfvOdVe8o19ABxcE21ak1WW1XCw,12231 +transformers/models/deepseek_v2/modeling_deepseek_v2.py,sha256=PhYjLjwKD9AJDdx50o6WaaoGACWKQnEpE8AI8Rkn0k0,27601 +transformers/models/deepseek_v2/modular_deepseek_v2.py,sha256=b1YihZ_fdIhnVOsp-56xwL58W4zjD3mfQPO2ZLITAFk,23569 +transformers/models/deepseek_v3/__init__.py,sha256=t-ejxAfULC_tUrUucNLt-x3hbTEIqUQp96m2DRFeaTg,1008 +transformers/models/deepseek_v3/__pycache__/__init__.cpython-310.pyc,, +transformers/models/deepseek_v3/__pycache__/configuration_deepseek_v3.cpython-310.pyc,, +transformers/models/deepseek_v3/__pycache__/modeling_deepseek_v3.cpython-310.pyc,, +transformers/models/deepseek_v3/__pycache__/modular_deepseek_v3.cpython-310.pyc,, +transformers/models/deepseek_v3/configuration_deepseek_v3.py,sha256=VEcrAJDOUBn4NmPDqAXDZ47gCRGGjZOaKsGL0qSH5xE,12703 +transformers/models/deepseek_v3/modeling_deepseek_v3.py,sha256=QM7sRHeb-zNBQ5urk2sGdkJHiQvBBXWgLO0ZF2QliyA,30489 +transformers/models/deepseek_v3/modular_deepseek_v3.py,sha256=7e7Ix8HnsXrubPR8Yr4vuKPk6fyr7nCiiRfbrEDFlLg,15832 +transformers/models/deepseek_vl/__init__.py,sha256=ZjpL2NkjCM_tsGMz_fY7bOQ2HQwimj3RL4cocjrEtHI,1162 +transformers/models/deepseek_vl/__pycache__/__init__.cpython-310.pyc,, +transformers/models/deepseek_vl/__pycache__/configuration_deepseek_vl.cpython-310.pyc,, +transformers/models/deepseek_vl/__pycache__/image_processing_deepseek_vl.cpython-310.pyc,, +transformers/models/deepseek_vl/__pycache__/image_processing_deepseek_vl_fast.cpython-310.pyc,, +transformers/models/deepseek_vl/__pycache__/modeling_deepseek_vl.cpython-310.pyc,, +transformers/models/deepseek_vl/__pycache__/modular_deepseek_vl.cpython-310.pyc,, +transformers/models/deepseek_vl/__pycache__/processing_deepseek_vl.cpython-310.pyc,, +transformers/models/deepseek_vl/configuration_deepseek_vl.py,sha256=z2lyOgCr8XztfjQoWNgco-pHZY6n6pcEH8jQiFw8L7E,4593 +transformers/models/deepseek_vl/image_processing_deepseek_vl.py,sha256=DKk5PicCpf8rvOAwL9b6o6IiA2GQmsrb3cjGQ_hmg1o,21602 +transformers/models/deepseek_vl/image_processing_deepseek_vl_fast.py,sha256=Hl_r3YqjdC-4yo5ZaeKH0YwitqFGEleVlXsQVCCh92g,8123 +transformers/models/deepseek_vl/modeling_deepseek_vl.py,sha256=gPlb_MQO_XjbCb0Fnd6NBjT3sBuS6ZevZgo_bZnsHFQ,15304 +transformers/models/deepseek_vl/modular_deepseek_vl.py,sha256=NSXCsWAom5biDuiD4D9MLsSe91Y3wVM3tb0mXAquE9g,13554 +transformers/models/deepseek_vl/processing_deepseek_vl.py,sha256=Xpk3WxJObG5j3MRJOI0qDoCiaIPw2gINw2iYgt7ztXQ,7966 +transformers/models/deepseek_vl_hybrid/__init__.py,sha256=FjSY1MYTEUP8BbAqIG2DZSAzmLh17w8aZr7pUkC_Gto,1257 +transformers/models/deepseek_vl_hybrid/__pycache__/__init__.cpython-310.pyc,, +transformers/models/deepseek_vl_hybrid/__pycache__/configuration_deepseek_vl_hybrid.cpython-310.pyc,, +transformers/models/deepseek_vl_hybrid/__pycache__/image_processing_deepseek_vl_hybrid.cpython-310.pyc,, +transformers/models/deepseek_vl_hybrid/__pycache__/image_processing_deepseek_vl_hybrid_fast.cpython-310.pyc,, +transformers/models/deepseek_vl_hybrid/__pycache__/modeling_deepseek_vl_hybrid.cpython-310.pyc,, +transformers/models/deepseek_vl_hybrid/__pycache__/modular_deepseek_vl_hybrid.cpython-310.pyc,, +transformers/models/deepseek_vl_hybrid/__pycache__/processing_deepseek_vl_hybrid.cpython-310.pyc,, +transformers/models/deepseek_vl_hybrid/configuration_deepseek_vl_hybrid.py,sha256=ETv0sLD0Ex8tVvRQxCaqJLpiS7BJ15Bl1y0w6maROiI,5507 +transformers/models/deepseek_vl_hybrid/image_processing_deepseek_vl_hybrid.py,sha256=vXtQ6OxoDfkjZVhRJDroJDxQStP9pRyxgUO02CQOO-k,26698 +transformers/models/deepseek_vl_hybrid/image_processing_deepseek_vl_hybrid_fast.py,sha256=fM_Mju8IhasrnIBlwq19Q5yOKZMrIe6BTgNVbbMnV6U,14783 +transformers/models/deepseek_vl_hybrid/modeling_deepseek_vl_hybrid.py,sha256=V6Lf7hZh89JjfIQemdD4O4hXLHIAq_GKz-eRddArGPU,22447 +transformers/models/deepseek_vl_hybrid/modular_deepseek_vl_hybrid.py,sha256=BWqPy_8BH5XmQ6sK2oUIPyAfnJiplJSKxefuKcGO5AY,48681 +transformers/models/deepseek_vl_hybrid/processing_deepseek_vl_hybrid.py,sha256=IqClaZkPl-79zpssFCYVh_Q-pIgCa2RgRsDfX1mRrJ4,8176 +transformers/models/deformable_detr/__init__.py,sha256=_ae-sABBY17hOT28SN_d0GLeRVjya0W4aqniH8u8Bcw,1176 +transformers/models/deformable_detr/__pycache__/__init__.cpython-310.pyc,, +transformers/models/deformable_detr/__pycache__/configuration_deformable_detr.cpython-310.pyc,, +transformers/models/deformable_detr/__pycache__/feature_extraction_deformable_detr.cpython-310.pyc,, +transformers/models/deformable_detr/__pycache__/image_processing_deformable_detr.cpython-310.pyc,, +transformers/models/deformable_detr/__pycache__/image_processing_deformable_detr_fast.cpython-310.pyc,, +transformers/models/deformable_detr/__pycache__/modeling_deformable_detr.cpython-310.pyc,, +transformers/models/deformable_detr/__pycache__/modular_deformable_detr.cpython-310.pyc,, +transformers/models/deformable_detr/configuration_deformable_detr.py,sha256=5CRV4cdMS_5N4NS8Qa9ymAKocEaGIegCQ0xFmwA-Ijw,14794 +transformers/models/deformable_detr/feature_extraction_deformable_detr.py,sha256=ifv-_D_b2_5GsavP72mH6etQoobhFYmf2NB4Fyl9nP0,1668 +transformers/models/deformable_detr/image_processing_deformable_detr.py,sha256=JtqFhMBmP8845nKe0qBrTARIMpAgzTeCVIJ8EDgf09Q,73307 +transformers/models/deformable_detr/image_processing_deformable_detr_fast.py,sha256=mu_jyTSy5e8QKPQ5HBWhoh_ox8e2OjGhTPWfE4ARidM,35141 +transformers/models/deformable_detr/modeling_deformable_detr.py,sha256=9bhVx_T1iKSaMJHLMkmL5PA6v9nacX12r9FXq1Qc0to,88592 +transformers/models/deformable_detr/modular_deformable_detr.py,sha256=kOtW_VmpwsmXaQMIalkg_ITMO-zm8IkceXw_9drFxFA,6543 +transformers/models/deit/__init__.py,sha256=8S1h-sIvhRy1EiQ7DKXHqqNEgR0_juhrAyQZ2AU1rVw,1155 +transformers/models/deit/__pycache__/__init__.cpython-310.pyc,, +transformers/models/deit/__pycache__/configuration_deit.cpython-310.pyc,, +transformers/models/deit/__pycache__/feature_extraction_deit.cpython-310.pyc,, +transformers/models/deit/__pycache__/image_processing_deit.cpython-310.pyc,, +transformers/models/deit/__pycache__/image_processing_deit_fast.cpython-310.pyc,, +transformers/models/deit/__pycache__/modeling_deit.cpython-310.pyc,, +transformers/models/deit/__pycache__/modeling_tf_deit.cpython-310.pyc,, +transformers/models/deit/configuration_deit.py,sha256=qd4pscfJKPWbxhmdCzj1Fdv19o8KPIuXwJpUI04Puf4,6375 +transformers/models/deit/feature_extraction_deit.py,sha256=0kfS_x_-B8O9b6ECuj3kosuPP9bwHKO_ZzjuvkBnPsc,1284 +transformers/models/deit/image_processing_deit.py,sha256=ro9TJB0U53dijS_v_Q0lMUUr_j1A3LkU4FwCYmNgeN0,15342 +transformers/models/deit/image_processing_deit_fast.py,sha256=DrJaX0I_Pu2tihvqPrsUZRdIWFTtH4BrTKT22RqVfYU,1399 +transformers/models/deit/modeling_deit.py,sha256=sUl9RJl5M1VAwdGXBkqmK9rf2xcYtejETfVAcRdMgnA,32912 +transformers/models/deit/modeling_tf_deit.py,sha256=iGVk1mPqdtOAbd6jo5j3gbueqXA30JVy7XBs2tE9kRY,51676 +transformers/models/deprecated/__init__.py,sha256=upBgfMVSzFMxNZYSd4AXNGvd0IkwHZ-ygfdf34srafo,1596 +transformers/models/deprecated/__pycache__/__init__.cpython-310.pyc,, +transformers/models/deprecated/bort/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +transformers/models/deprecated/bort/__pycache__/__init__.cpython-310.pyc,, +transformers/models/deprecated/deta/__init__.py,sha256=WNvQWU-pO4wBtGZPE5TAHF0OF1RPjEIgql1GC9wnmf8,1032 +transformers/models/deprecated/deta/__pycache__/__init__.cpython-310.pyc,, +transformers/models/deprecated/deta/__pycache__/configuration_deta.cpython-310.pyc,, +transformers/models/deprecated/deta/__pycache__/image_processing_deta.cpython-310.pyc,, +transformers/models/deprecated/deta/__pycache__/modeling_deta.cpython-310.pyc,, +transformers/models/deprecated/deta/configuration_deta.py,sha256=Hvr4QZAIruQw-s7C2JarGwAzrXzqg8FU40Co6g7Hhlc,14198 +transformers/models/deprecated/deta/image_processing_deta.py,sha256=HnnwUSDq_e5aIugcapay6VaE7qVWqQenj0W4Nk64-9M,54964 +transformers/models/deprecated/deta/modeling_deta.py,sha256=H-H8_K3t22MJjFt7Wm6ECcCZBIRHu1sEFLPmxS3HFzw,135531 +transformers/models/deprecated/efficientformer/__init__.py,sha256=RIMtCzn7AGYDfv279AZxapQ7tM7FFguknlC5CShrV3M,1112 +transformers/models/deprecated/efficientformer/__pycache__/__init__.cpython-310.pyc,, +transformers/models/deprecated/efficientformer/__pycache__/configuration_efficientformer.cpython-310.pyc,, +transformers/models/deprecated/efficientformer/__pycache__/image_processing_efficientformer.cpython-310.pyc,, +transformers/models/deprecated/efficientformer/__pycache__/modeling_efficientformer.cpython-310.pyc,, +transformers/models/deprecated/efficientformer/__pycache__/modeling_tf_efficientformer.cpython-310.pyc,, +transformers/models/deprecated/efficientformer/configuration_efficientformer.py,sha256=liR9COZM1WNt1Cp7LtY0hBm4HQxcFcTSML5Sokq8Jwc,7739 +transformers/models/deprecated/efficientformer/image_processing_efficientformer.py,sha256=hJ6jnRePCFxsVK3VQphL5M0gwJLZg9bA-eObxYE7V1Q,15782 +transformers/models/deprecated/efficientformer/modeling_efficientformer.py,sha256=ILkaYcZ-GKzxhlizv8vXxIoQQUIdZm6-NDCuHCwSV54,32648 +transformers/models/deprecated/efficientformer/modeling_tf_efficientformer.py,sha256=5vHabl_36CmhqvWXoP2Lxbno9i0MXsKErQtY43-bf-U,49406 +transformers/models/deprecated/ernie_m/__init__.py,sha256=LlPR0I3qUe-L3t0xeakW3FKohvQgcWBgRMxENjy6_Ew,1047 +transformers/models/deprecated/ernie_m/__pycache__/__init__.cpython-310.pyc,, +transformers/models/deprecated/ernie_m/__pycache__/configuration_ernie_m.cpython-310.pyc,, +transformers/models/deprecated/ernie_m/__pycache__/modeling_ernie_m.cpython-310.pyc,, +transformers/models/deprecated/ernie_m/__pycache__/tokenization_ernie_m.cpython-310.pyc,, +transformers/models/deprecated/ernie_m/configuration_ernie_m.py,sha256=jPmSWmo38ovIiyrzIcHvnj-CdbnzqkogCTcCkPPsf0o,5889 +transformers/models/deprecated/ernie_m/modeling_ernie_m.py,sha256=Je-y2aRLSGIzCxxM6UjqzVVkLT-fXD7LXDo2QnFIXwo,47347 +transformers/models/deprecated/ernie_m/tokenization_ernie_m.py,sha256=se3eYEzFrfa1Z_Xnla9l7c4WsXBeF4gePXVh0jf81K4,16250 +transformers/models/deprecated/gptsan_japanese/__init__.py,sha256=Q0KI_MuMRbQNKBzYOEsDgNZLktGUjTUWlm-1-TmdAeE,1061 +transformers/models/deprecated/gptsan_japanese/__pycache__/__init__.cpython-310.pyc,, +transformers/models/deprecated/gptsan_japanese/__pycache__/configuration_gptsan_japanese.cpython-310.pyc,, +transformers/models/deprecated/gptsan_japanese/__pycache__/modeling_gptsan_japanese.cpython-310.pyc,, +transformers/models/deprecated/gptsan_japanese/__pycache__/tokenization_gptsan_japanese.cpython-310.pyc,, +transformers/models/deprecated/gptsan_japanese/configuration_gptsan_japanese.py,sha256=UQbzr2Yr4EkjZgUE0hj8HYuelQDZZi0b7nw_vwtOvvk,7169 +transformers/models/deprecated/gptsan_japanese/modeling_gptsan_japanese.py,sha256=zniTVsH8H09BVrsg-62uUfU92d76DbudGDDH7ARNkPw,65096 +transformers/models/deprecated/gptsan_japanese/tokenization_gptsan_japanese.py,sha256=Ndjdq7_mYUxUaUajF091gKrwYTlNMGUGih9MngjtIUA,23341 +transformers/models/deprecated/graphormer/__init__.py,sha256=qvmWWqa8KkAItGYVAHgjatAQlmjcF0bovLch0U0ubc8,1003 +transformers/models/deprecated/graphormer/__pycache__/__init__.cpython-310.pyc,, +transformers/models/deprecated/graphormer/__pycache__/collating_graphormer.cpython-310.pyc,, +transformers/models/deprecated/graphormer/__pycache__/configuration_graphormer.cpython-310.pyc,, +transformers/models/deprecated/graphormer/__pycache__/modeling_graphormer.cpython-310.pyc,, +transformers/models/deprecated/graphormer/algos_graphormer.pyx,sha256=b_Qlm1hKCHnAqx6oOLGC9LkivAV0K_AZRGgXT9MmBas,3635 +transformers/models/deprecated/graphormer/collating_graphormer.py,sha256=Tsm00bqXeKDCtESNHUE4q6OotxCjW9rbjy9MKyo3rvk,6075 +transformers/models/deprecated/graphormer/configuration_graphormer.py,sha256=vg6O_wY-Xn_aTVTg5XTYqNREozAomSLCHVo_diH9Pas,10480 +transformers/models/deprecated/graphormer/modeling_graphormer.py,sha256=QbQNmiKzedpILarXhoFiZR9McA29QJ1w_eJ2DVaMdpQ,37118 +transformers/models/deprecated/jukebox/__init__.py,sha256=5boFy1Eld2ll-ZpGhar77TZp4gVN5m-Ks8QumIZeAcI,1037 +transformers/models/deprecated/jukebox/__pycache__/__init__.cpython-310.pyc,, +transformers/models/deprecated/jukebox/__pycache__/configuration_jukebox.cpython-310.pyc,, +transformers/models/deprecated/jukebox/__pycache__/modeling_jukebox.cpython-310.pyc,, +transformers/models/deprecated/jukebox/__pycache__/tokenization_jukebox.cpython-310.pyc,, +transformers/models/deprecated/jukebox/configuration_jukebox.py,sha256=etr-yMp1t851E6omXV9ZrZdruQL7NkA1lifBu9h6f6A,26837 +transformers/models/deprecated/jukebox/modeling_jukebox.py,sha256=TsKdCCiOrpbuoEc2cDZV518JyOgV7mkoFUobjcFr0VA,119621 +transformers/models/deprecated/jukebox/tokenization_jukebox.py,sha256=bwpU60IQUNrPoZ0Mg4cobVe9_04tnda-6KU0koLpAC0,17366 +transformers/models/deprecated/mctct/__init__.py,sha256=oL2eRCmC1eKqGcN2nn7WWmVh4Lyq6zvfTK8Fbcct-Cc,1073 +transformers/models/deprecated/mctct/__pycache__/__init__.cpython-310.pyc,, +transformers/models/deprecated/mctct/__pycache__/configuration_mctct.cpython-310.pyc,, +transformers/models/deprecated/mctct/__pycache__/feature_extraction_mctct.cpython-310.pyc,, +transformers/models/deprecated/mctct/__pycache__/modeling_mctct.cpython-310.pyc,, +transformers/models/deprecated/mctct/__pycache__/processing_mctct.cpython-310.pyc,, +transformers/models/deprecated/mctct/configuration_mctct.py,sha256=se5nTkdBsiWJT9eGIbsAju4olV_f-GddUDtba3HUSEk,9101 +transformers/models/deprecated/mctct/feature_extraction_mctct.py,sha256=FdZKMKkJodKfUjYXa4r12b3AkTD7qcwBDF6JCbgW-68,13494 +transformers/models/deprecated/mctct/modeling_mctct.py,sha256=0KPKMc0DVRpDeplg15-Z410B8jGHCctPebbzLoPgk3o,32526 +transformers/models/deprecated/mctct/processing_mctct.py,sha256=OcRrtpUDakmEL1HbH9atDrl9QYm4DrlR89QZoHtVwO0,5652 +transformers/models/deprecated/mega/__init__.py,sha256=MAxMoZtbT_fdVUYgMGeBlgwYRYVz07EeK5RyL2GB-ic,991 +transformers/models/deprecated/mega/__pycache__/__init__.cpython-310.pyc,, +transformers/models/deprecated/mega/__pycache__/configuration_mega.cpython-310.pyc,, +transformers/models/deprecated/mega/__pycache__/modeling_mega.cpython-310.pyc,, +transformers/models/deprecated/mega/configuration_mega.py,sha256=nWdk-zPvpSI7UmUeXnClAwk-hEXCM5f5vt4xxJyAE_E,12642 +transformers/models/deprecated/mega/modeling_mega.py,sha256=ZQePgkC55tsABy9Jzz9nAH1ilQtQCPTKK_w6S3AQHTY,109494 +transformers/models/deprecated/mmbt/__init__.py,sha256=X5f5OKVKnz-mOSV_v9IbfPsDFzOpYCf2yU4ktLWWmOA,991 +transformers/models/deprecated/mmbt/__pycache__/__init__.cpython-310.pyc,, +transformers/models/deprecated/mmbt/__pycache__/configuration_mmbt.cpython-310.pyc,, +transformers/models/deprecated/mmbt/__pycache__/modeling_mmbt.cpython-310.pyc,, +transformers/models/deprecated/mmbt/configuration_mmbt.py,sha256=UNksVsSmP6e_52vlf5pa9ETgiQw6M2pM2ocVxq52fWY,1624 +transformers/models/deprecated/mmbt/modeling_mmbt.py,sha256=xil7uW5Q1fHo-0yo4eC0K6egN-sO0LasqBxe2wp9nTE,18983 +transformers/models/deprecated/nat/__init__.py,sha256=Ggl4KcqVEX5Ub66NyyA7fyMz_oBLHOMUlqRTVrYwAYs,989 +transformers/models/deprecated/nat/__pycache__/__init__.cpython-310.pyc,, +transformers/models/deprecated/nat/__pycache__/configuration_nat.cpython-310.pyc,, +transformers/models/deprecated/nat/__pycache__/modeling_nat.cpython-310.pyc,, +transformers/models/deprecated/nat/configuration_nat.py,sha256=7ZZXfsex0BfTQ5HMdINit2aAC1j_6me30ctX4IDM35o,7001 +transformers/models/deprecated/nat/modeling_nat.py,sha256=b5awRdTSdVu223JQXBQlA5OS1F9cnbs0UBm6hKMEFTQ,38726 +transformers/models/deprecated/nezha/__init__.py,sha256=3WxwqDdNckh4KfXKV4gxIeKvkr_U1GBDA-MdEHux3JM,993 +transformers/models/deprecated/nezha/__pycache__/__init__.cpython-310.pyc,, +transformers/models/deprecated/nezha/__pycache__/configuration_nezha.cpython-310.pyc,, +transformers/models/deprecated/nezha/__pycache__/modeling_nezha.cpython-310.pyc,, +transformers/models/deprecated/nezha/configuration_nezha.py,sha256=gZvb3NVibiLmMrTrjzlKcChmBET6dOhyAQCjFFDyp0Y,4845 +transformers/models/deprecated/nezha/modeling_nezha.py,sha256=z6e2YNMpX6TVKaKGkvldDSJ9X5-uYEuunNd6ZblUaTU,73939 +transformers/models/deprecated/open_llama/__init__.py,sha256=hhWBBxouawhwSYkuWi7Co_dO86xNFofKrtxacOlcmiM,1023 +transformers/models/deprecated/open_llama/__pycache__/__init__.cpython-310.pyc,, +transformers/models/deprecated/open_llama/__pycache__/configuration_open_llama.cpython-310.pyc,, +transformers/models/deprecated/open_llama/__pycache__/modeling_open_llama.cpython-310.pyc,, +transformers/models/deprecated/open_llama/configuration_open_llama.py,sha256=Iwpxsxa85jUukrVctVnhz1zOswDR889ZYcXbW6-bxuA,7800 +transformers/models/deprecated/open_llama/modeling_open_llama.py,sha256=34hkO14GtiYHH0qdvZv-KIKmxvcMpnIyMJB0_gl4smM,42741 +transformers/models/deprecated/qdqbert/__init__.py,sha256=0sVNCbOvGXfJhrGbtQ7zV4v8rctY5pMzYKUvngVcvRg,1020 +transformers/models/deprecated/qdqbert/__pycache__/__init__.cpython-310.pyc,, +transformers/models/deprecated/qdqbert/__pycache__/configuration_qdqbert.cpython-310.pyc,, +transformers/models/deprecated/qdqbert/__pycache__/modeling_qdqbert.cpython-310.pyc,, +transformers/models/deprecated/qdqbert/configuration_qdqbert.py,sha256=HCvSo5NpospAUVinJu8NEGtDo4Oa2KHQX-_1kTkFA6g,5719 +transformers/models/deprecated/qdqbert/modeling_qdqbert.py,sha256=h5pmCB9MxX4gcXLvBln4dJuPiQOo_sisk-pThBsjKgY,76910 +transformers/models/deprecated/realm/__init__.py,sha256=Cqg86mvi125eaBzeoP10ykpvXvHD-InC6JYTDJXM3Ik,1109 +transformers/models/deprecated/realm/__pycache__/__init__.cpython-310.pyc,, +transformers/models/deprecated/realm/__pycache__/configuration_realm.cpython-310.pyc,, +transformers/models/deprecated/realm/__pycache__/modeling_realm.cpython-310.pyc,, +transformers/models/deprecated/realm/__pycache__/retrieval_realm.cpython-310.pyc,, +transformers/models/deprecated/realm/__pycache__/tokenization_realm.cpython-310.pyc,, +transformers/models/deprecated/realm/__pycache__/tokenization_realm_fast.cpython-310.pyc,, +transformers/models/deprecated/realm/configuration_realm.py,sha256=1CmnEKCJyYUmedP5pXcvLwrT2ThND3YHeuHfaEokz3M,7585 +transformers/models/deprecated/realm/modeling_realm.py,sha256=4c_tZx1f1VGR3Bmp-J-VMvP3JoIgKT6sr0aSBS9H1sA,83578 +transformers/models/deprecated/realm/retrieval_realm.py,sha256=bGzuAOl8j59toVMwzUHZbpKkNBuAeP-qo1kg8Wdh0q8,7012 +transformers/models/deprecated/realm/tokenization_realm.py,sha256=c_H4sBrcnU_bXnQZrHyPuPRvMJx_7Coc3jB0Skkyxzs,21995 +transformers/models/deprecated/realm/tokenization_realm_fast.py,sha256=vzueU81dDD3DLcdK5nhZIRJH6avUkPAB2lJ5e8F9jbA,9858 +transformers/models/deprecated/retribert/__init__.py,sha256=bitEp-fOvn6_HvMY2CUlvJCGV5-baV6Bvl7EcbBh1jM,1090 +transformers/models/deprecated/retribert/__pycache__/__init__.cpython-310.pyc,, +transformers/models/deprecated/retribert/__pycache__/configuration_retribert.cpython-310.pyc,, +transformers/models/deprecated/retribert/__pycache__/modeling_retribert.cpython-310.pyc,, +transformers/models/deprecated/retribert/__pycache__/tokenization_retribert.cpython-310.pyc,, +transformers/models/deprecated/retribert/__pycache__/tokenization_retribert_fast.cpython-310.pyc,, +transformers/models/deprecated/retribert/configuration_retribert.py,sha256=nAqsKCL46N2eJwlcyfDs2ijqCWo7SDsOInq4rOsDAhs,5232 +transformers/models/deprecated/retribert/modeling_retribert.py,sha256=PzP_j4PTRb0wLpYvS3A6D9CjRFNT-gc99MZos1LwBR8,9349 +transformers/models/deprecated/retribert/tokenization_retribert.py,sha256=Uo7UQxxwhM-SonyGQtjXvpTZK7a9FLs2UTENCOXYIfo,19536 +transformers/models/deprecated/retribert/tokenization_retribert_fast.py,sha256=EXkSqeK6zEF8yng9UPSXjrxKaTHnhyGHWqlRugUsEYQ,6730 +transformers/models/deprecated/speech_to_text_2/__init__.py,sha256=gpV3g4cmZOc1rTvOVZQN9dY1eGoXQvVnSq0LMzYYJm0,1111 +transformers/models/deprecated/speech_to_text_2/__pycache__/__init__.cpython-310.pyc,, +transformers/models/deprecated/speech_to_text_2/__pycache__/configuration_speech_to_text_2.cpython-310.pyc,, +transformers/models/deprecated/speech_to_text_2/__pycache__/modeling_speech_to_text_2.cpython-310.pyc,, +transformers/models/deprecated/speech_to_text_2/__pycache__/processing_speech_to_text_2.cpython-310.pyc,, +transformers/models/deprecated/speech_to_text_2/__pycache__/tokenization_speech_to_text_2.cpython-310.pyc,, +transformers/models/deprecated/speech_to_text_2/configuration_speech_to_text_2.py,sha256=0nf8Vrheuc_3fpZhc3fNFfd05fXLfKvCe6n9B5hAcNA,6052 +transformers/models/deprecated/speech_to_text_2/modeling_speech_to_text_2.py,sha256=zvhPGSByae0b0JkGOc32UBSePJIiyz7Ind37J_jkgaw,43395 +transformers/models/deprecated/speech_to_text_2/processing_speech_to_text_2.py,sha256=eiJ_HvJhKH4VNOkOW33rZqURdZ5ElyiaY0vg48utC4M,4212 +transformers/models/deprecated/speech_to_text_2/tokenization_speech_to_text_2.py,sha256=vTNJBHuH4CwO6SvtOgx24mWtZzjjdHpY1ee7TZw1XxQ,8424 +transformers/models/deprecated/tapex/__init__.py,sha256=YDgKE4wAmqYPQ9U94PaZXHGDiLkZQAoMt4mNiO3QrXg,958 +transformers/models/deprecated/tapex/__pycache__/__init__.cpython-310.pyc,, +transformers/models/deprecated/tapex/__pycache__/tokenization_tapex.cpython-310.pyc,, +transformers/models/deprecated/tapex/tokenization_tapex.py,sha256=mrRkwgPKHyVUpOKYSI12x9_Pgr3Yyv8uWcePFxKWuI8,64396 +transformers/models/deprecated/trajectory_transformer/__init__.py,sha256=qhJ78kxJOG5Q5d_NDrIiH5_btuaAKfluEzKD_nuESPw,1027 +transformers/models/deprecated/trajectory_transformer/__pycache__/__init__.cpython-310.pyc,, +transformers/models/deprecated/trajectory_transformer/__pycache__/configuration_trajectory_transformer.cpython-310.pyc,, +transformers/models/deprecated/trajectory_transformer/__pycache__/modeling_trajectory_transformer.cpython-310.pyc,, +transformers/models/deprecated/trajectory_transformer/configuration_trajectory_transformer.py,sha256=EEkSTX_sw2eYmNqYutj1acxjZnlM-jFldEtqycOwJko,7105 +transformers/models/deprecated/trajectory_transformer/modeling_trajectory_transformer.py,sha256=TlcEkjXlO7PMUOcFK63sFUpdA9L6mEbGbO8G2y3OfY8,25429 +transformers/models/deprecated/transfo_xl/__init__.py,sha256=_wXu1dOeNxgJemZTynDRPmYOWcMQpYwkxbHIC_070_M,1088 +transformers/models/deprecated/transfo_xl/__pycache__/__init__.cpython-310.pyc,, +transformers/models/deprecated/transfo_xl/__pycache__/configuration_transfo_xl.cpython-310.pyc,, +transformers/models/deprecated/transfo_xl/__pycache__/modeling_tf_transfo_xl.cpython-310.pyc,, +transformers/models/deprecated/transfo_xl/__pycache__/modeling_tf_transfo_xl_utilities.cpython-310.pyc,, +transformers/models/deprecated/transfo_xl/__pycache__/modeling_transfo_xl.cpython-310.pyc,, +transformers/models/deprecated/transfo_xl/__pycache__/modeling_transfo_xl_utilities.cpython-310.pyc,, +transformers/models/deprecated/transfo_xl/__pycache__/tokenization_transfo_xl.cpython-310.pyc,, +transformers/models/deprecated/transfo_xl/configuration_transfo_xl.py,sha256=5lUsNUzrmw3wWw_35s4TQgXQhf7C-QovFDkLs7R74Io,7905 +transformers/models/deprecated/transfo_xl/modeling_tf_transfo_xl.py,sha256=j4yoV9YRQ6xroWV1XXTIYH46EEKXgFA9_x8YIIGu76Q,46054 +transformers/models/deprecated/transfo_xl/modeling_tf_transfo_xl_utilities.py,sha256=Dlv3ZzRduWFBnZZHn8RegbW45XeCecuYCzzzZC3bDXs,7633 +transformers/models/deprecated/transfo_xl/modeling_transfo_xl.py,sha256=GNYB-j2j_3Q0Yg3xC-nCmzOOmQhCoPOQcrCp5IBVtnE,56120 +transformers/models/deprecated/transfo_xl/modeling_transfo_xl_utilities.py,sha256=L1l4K7sj8rwXzvhn7_-RK2UbOnYtfDUF0VdFr4L8nxA,10859 +transformers/models/deprecated/transfo_xl/tokenization_transfo_xl.py,sha256=PcUEB2E_ZkrCDiyWhxtVaHC3oa6DHEBQfja72VZ65bA,32193 +transformers/models/deprecated/tvlt/__init__.py,sha256=5kgH30TJlq9WEsRw6f5Bs7U4MxNFKzw2dvlENb-ZsPM,674 +transformers/models/deprecated/tvlt/__pycache__/__init__.cpython-310.pyc,, +transformers/models/deprecated/tvlt/__pycache__/configuration_tvlt.cpython-310.pyc,, +transformers/models/deprecated/tvlt/__pycache__/feature_extraction_tvlt.cpython-310.pyc,, +transformers/models/deprecated/tvlt/__pycache__/image_processing_tvlt.cpython-310.pyc,, +transformers/models/deprecated/tvlt/__pycache__/modeling_tvlt.cpython-310.pyc,, +transformers/models/deprecated/tvlt/__pycache__/processing_tvlt.cpython-310.pyc,, +transformers/models/deprecated/tvlt/configuration_tvlt.py,sha256=PaJXPttCw4t832Pqo1pV0MBYa9f-oDljfmc2SBMFXCI,8650 +transformers/models/deprecated/tvlt/feature_extraction_tvlt.py,sha256=8NHtBJnMjCRq1tpCaOjKlzbajU6hN2sIk2JjlvhJl6I,10591 +transformers/models/deprecated/tvlt/image_processing_tvlt.py,sha256=lruyDzTOOVfLfgK2ThGm0lkHVl13qU8u8xxBhiM7-xs,20314 +transformers/models/deprecated/tvlt/modeling_tvlt.py,sha256=PUpjdZ_0yjRy7tTnpmpkLE_dG0RvV4AnEqs2nnbaY9Y,56275 +transformers/models/deprecated/tvlt/processing_tvlt.py,sha256=nfcrdlaKcTk14Zb6DOBAWi5w7dHIgrxskF0ELbGWJxg,3235 +transformers/models/deprecated/van/__init__.py,sha256=zH2jgRuTkGqz0fzogoEi1HhRMNmg8BbWjhZ9dwVWyM0,989 +transformers/models/deprecated/van/__pycache__/__init__.cpython-310.pyc,, +transformers/models/deprecated/van/__pycache__/configuration_van.cpython-310.pyc,, +transformers/models/deprecated/van/__pycache__/modeling_van.cpython-310.pyc,, +transformers/models/deprecated/van/configuration_van.py,sha256=fTfaChmHuw2qoi_mZxIQxUH7JoVRBdkA38R_qPbrc3E,4683 +transformers/models/deprecated/van/modeling_van.py,sha256=015oRhkIzWHZTFuHcFJkFgjvPBN-8zkqLnqkV1fKAPs,20091 +transformers/models/deprecated/vit_hybrid/__init__.py,sha256=9OIBt-kLfL3VHtfpoj3rVLFzXbpwFu1F5QotHqQAUuM,1050 +transformers/models/deprecated/vit_hybrid/__pycache__/__init__.cpython-310.pyc,, +transformers/models/deprecated/vit_hybrid/__pycache__/configuration_vit_hybrid.cpython-310.pyc,, +transformers/models/deprecated/vit_hybrid/__pycache__/image_processing_vit_hybrid.cpython-310.pyc,, +transformers/models/deprecated/vit_hybrid/__pycache__/modeling_vit_hybrid.cpython-310.pyc,, +transformers/models/deprecated/vit_hybrid/configuration_vit_hybrid.py,sha256=Eof6B__quu-2A2SDw7erhD6goglbdVsgB3wqJGEp9WE,8477 +transformers/models/deprecated/vit_hybrid/image_processing_vit_hybrid.py,sha256=yBdG4xtH8UkzOwpMQvjNxoucIN1QWlZE93Bx9UnaRGw,16367 +transformers/models/deprecated/vit_hybrid/modeling_vit_hybrid.py,sha256=lkcuhuA7FUgqijT_0qy69R-qfQzEsumMQw9CbpFo2as,31187 +transformers/models/deprecated/xlm_prophetnet/__init__.py,sha256=q9zJIXoPqoGPw0x9PQXvpTrpSCw1y1WyYoNCFz-X554,1058 +transformers/models/deprecated/xlm_prophetnet/__pycache__/__init__.cpython-310.pyc,, +transformers/models/deprecated/xlm_prophetnet/__pycache__/configuration_xlm_prophetnet.cpython-310.pyc,, +transformers/models/deprecated/xlm_prophetnet/__pycache__/modeling_xlm_prophetnet.cpython-310.pyc,, +transformers/models/deprecated/xlm_prophetnet/__pycache__/tokenization_xlm_prophetnet.cpython-310.pyc,, +transformers/models/deprecated/xlm_prophetnet/configuration_xlm_prophetnet.py,sha256=eFMoiTH5qFKL6R0aLhV9-uqUvB2oVVcgrAia6wuLnAY,8968 +transformers/models/deprecated/xlm_prophetnet/modeling_xlm_prophetnet.py,sha256=2WOSJBHp4_W0c75GOJVDKMDhaItVk-BkTCoiBJ_NcGk,114276 +transformers/models/deprecated/xlm_prophetnet/tokenization_xlm_prophetnet.py,sha256=5m053u9Y9NEbmCUJlhprGGdC8ZrXy9VkZF3UGg3fsmo,13153 +transformers/models/depth_anything/__init__.py,sha256=Jbd8LXt-fU3_cTF7jBrkBBw-Kzscv6o7O0YiZy0R8-A,1009 +transformers/models/depth_anything/__pycache__/__init__.cpython-310.pyc,, +transformers/models/depth_anything/__pycache__/configuration_depth_anything.cpython-310.pyc,, +transformers/models/depth_anything/__pycache__/modeling_depth_anything.cpython-310.pyc,, +transformers/models/depth_anything/configuration_depth_anything.py,sha256=s_lwOMcrASuIud4jMw8rBn54vNn2zBzb1RTVVm_1KDU,8189 +transformers/models/depth_anything/modeling_depth_anything.py,sha256=UUMEeEXiKc6HBksv-O_TK4c_NFY-Ad5xmKsZrDsjFn0,16675 +transformers/models/depth_pro/__init__.py,sha256=5R4N4IVUQuK8bCFtg9qGvJFceJaHXNj4HdCWkcsyELc,1096 +transformers/models/depth_pro/__pycache__/__init__.cpython-310.pyc,, +transformers/models/depth_pro/__pycache__/configuration_depth_pro.cpython-310.pyc,, +transformers/models/depth_pro/__pycache__/image_processing_depth_pro.cpython-310.pyc,, +transformers/models/depth_pro/__pycache__/image_processing_depth_pro_fast.cpython-310.pyc,, +transformers/models/depth_pro/__pycache__/modeling_depth_pro.cpython-310.pyc,, +transformers/models/depth_pro/configuration_depth_pro.py,sha256=egobmJm308gpyStYixPOET6ikjGZA5kN9U1iCu79Yyw,10675 +transformers/models/depth_pro/image_processing_depth_pro.py,sha256=YBJndM5kRF9WeS41cGGcBXQVmuVr1z42ZyHG2DmuADQ,18962 +transformers/models/depth_pro/image_processing_depth_pro_fast.py,sha256=Rk3J7PTb1TlrQ8PWN4jOqgSbgu1nnldyjSdmFWv_JDM,6697 +transformers/models/depth_pro/modeling_depth_pro.py,sha256=ArZOeVI_0hXCU7ueWa8PVEmg16EF-QS2n-YxVifFFwE,43072 +transformers/models/detr/__init__.py,sha256=YEWZnoCCgWt4KZNfbSi-v4KNDOJT2-ii2sxanyVDkvY,1120 +transformers/models/detr/__pycache__/__init__.cpython-310.pyc,, +transformers/models/detr/__pycache__/configuration_detr.cpython-310.pyc,, +transformers/models/detr/__pycache__/feature_extraction_detr.cpython-310.pyc,, +transformers/models/detr/__pycache__/image_processing_detr.cpython-310.pyc,, +transformers/models/detr/__pycache__/image_processing_detr_fast.cpython-310.pyc,, +transformers/models/detr/__pycache__/modeling_detr.cpython-310.pyc,, +transformers/models/detr/configuration_detr.py,sha256=wSdE-pszgelpLPMBREhmjXk77t8sPYthn9Cj4Qo02Y8,13918 +transformers/models/detr/feature_extraction_detr.py,sha256=VudvO9SXjwtxL9PPT8vM3vFKcpiOGOe6Mt8zbZuIV1I,1586 +transformers/models/detr/image_processing_detr.py,sha256=M58nEKuWgSzmumA5rIondxnghmSi-I0K-s6qgH9ZFlw,94099 +transformers/models/detr/image_processing_detr_fast.py,sha256=AQOc6jfFZ9fHk1JdGMz8r1M5Z138yugJRlVwt8D8BVw,58606 +transformers/models/detr/modeling_detr.py,sha256=JUhvZIbo4eeazVfnZzXCrq7OY0N4LP9vJ4Dsh2umBxU,77797 +transformers/models/dia/__init__.py,sha256=fvBcwJ7FAFDO6RNyUUMGrdSlUtowciNo3YYv7R2Qz1c,1133 +transformers/models/dia/__pycache__/__init__.cpython-310.pyc,, +transformers/models/dia/__pycache__/configuration_dia.cpython-310.pyc,, +transformers/models/dia/__pycache__/feature_extraction_dia.cpython-310.pyc,, +transformers/models/dia/__pycache__/generation_dia.cpython-310.pyc,, +transformers/models/dia/__pycache__/modeling_dia.cpython-310.pyc,, +transformers/models/dia/__pycache__/modular_dia.cpython-310.pyc,, +transformers/models/dia/__pycache__/processing_dia.cpython-310.pyc,, +transformers/models/dia/__pycache__/tokenization_dia.cpython-310.pyc,, +transformers/models/dia/configuration_dia.py,sha256=G6BnNf5536gSsmhLIJco3EMulv0tk7u89VDQLkFp3Hw,20609 +transformers/models/dia/feature_extraction_dia.py,sha256=AlV5JpJ3IfoNTHjK-PPH96ZvxNaM-VMgb_-tjoe6zrM,8501 +transformers/models/dia/generation_dia.py,sha256=pS34MqzVH7_Vw7SJM_vJNzm4Wg8unT9zxx-OjNufsQ8,21579 +transformers/models/dia/modeling_dia.py,sha256=19q2BMDiq5dF2TD-p3gZwq0LK8aWW635Pb9KMnx9X1w,42571 +transformers/models/dia/modular_dia.py,sha256=kXDVJIFH3cKG5GASwkS-vA-aHvZSQPIUdbwTkh6ld7o,33408 +transformers/models/dia/processing_dia.py,sha256=amS9PaB8pEgZ9RAKytZH_KH_NNK7DVnYA9NBBTuY8jE,19969 +transformers/models/dia/tokenization_dia.py,sha256=O4dTQjoErcFLHF5IbLHp2IdlPj_8POhLfkiRr0p0BNI,4511 +transformers/models/dialogpt/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +transformers/models/dialogpt/__pycache__/__init__.cpython-310.pyc,, +transformers/models/diffllama/__init__.py,sha256=Yosk5eQ82PblntLff-bL3pfJZ-AVKp5jbQK5R2SLVc8,1004 +transformers/models/diffllama/__pycache__/__init__.cpython-310.pyc,, +transformers/models/diffllama/__pycache__/configuration_diffllama.cpython-310.pyc,, +transformers/models/diffllama/__pycache__/modeling_diffllama.cpython-310.pyc,, +transformers/models/diffllama/__pycache__/modular_diffllama.cpython-310.pyc,, +transformers/models/diffllama/configuration_diffllama.py,sha256=SQr6FM8h6EQCI-NNYYksvK0JSy2WN8q6aGQNDFbJAgA,10688 +transformers/models/diffllama/modeling_diffllama.py,sha256=5-s9-4khgpEaILoMw61oHAJV8I_WDRuBiPO-jEemD5g,35432 +transformers/models/diffllama/modular_diffllama.py,sha256=4RuvdV8UMZpSbin7zLNmM40jQNrOtD3wW7Rt75W6beg,20665 +transformers/models/dinat/__init__.py,sha256=N0HykajUSY5KsvPQNUxc8jAuuJntmDJ-Dz8Qa8_sJ9E,991 +transformers/models/dinat/__pycache__/__init__.cpython-310.pyc,, +transformers/models/dinat/__pycache__/configuration_dinat.cpython-310.pyc,, +transformers/models/dinat/__pycache__/modeling_dinat.cpython-310.pyc,, +transformers/models/dinat/configuration_dinat.py,sha256=fhGXUqRCEkTgWL6rpPUF7J-W7usE4e7gl3DS_J99wMc,7356 +transformers/models/dinat/modeling_dinat.py,sha256=WZl4uGt1rJxWZAK4mmPGC6ms0q9wQbQ7nGOv4CDc9sI,33824 +transformers/models/dinov2/__init__.py,sha256=fDyp5N-KcJzO-vUeT3fZA8UbC21FfGEhDOlYNvXHHDc,1033 +transformers/models/dinov2/__pycache__/__init__.cpython-310.pyc,, +transformers/models/dinov2/__pycache__/configuration_dinov2.cpython-310.pyc,, +transformers/models/dinov2/__pycache__/modeling_dinov2.cpython-310.pyc,, +transformers/models/dinov2/__pycache__/modeling_flax_dinov2.cpython-310.pyc,, +transformers/models/dinov2/configuration_dinov2.py,sha256=020F55Jhk4nwbpzxfDxzi77Poe-5OpuGZ-f-mxEDYFg,8291 +transformers/models/dinov2/modeling_dinov2.py,sha256=4TduDezEzz_WAEKhdGSkEY8YAqThyir0SWwhH6u200s,28715 +transformers/models/dinov2/modeling_flax_dinov2.py,sha256=dfmeUz3KQ9d7eoX0X0QqJPKLHZv7c8GOrT2VF9_g7zk,31050 +transformers/models/dinov2_with_registers/__init__.py,sha256=s0cefgSRnlIVcdZYV0qz3Q9X3IEChU7mkGbbnr2IH6E,1023 +transformers/models/dinov2_with_registers/__pycache__/__init__.cpython-310.pyc,, +transformers/models/dinov2_with_registers/__pycache__/configuration_dinov2_with_registers.cpython-310.pyc,, +transformers/models/dinov2_with_registers/__pycache__/modeling_dinov2_with_registers.cpython-310.pyc,, +transformers/models/dinov2_with_registers/__pycache__/modular_dinov2_with_registers.cpython-310.pyc,, +transformers/models/dinov2_with_registers/configuration_dinov2_with_registers.py,sha256=Jv2lhwSt3lSvN8BQuhsK6rmW1IKtSqm4un5Qsvdm6DI,8633 +transformers/models/dinov2_with_registers/modeling_dinov2_with_registers.py,sha256=wyz7nf8J8rWLbTVjSDOnjyLcchJgu7orPbHlFQ9zKxk,31010 +transformers/models/dinov2_with_registers/modular_dinov2_with_registers.py,sha256=_8fvWMtffNpDsAvraYs-IERWEUO4pfjUUH3-Zwww6DM,19565 +transformers/models/dinov3_convnext/__init__.py,sha256=8VOE7Jnq3g2JBuwkVcsFoZEerdZF5dn2p5XZ26BMRY4,1011 +transformers/models/dinov3_convnext/__pycache__/__init__.cpython-310.pyc,, +transformers/models/dinov3_convnext/__pycache__/configuration_dinov3_convnext.cpython-310.pyc,, +transformers/models/dinov3_convnext/__pycache__/modeling_dinov3_convnext.cpython-310.pyc,, +transformers/models/dinov3_convnext/configuration_dinov3_convnext.py,sha256=1_jX9wksnEI0Ds7Jb4n5qpI8SNRsDRE5KggYETxwlZo,4279 +transformers/models/dinov3_convnext/modeling_dinov3_convnext.py,sha256=OksbEwowCgncflWokKOuq5eYBxC-IkFziPhp4UhuBN8,10992 +transformers/models/dinov3_vit/__init__.py,sha256=DYSqKAAuJCZAhQyu7pcechuSR025KnzcKNtJIafTq1E,1053 +transformers/models/dinov3_vit/__pycache__/__init__.cpython-310.pyc,, +transformers/models/dinov3_vit/__pycache__/configuration_dinov3_vit.cpython-310.pyc,, +transformers/models/dinov3_vit/__pycache__/image_processing_dinov3_vit_fast.cpython-310.pyc,, +transformers/models/dinov3_vit/__pycache__/modeling_dinov3_vit.cpython-310.pyc,, +transformers/models/dinov3_vit/__pycache__/modular_dinov3_vit.cpython-310.pyc,, +transformers/models/dinov3_vit/configuration_dinov3_vit.py,sha256=GsfLiJ4jFOjK35sL7UPULPsF3ObXMPcZvkOAyKEKikY,7421 +transformers/models/dinov3_vit/image_processing_dinov3_vit_fast.py,sha256=uuEZBAZp5qadAQ-sBuDna9geUlkVhdW7cV76VX0pzl0,3942 +transformers/models/dinov3_vit/modeling_dinov3_vit.py,sha256=efnMFAweyhnZkihc7P5X-vDxxHDm8rKWvwH3_ZRHNwU,22718 +transformers/models/dinov3_vit/modular_dinov3_vit.py,sha256=wuep7S-vBk_hEcD5gK9aiBFE9lVj1f_kG5A7zLoH2ts,17354 +transformers/models/distilbert/__init__.py,sha256=dKwCe9QsyAaNsdUJFMUa-vcuHPSQSuLKFoFBvK3cLEY,1178 +transformers/models/distilbert/__pycache__/__init__.cpython-310.pyc,, +transformers/models/distilbert/__pycache__/configuration_distilbert.cpython-310.pyc,, +transformers/models/distilbert/__pycache__/modeling_distilbert.cpython-310.pyc,, +transformers/models/distilbert/__pycache__/modeling_flax_distilbert.cpython-310.pyc,, +transformers/models/distilbert/__pycache__/modeling_tf_distilbert.cpython-310.pyc,, +transformers/models/distilbert/__pycache__/tokenization_distilbert.cpython-310.pyc,, +transformers/models/distilbert/__pycache__/tokenization_distilbert_fast.cpython-310.pyc,, +transformers/models/distilbert/configuration_distilbert.py,sha256=h2rBKH_a_aEdRDo-5JEHAbVwUf1-6Sy6xpNRjdLvhnE,6055 +transformers/models/distilbert/modeling_distilbert.py,sha256=LZAPfqyZmEXM6pwP7jZvekd7xEJPvC2X2vF7fI6ChkM,56462 +transformers/models/distilbert/modeling_flax_distilbert.py,sha256=U0jH7nehL1vEt1gPTDwA882r8erT6Ol_QnOhgv7owro,32922 +transformers/models/distilbert/modeling_tf_distilbert.py,sha256=tOX6XGcxJXcy3lPurE3r0pRjX0U4TMWExb-EQbFc4eA,48995 +transformers/models/distilbert/tokenization_distilbert.py,sha256=hpvjVFbpRKQ1rFKW9QoGzUf2Ds3DAYLe_ZRLWi2EdCo,20999 +transformers/models/distilbert/tokenization_distilbert_fast.py,sha256=GfYGXroocFvwRahr1KHTowy-qtYwoqeqmt31MWlf2E0,6827 +transformers/models/dit/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +transformers/models/dit/__pycache__/__init__.cpython-310.pyc,, +transformers/models/doge/__init__.py,sha256=SU7Ea0BtJ8psgsDda2RcXdb1466OYN0l5IK7aOiuanY,1024 +transformers/models/doge/__pycache__/__init__.cpython-310.pyc,, +transformers/models/doge/__pycache__/configuration_doge.cpython-310.pyc,, +transformers/models/doge/__pycache__/modeling_doge.cpython-310.pyc,, +transformers/models/doge/__pycache__/modular_doge.cpython-310.pyc,, +transformers/models/doge/configuration_doge.py,sha256=nnuGXqrDVC9o1zt1g2sGqNy2nlwiH1hSv8HUHQQVF-c,13910 +transformers/models/doge/modeling_doge.py,sha256=6UAO7Claalo6giUmgfihjeldr-UUfEa-Qm5U9mNpl_E,36272 +transformers/models/doge/modular_doge.py,sha256=HQnQmH3Rs2CShqxicRXs81qCmqG_IS2VOXF8SKTNooM,37256 +transformers/models/donut/__init__.py,sha256=O1JOQtPxtjcxSfWgC_PUZkmfvcKzjPgNAakujNra1PA,1170 +transformers/models/donut/__pycache__/__init__.cpython-310.pyc,, +transformers/models/donut/__pycache__/configuration_donut_swin.cpython-310.pyc,, +transformers/models/donut/__pycache__/feature_extraction_donut.cpython-310.pyc,, +transformers/models/donut/__pycache__/image_processing_donut.cpython-310.pyc,, +transformers/models/donut/__pycache__/image_processing_donut_fast.cpython-310.pyc,, +transformers/models/donut/__pycache__/modeling_donut_swin.cpython-310.pyc,, +transformers/models/donut/__pycache__/processing_donut.cpython-310.pyc,, +transformers/models/donut/configuration_donut_swin.py,sha256=mHg0P4MRxMOw_IsHKFtBIuSuuY0tINGN3FmUImMqST8,5785 +transformers/models/donut/feature_extraction_donut.py,sha256=JfpHRB_aTYyBkySWUgofHHwGxIA8hpaS8NilnFsgIAU,1292 +transformers/models/donut/image_processing_donut.py,sha256=ZVtXfYgudu0LKhqzEb02TgjOUjGsDhg-z2bTkqhTPcE,22152 +transformers/models/donut/image_processing_donut_fast.py,sha256=JQ3LcYzC9JVAjUZPyk11oyVZmX3uMoxw628Zl_-F9Xs,10016 +transformers/models/donut/modeling_donut_swin.py,sha256=-Iz33safTU4MRpimlQLP4wSfJgyck6-AJUNHfXLszo8,45688 +transformers/models/donut/processing_donut.py,sha256=b8gOo7yxlIM-0aSh2zky5E9WiyVXc-5nYTIiQ0v0dMo,8620 +transformers/models/dots1/__init__.py,sha256=A2jXARtNWOrbWAW2SIrsvvydm2_2keRyUBbNEz0By-I,991 +transformers/models/dots1/__pycache__/__init__.cpython-310.pyc,, +transformers/models/dots1/__pycache__/configuration_dots1.cpython-310.pyc,, +transformers/models/dots1/__pycache__/modeling_dots1.cpython-310.pyc,, +transformers/models/dots1/__pycache__/modular_dots1.cpython-310.pyc,, +transformers/models/dots1/configuration_dots1.py,sha256=c_oMyjwI019zij4AnqwQfJSWGOA81HM7H3QKWwsZ-sE,10104 +transformers/models/dots1/modeling_dots1.py,sha256=0GUi8z2EEVBijain8hL5eySex_YtBNyoC2nLMkHc8Fk,27566 +transformers/models/dots1/modular_dots1.py,sha256=M350mYt43vL3zl2Wzwx2D08eK6mrGZfyMv4xDl23waM,3277 +transformers/models/dpr/__init__.py,sha256=z4FocLkQ_ckWtBZctTh-aeV1haJJY-lXF0ZRKuVbVkc,1099 +transformers/models/dpr/__pycache__/__init__.cpython-310.pyc,, +transformers/models/dpr/__pycache__/configuration_dpr.cpython-310.pyc,, +transformers/models/dpr/__pycache__/modeling_dpr.cpython-310.pyc,, +transformers/models/dpr/__pycache__/modeling_tf_dpr.cpython-310.pyc,, +transformers/models/dpr/__pycache__/tokenization_dpr.cpython-310.pyc,, +transformers/models/dpr/__pycache__/tokenization_dpr_fast.cpython-310.pyc,, +transformers/models/dpr/configuration_dpr.py,sha256=-DGEGi7rH0bSlWSh2WCFvB6cdZ6bJ8kO3u8xvhDS8mk,6432 +transformers/models/dpr/modeling_dpr.py,sha256=L0Kl_E2Cu740zGQPZCT7wpmLBECZNGaS3V3DzRN2a7A,22826 +transformers/models/dpr/modeling_tf_dpr.py,sha256=VpzB67gC0sMnnuVcAxUhHxxj-Lxjnf658LIOFvhKLRc,33857 +transformers/models/dpr/tokenization_dpr.py,sha256=KuNEnPczArBcq36g3p_eueA2Z5AG4Y7vtgqMFHstzE4,15834 +transformers/models/dpr/tokenization_dpr_fast.py,sha256=ClKoqvgOkO4nnQX8R0KwwMTl5gZhh1VLMURD_9nEN-o,16215 +transformers/models/dpt/__init__.py,sha256=7i4wNFCo8NTFsJQi7TO9u0VGxpZ8xg1_QNvD862jNk4,1114 +transformers/models/dpt/__pycache__/__init__.cpython-310.pyc,, +transformers/models/dpt/__pycache__/configuration_dpt.cpython-310.pyc,, +transformers/models/dpt/__pycache__/feature_extraction_dpt.cpython-310.pyc,, +transformers/models/dpt/__pycache__/image_processing_dpt.cpython-310.pyc,, +transformers/models/dpt/__pycache__/image_processing_dpt_fast.cpython-310.pyc,, +transformers/models/dpt/__pycache__/modeling_dpt.cpython-310.pyc,, +transformers/models/dpt/__pycache__/modular_dpt.cpython-310.pyc,, +transformers/models/dpt/configuration_dpt.py,sha256=6U3U6oThmJNDyQ7iwCjGVU5rdS-gUBFU36_O_uKGX3M,14845 +transformers/models/dpt/feature_extraction_dpt.py,sha256=oCMnm3Pf3cDqtuENmJyqiT0F6OOFKKC5AjwldSpx7t8,1276 +transformers/models/dpt/image_processing_dpt.py,sha256=bZaco6DG7X7UStdI5e5Wjsl9Z82YT4aNq8iNZwZxDe8,31693 +transformers/models/dpt/image_processing_dpt_fast.py,sha256=OA3em6yrstj5VfTrwzp3-E7a7DS7ERGD9IAdrk6cuNc,17120 +transformers/models/dpt/modeling_dpt.py,sha256=PZwFopcIFMfDIWwqWYFrqBbnrDr1DAX2M7qvyQF-_0U,51081 +transformers/models/dpt/modular_dpt.py,sha256=-YCUdGQypm_SDonFhnpMHs05BMVmO1ltGTURutGXn40,11912 +transformers/models/edgetam/__init__.py,sha256=oGzMZGNhQp2fv5UQEYcLdYLUIRQEnn3_vucmlOvmM_o,995 +transformers/models/edgetam/__pycache__/__init__.cpython-310.pyc,, +transformers/models/edgetam/__pycache__/configuration_edgetam.cpython-310.pyc,, +transformers/models/edgetam/__pycache__/modeling_edgetam.cpython-310.pyc,, +transformers/models/edgetam/__pycache__/modular_edgetam.cpython-310.pyc,, +transformers/models/edgetam/configuration_edgetam.py,sha256=U_Exgi-kJOOyte5M0XgSwGa-ppjEkf_-vahRDdwy4SI,15499 +transformers/models/edgetam/modeling_edgetam.py,sha256=FXUrPjpP284qdSz61dtr04BWueeNJagcG2-VVa21u24,59347 +transformers/models/edgetam/modular_edgetam.py,sha256=JxUFTdyoIj0Wp2Fe0cDuJOefn2TcSp-FcP44nLf-Zx8,9701 +transformers/models/edgetam_video/__init__.py,sha256=6VuEzH4c1uAjYHV0np4nArGPyCPZxg8UTwukCpJnHbw,1023 +transformers/models/edgetam_video/__pycache__/__init__.cpython-310.pyc,, +transformers/models/edgetam_video/__pycache__/configuration_edgetam_video.cpython-310.pyc,, +transformers/models/edgetam_video/__pycache__/modeling_edgetam_video.cpython-310.pyc,, +transformers/models/edgetam_video/__pycache__/modular_edgetam_video.cpython-310.pyc,, +transformers/models/edgetam_video/configuration_edgetam_video.py,sha256=XaLD87Re-TWi3CBiMNWyhib6sJd6_YrOPMDc0g2vt0k,23699 +transformers/models/edgetam_video/modeling_edgetam_video.py,sha256=rKVpE1ylOrrEpTiW0P1nE1566GXu88D3DbgzkqNDLW0,143139 +transformers/models/edgetam_video/modular_edgetam_video.py,sha256=5Q9aQEUKTd-173isLwKPYcfvYYK_bO824UbPV8Kq8nA,57205 +transformers/models/efficientloftr/__init__.py,sha256=tG2whk3HBxtW2jyKIXiiHuLxzHhaGo8YmfxgZbX-57k,1116 +transformers/models/efficientloftr/__pycache__/__init__.cpython-310.pyc,, +transformers/models/efficientloftr/__pycache__/configuration_efficientloftr.cpython-310.pyc,, +transformers/models/efficientloftr/__pycache__/image_processing_efficientloftr.cpython-310.pyc,, +transformers/models/efficientloftr/__pycache__/image_processing_efficientloftr_fast.cpython-310.pyc,, +transformers/models/efficientloftr/__pycache__/modeling_efficientloftr.cpython-310.pyc,, +transformers/models/efficientloftr/configuration_efficientloftr.py,sha256=RjGJf6yTfjGNkneCvq8PuSbQ58h41cdkKg8GnJL7cWk,10423 +transformers/models/efficientloftr/image_processing_efficientloftr.py,sha256=lIEKp9nZLGBU86o_m2NUt_OvkFT1mzYnc0ndAKiDsn4,21505 +transformers/models/efficientloftr/image_processing_efficientloftr_fast.py,sha256=RGbuaRnYSv_sluhbmSKK4nZLNDOqokyQQ1ApJW09EZ4,12610 +transformers/models/efficientloftr/modeling_efficientloftr.py,sha256=mvqNZgZb_6oXGGm68RVOSSqmn8MYJM66Xts48Ut24Is,58711 +transformers/models/efficientnet/__init__.py,sha256=0wxLCBxWBCh8uj4nH1syYJ76kRvUlMS6EUN5E2L2Qwc,1108 +transformers/models/efficientnet/__pycache__/__init__.cpython-310.pyc,, +transformers/models/efficientnet/__pycache__/configuration_efficientnet.cpython-310.pyc,, +transformers/models/efficientnet/__pycache__/image_processing_efficientnet.cpython-310.pyc,, +transformers/models/efficientnet/__pycache__/image_processing_efficientnet_fast.cpython-310.pyc,, +transformers/models/efficientnet/__pycache__/modeling_efficientnet.cpython-310.pyc,, +transformers/models/efficientnet/configuration_efficientnet.py,sha256=pzLFg-QlskKos0hEVJI55TihTkR0Kn_WvxRAtHQEN_E,7660 +transformers/models/efficientnet/image_processing_efficientnet.py,sha256=pNf4S1dZSS-eRUR0UESMKiNeUVyHx10SINHwtsRd4hE,18450 +transformers/models/efficientnet/image_processing_efficientnet_fast.py,sha256=f7pFk0mnkkHFjzpX4HhJDKGRVGEJ30jOR3Ka3JxaaeU,7878 +transformers/models/efficientnet/modeling_efficientnet.py,sha256=P0kfpJW6TcstFqVYIYhmJLg_IGuHRGmAslT00MRCs38,20255 +transformers/models/electra/__init__.py,sha256=e6DkZL6cjtWVsTx7tamR-zsyv0tuRYLbuYn-r-04P84,1160 +transformers/models/electra/__pycache__/__init__.cpython-310.pyc,, +transformers/models/electra/__pycache__/configuration_electra.cpython-310.pyc,, +transformers/models/electra/__pycache__/modeling_electra.cpython-310.pyc,, +transformers/models/electra/__pycache__/modeling_flax_electra.cpython-310.pyc,, +transformers/models/electra/__pycache__/modeling_tf_electra.cpython-310.pyc,, +transformers/models/electra/__pycache__/tokenization_electra.cpython-310.pyc,, +transformers/models/electra/__pycache__/tokenization_electra_fast.cpython-310.pyc,, +transformers/models/electra/configuration_electra.py,sha256=Q8udyq_AymQzkwnlrPurj4mdl9f4QU2l0YODKH523uc,9170 +transformers/models/electra/modeling_electra.py,sha256=oyBU8qwulBkK2yPUx9LYuohCfUGQ8NDvblZKQawTpXw,69813 +transformers/models/electra/modeling_flax_electra.py,sha256=I8aa02ZkCCKL6ch_L38BFxYmQK-EWuMnSEUsT_qUxPE,62613 +transformers/models/electra/modeling_tf_electra.py,sha256=dW-ED6HQKsLpr_QzQy3OqL-nMZBzmT_lhrlRz2bic08,78430 +transformers/models/electra/tokenization_electra.py,sha256=n0A4Wm-kdEhLKUkbn3dFM8nGWPV0vV71AzpH-YigFmk,20108 +transformers/models/electra/tokenization_electra_fast.py,sha256=vIX5oBKDTWD2Vn_CHNOUFX9Y3PB4QTUfxGyZNUswEVY,6590 +transformers/models/emu3/__init__.py,sha256=VEBLADqeToacty2xd3Zu0F_fLQRxvhfiKPkuB9jwcFM,1070 +transformers/models/emu3/__pycache__/__init__.cpython-310.pyc,, +transformers/models/emu3/__pycache__/configuration_emu3.cpython-310.pyc,, +transformers/models/emu3/__pycache__/image_processing_emu3.cpython-310.pyc,, +transformers/models/emu3/__pycache__/modeling_emu3.cpython-310.pyc,, +transformers/models/emu3/__pycache__/modular_emu3.cpython-310.pyc,, +transformers/models/emu3/__pycache__/processing_emu3.cpython-310.pyc,, +transformers/models/emu3/configuration_emu3.py,sha256=1zPD80z9vAL54uZOgcBFqg5R6qXdLunsJXfYjH61eUc,16196 +transformers/models/emu3/image_processing_emu3.py,sha256=97ca3p77vjZMHvdnAxhcVzI0XrTG3hADD3DJAp__2T8,27279 +transformers/models/emu3/modeling_emu3.py,sha256=3ZEGY_OX9Sen4V67apRiu2VL3gpS7DERjNqd52Ft6X0,65127 +transformers/models/emu3/modular_emu3.py,sha256=VaJz03Jlu2vByoQBTfcDtSJXBy6AzFWRkgYmjqsx96w,46503 +transformers/models/emu3/processing_emu3.py,sha256=ECEglZiz4JzBpGiyvhvsYDxsiZ3Dmapgw-FNxzfoyVg,11793 +transformers/models/encodec/__init__.py,sha256=QbO9yEfCaRwYKbK0vvmwKMbqRAToyos-HTHhRmf7n5s,1041 +transformers/models/encodec/__pycache__/__init__.cpython-310.pyc,, +transformers/models/encodec/__pycache__/configuration_encodec.cpython-310.pyc,, +transformers/models/encodec/__pycache__/feature_extraction_encodec.cpython-310.pyc,, +transformers/models/encodec/__pycache__/modeling_encodec.cpython-310.pyc,, +transformers/models/encodec/configuration_encodec.py,sha256=yi016nmXOdgM9NgSSWJW6rDDHpzTIPJJ8gG9OHZK83w,8705 +transformers/models/encodec/feature_extraction_encodec.py,sha256=ANwwpLKhArrcXtqC4eLpFFeJ2fZReWsaAtvdDuCcUYg,9944 +transformers/models/encodec/modeling_encodec.py,sha256=hmDympFkHTgJCVlAzeQFz-e90AgSf8aF9gA-OeurUyY,34606 +transformers/models/encoder_decoder/__init__.py,sha256=wxXN9-4nCvYICfq8pE592rdRiQXK7S69V2cWGVQyIkw,1107 +transformers/models/encoder_decoder/__pycache__/__init__.cpython-310.pyc,, +transformers/models/encoder_decoder/__pycache__/configuration_encoder_decoder.cpython-310.pyc,, +transformers/models/encoder_decoder/__pycache__/modeling_encoder_decoder.cpython-310.pyc,, +transformers/models/encoder_decoder/__pycache__/modeling_flax_encoder_decoder.cpython-310.pyc,, +transformers/models/encoder_decoder/__pycache__/modeling_tf_encoder_decoder.cpython-310.pyc,, +transformers/models/encoder_decoder/configuration_encoder_decoder.py,sha256=3RReXpXx5UcFH8EEfzAsyQrbJ9FmHuHfZ3vx-Br1-54,4596 +transformers/models/encoder_decoder/modeling_encoder_decoder.py,sha256=7cohVOyp3j7WZV_FMZ37Owz2d4YwNp5C5g3lf9wigcA,30038 +transformers/models/encoder_decoder/modeling_flax_encoder_decoder.py,sha256=U3bHgOkJxZQRUqXOacW7nExXg4j2zI9850rSDCWoFDU,43595 +transformers/models/encoder_decoder/modeling_tf_encoder_decoder.py,sha256=qS8cY9FGuUbFajw75i496zVBPJJIf17ZxVKkMAfcKQ8,34188 +transformers/models/eomt/__init__.py,sha256=yXVhFSLXI_umGHqTtRHHaTevf4KwrA9LOldvY7DfuFk,1076 +transformers/models/eomt/__pycache__/__init__.cpython-310.pyc,, +transformers/models/eomt/__pycache__/configuration_eomt.cpython-310.pyc,, +transformers/models/eomt/__pycache__/image_processing_eomt.cpython-310.pyc,, +transformers/models/eomt/__pycache__/image_processing_eomt_fast.cpython-310.pyc,, +transformers/models/eomt/__pycache__/modeling_eomt.cpython-310.pyc,, +transformers/models/eomt/__pycache__/modular_eomt.cpython-310.pyc,, +transformers/models/eomt/configuration_eomt.py,sha256=nvH6qjar0r7ejH9yM_WWvz8aiVQJG188ZdLedGMTOUw,8069 +transformers/models/eomt/image_processing_eomt.py,sha256=9LiR3mUdge-GsB2aTzhm0ypSCzYBru78MGaIv9zDprY,41160 +transformers/models/eomt/image_processing_eomt_fast.py,sha256=5HpXCUeyAaSfm_NCC1tigaJrcexCnZA0gKjbX83rG7E,21824 +transformers/models/eomt/modeling_eomt.py,sha256=FGIZjJ46p2TRhcmj8cFMZzZqqq0c50IuuanlzA_rJAg,54622 +transformers/models/eomt/modular_eomt.py,sha256=XpyX6NrlLCH4nAmGUbQdKj48Uyau0XESD0eTP_pijlk,25332 +transformers/models/ernie/__init__.py,sha256=TyzaXpzGwu-WqsIn1tavDqa7BCV9X-mPho4JDa9gk0I,991 +transformers/models/ernie/__pycache__/__init__.cpython-310.pyc,, +transformers/models/ernie/__pycache__/configuration_ernie.cpython-310.pyc,, +transformers/models/ernie/__pycache__/modeling_ernie.cpython-310.pyc,, +transformers/models/ernie/configuration_ernie.py,sha256=_1shyRgpTVMQS2z7kEW8FF7spluVDc-azldGq8Clr4Y,7719 +transformers/models/ernie/modeling_ernie.py,sha256=lyvxE0tqlqlOhQvVhn_tmPyneE3ooH_qQd20whEa1ZY,76788 +transformers/models/ernie4_5/__init__.py,sha256=5tqpitaOWvT1CdXTgMtMLCKIkUG683y3jdcTZ8yuwfM,997 +transformers/models/ernie4_5/__pycache__/__init__.cpython-310.pyc,, +transformers/models/ernie4_5/__pycache__/configuration_ernie4_5.cpython-310.pyc,, +transformers/models/ernie4_5/__pycache__/modeling_ernie4_5.cpython-310.pyc,, +transformers/models/ernie4_5/__pycache__/modular_ernie4_5.cpython-310.pyc,, +transformers/models/ernie4_5/configuration_ernie4_5.py,sha256=Sg3qqYRBjErH7dPcyPdfe3CKYnaxSpjo5d2tI5RAVvs,10671 +transformers/models/ernie4_5/modeling_ernie4_5.py,sha256=t6FppbP1O7icRfoOsps_cNQ3KLdvFTikvrK5dAvrGY4,20583 +transformers/models/ernie4_5/modular_ernie4_5.py,sha256=ake2tS9BcYGYQXtIeL2qvCjEsSpqItrWOtaxJTy6_tU,5604 +transformers/models/ernie4_5_moe/__init__.py,sha256=MJaAQxyB3YypXN79FGJpkSvnX6KWt86iunOFXjiA7a4,1005 +transformers/models/ernie4_5_moe/__pycache__/__init__.cpython-310.pyc,, +transformers/models/ernie4_5_moe/__pycache__/configuration_ernie4_5_moe.cpython-310.pyc,, +transformers/models/ernie4_5_moe/__pycache__/modeling_ernie4_5_moe.cpython-310.pyc,, +transformers/models/ernie4_5_moe/__pycache__/modular_ernie4_5_moe.cpython-310.pyc,, +transformers/models/ernie4_5_moe/configuration_ernie4_5_moe.py,sha256=HpcWwQdyQFpvYwFzMBptIsUq90mRDxNVDQEXpJGJUc8,13489 +transformers/models/ernie4_5_moe/modeling_ernie4_5_moe.py,sha256=gjdVoctA729oN6EjkXh2YYcTsfNX8GKcWCO_PcMfg3k,33541 +transformers/models/ernie4_5_moe/modular_ernie4_5_moe.py,sha256=-VB2OWfxK4TnyFwP1fGqApm1EYYMGYHBdYzuYS3L5UI,14444 +transformers/models/esm/__init__.py,sha256=muSqvVMt6mySkoAm7MjweiFHJVBSj70LlakjHmZ6PEE,1094 +transformers/models/esm/__pycache__/__init__.cpython-310.pyc,, +transformers/models/esm/__pycache__/configuration_esm.cpython-310.pyc,, +transformers/models/esm/__pycache__/modeling_esm.cpython-310.pyc,, +transformers/models/esm/__pycache__/modeling_esmfold.cpython-310.pyc,, +transformers/models/esm/__pycache__/modeling_tf_esm.cpython-310.pyc,, +transformers/models/esm/__pycache__/tokenization_esm.cpython-310.pyc,, +transformers/models/esm/configuration_esm.py,sha256=ehwkp9UcXcXXp6dphMO7cqdn-G1Bv1LUB4sohOvWy6Y,14436 +transformers/models/esm/modeling_esm.py,sha256=R7pQx6-rttj9ux-9poUXcvrrXth0rJnNcoNFGz2JIvo,43625 +transformers/models/esm/modeling_esmfold.py,sha256=wc-jMGK2mCfAMX1Q2JpRRIgvDkxf8kM3vPTnEBHEm8I,86171 +transformers/models/esm/modeling_tf_esm.py,sha256=5GsQDy8NmoHzk0s9rr1PhBQXmGke7FgtKYxd6XN0k_k,68985 +transformers/models/esm/openfold_utils/__init__.py,sha256=Xy2uqvFsLC8Ax-OOce5PgoBDiZgEJgJPqs__p5SBWUY,446 +transformers/models/esm/openfold_utils/__pycache__/__init__.cpython-310.pyc,, +transformers/models/esm/openfold_utils/__pycache__/chunk_utils.cpython-310.pyc,, +transformers/models/esm/openfold_utils/__pycache__/data_transforms.cpython-310.pyc,, +transformers/models/esm/openfold_utils/__pycache__/feats.cpython-310.pyc,, +transformers/models/esm/openfold_utils/__pycache__/loss.cpython-310.pyc,, +transformers/models/esm/openfold_utils/__pycache__/protein.cpython-310.pyc,, +transformers/models/esm/openfold_utils/__pycache__/residue_constants.cpython-310.pyc,, +transformers/models/esm/openfold_utils/__pycache__/rigid_utils.cpython-310.pyc,, +transformers/models/esm/openfold_utils/__pycache__/tensor_utils.cpython-310.pyc,, +transformers/models/esm/openfold_utils/chunk_utils.py,sha256=dwwoG_7zj-juGYg3bb1QZa0LPASNsRm7I1Oq9optMwk,14390 +transformers/models/esm/openfold_utils/data_transforms.py,sha256=Q5J_BpJ_8Fa5fZ8nP6kPB5ops-Y4MydSQkwZ-_yMDBA,3688 +transformers/models/esm/openfold_utils/feats.py,sha256=QCYupsVINo5jJuwYk38TejNYkPlGm6Kfc1YpNUxpI8s,8355 +transformers/models/esm/openfold_utils/loss.py,sha256=sndbYMMXuL0KIHlzq7ZJUlQoIRMy2Q3ZGl3h20BR1rg,3692 +transformers/models/esm/openfold_utils/protein.py,sha256=Ii9o1j_qa6cJgcJ8WBNvrVXhvuUX3668sOf1WCkJflo,11497 +transformers/models/esm/openfold_utils/residue_constants.py,sha256=-y44cw8jjQJakRSjn4MAMCeGhFSHoPzUCiMv9MfdGes,37875 +transformers/models/esm/openfold_utils/rigid_utils.py,sha256=oM1q5gGBukDtpQqrJosTmfASUEQRjM7Lo-u2PR-W6Cs,41006 +transformers/models/esm/openfold_utils/tensor_utils.py,sha256=94wNOGOftULOVB_WsyH6b-Sv38Ny1QCa4R6he3iRyl8,4763 +transformers/models/esm/tokenization_esm.py,sha256=HcbVQ9J-e7NjuhVSqcHMj-2PIGTtok-5zRRT-YhffdE,5379 +transformers/models/evolla/__init__.py,sha256=pOj8KGoc9jqtS_PYTeNCxZUtQrlFR_txE-kdZpiAkCw,1030 +transformers/models/evolla/__pycache__/__init__.cpython-310.pyc,, +transformers/models/evolla/__pycache__/configuration_evolla.cpython-310.pyc,, +transformers/models/evolla/__pycache__/modeling_evolla.cpython-310.pyc,, +transformers/models/evolla/__pycache__/modular_evolla.cpython-310.pyc,, +transformers/models/evolla/__pycache__/processing_evolla.cpython-310.pyc,, +transformers/models/evolla/configuration_evolla.py,sha256=jz9pKidmvndFIVcAAlpjw7BTb3i-Mv94ac9yhLprNlA,13817 +transformers/models/evolla/modeling_evolla.py,sha256=hH3UdwnTAScW8zb-KHhi24Ql7b32Ev-CkyGa322Qdww,68759 +transformers/models/evolla/modular_evolla.py,sha256=JaPT158JdJ1RGhWso4iTRYSYZXa6ikx3pvjGvgsv7fQ,41300 +transformers/models/evolla/processing_evolla.py,sha256=l__liYSr-NmfClwzRCL88HoIAUs1TZpFYVyn4edYzlU,11480 +transformers/models/exaone4/__init__.py,sha256=gUDbb0olRjqxaPnB3APYKYKRlDPG2phGkfrmf7mIVD4,1018 +transformers/models/exaone4/__pycache__/__init__.cpython-310.pyc,, +transformers/models/exaone4/__pycache__/configuration_exaone4.cpython-310.pyc,, +transformers/models/exaone4/__pycache__/modeling_exaone4.cpython-310.pyc,, +transformers/models/exaone4/__pycache__/modular_exaone4.cpython-310.pyc,, +transformers/models/exaone4/configuration_exaone4.py,sha256=4BHo8dBOpEPtp-4n-ZV9rSB-JtkGdlIYrWtgE6w5iwE,12514 +transformers/models/exaone4/modeling_exaone4.py,sha256=JOBB_tM3aEDy4txmlHmHV5MTnpGQKABicClwn44BQgk,23690 +transformers/models/exaone4/modular_exaone4.py,sha256=Zg1aXfu3XlNUzFUYckE1pKJoLLvIUlsr5cbUm0Zn52Y,23643 +transformers/models/falcon/__init__.py,sha256=qmBlF_xusyrueKMfriC2ldVrHzeLIT7ruSdduMODuE4,993 +transformers/models/falcon/__pycache__/__init__.cpython-310.pyc,, +transformers/models/falcon/__pycache__/configuration_falcon.cpython-310.pyc,, +transformers/models/falcon/__pycache__/modeling_falcon.cpython-310.pyc,, +transformers/models/falcon/configuration_falcon.py,sha256=5vh10LAkioX6y3qJh84u3SlXmu3gPArXNMe1apM7f9g,10917 +transformers/models/falcon/modeling_falcon.py,sha256=H0LI3p32Zu7IxZT3EfabgEoLNWvU5vAs7_yzK2k_0gs,63968 +transformers/models/falcon_h1/__init__.py,sha256=cpix3f3f_xMDLf2OLuyYZULnb7enZl3UZapPQuf0YZc,1012 +transformers/models/falcon_h1/__pycache__/__init__.cpython-310.pyc,, +transformers/models/falcon_h1/__pycache__/configuration_falcon_h1.cpython-310.pyc,, +transformers/models/falcon_h1/__pycache__/modeling_falcon_h1.cpython-310.pyc,, +transformers/models/falcon_h1/__pycache__/modular_falcon_h1.cpython-310.pyc,, +transformers/models/falcon_h1/configuration_falcon_h1.py,sha256=ql8WPS_TKtf2KPz0Ko_WxJpf7NVnyufn-B-j20kewfc,13894 +transformers/models/falcon_h1/modeling_falcon_h1.py,sha256=ho4wA8e3m2zRNW0rf4hYlfilnLGOlh9FaHB4dP4swr8,74104 +transformers/models/falcon_h1/modular_falcon_h1.py,sha256=GrayFTwl3omibc-3Eq8fQCZmT20yf3dg2sBgc3LhJ9w,62060 +transformers/models/falcon_mamba/__init__.py,sha256=Czo-T_Nt73nvRbK-yJEZAYsU3Bxu4i1fOxFuPosiFPw,1005 +transformers/models/falcon_mamba/__pycache__/__init__.cpython-310.pyc,, +transformers/models/falcon_mamba/__pycache__/configuration_falcon_mamba.cpython-310.pyc,, +transformers/models/falcon_mamba/__pycache__/modeling_falcon_mamba.cpython-310.pyc,, +transformers/models/falcon_mamba/__pycache__/modular_falcon_mamba.cpython-310.pyc,, +transformers/models/falcon_mamba/configuration_falcon_mamba.py,sha256=xbRMQ4ZHRpJmNHxVJh2tIYtnMJWAME0aDbKe1oMY_34,8846 +transformers/models/falcon_mamba/modeling_falcon_mamba.py,sha256=FNLdMUwOlFNjCHyQazOHu5czgnwpQCQL2o22jkI41Wo,43095 +transformers/models/falcon_mamba/modular_falcon_mamba.py,sha256=RQ0kTvNF7LiFgGduy7fOvhIwCBVCRB4liCWJQx5ajYQ,26342 +transformers/models/fastspeech2_conformer/__init__.py,sha256=pILmX51CcqSiFGtl_dsX1yW2S_QugA3UHAT8f4psOtA,1077 +transformers/models/fastspeech2_conformer/__pycache__/__init__.cpython-310.pyc,, +transformers/models/fastspeech2_conformer/__pycache__/configuration_fastspeech2_conformer.cpython-310.pyc,, +transformers/models/fastspeech2_conformer/__pycache__/modeling_fastspeech2_conformer.cpython-310.pyc,, +transformers/models/fastspeech2_conformer/__pycache__/tokenization_fastspeech2_conformer.cpython-310.pyc,, +transformers/models/fastspeech2_conformer/configuration_fastspeech2_conformer.py,sha256=TZ6a2rSWE3ikugOBx_sr4tULm2FpX8Qtj2S7MLBdnNQ,24656 +transformers/models/fastspeech2_conformer/modeling_fastspeech2_conformer.py,sha256=x5A-irRigdYUA7wZoHIWznuitR26YoEdFA-Anmz3c7I,69493 +transformers/models/fastspeech2_conformer/tokenization_fastspeech2_conformer.py,sha256=x8b0G-lsibtRBg-I3FzLBHC1YhiTmr8A2o6V8LbEz6M,6258 +transformers/models/flaubert/__init__.py,sha256=LdGmxq7pcDPVcvqO1ol7VYtpjKKCAQuiJ1ISrNT9nEs,1078 +transformers/models/flaubert/__pycache__/__init__.cpython-310.pyc,, +transformers/models/flaubert/__pycache__/configuration_flaubert.cpython-310.pyc,, +transformers/models/flaubert/__pycache__/modeling_flaubert.cpython-310.pyc,, +transformers/models/flaubert/__pycache__/modeling_tf_flaubert.cpython-310.pyc,, +transformers/models/flaubert/__pycache__/tokenization_flaubert.cpython-310.pyc,, +transformers/models/flaubert/configuration_flaubert.py,sha256=920NSmtA4I1NbeTk642E8OvKEWD9TnwBggtaIGyx70U,11250 +transformers/models/flaubert/modeling_flaubert.py,sha256=o91gC3wmWAM4HXfeAtU8BwMQzlqmOv-Po_HZljFL2zM,80054 +transformers/models/flaubert/modeling_tf_flaubert.py,sha256=zeZWpnYi56nPKArmP43f6TTDPOxxObhgjd0CXJ4Y3Qo,57170 +transformers/models/flaubert/tokenization_flaubert.py,sha256=ACYpzkElWcCyW9lJX9mRqh1-uEI9qqV2IQIXSr8JhPk,20970 +transformers/models/flava/__init__.py,sha256=UZ-PnfpalIOh2pPXWj_WSjsxjLgMBh2kKVyyLsNTUOk,1160 +transformers/models/flava/__pycache__/__init__.cpython-310.pyc,, +transformers/models/flava/__pycache__/configuration_flava.cpython-310.pyc,, +transformers/models/flava/__pycache__/feature_extraction_flava.cpython-310.pyc,, +transformers/models/flava/__pycache__/image_processing_flava.cpython-310.pyc,, +transformers/models/flava/__pycache__/image_processing_flava_fast.cpython-310.pyc,, +transformers/models/flava/__pycache__/modeling_flava.cpython-310.pyc,, +transformers/models/flava/__pycache__/processing_flava.cpython-310.pyc,, +transformers/models/flava/configuration_flava.py,sha256=5rnIMzvISrCpS012IshWXbiLyc4gvSrhWursvORJUF0,34021 +transformers/models/flava/feature_extraction_flava.py,sha256=fZzf449ea7VNw1xyNfCuoa_e2pMEfGSxqNTX9YdoE5I,1314 +transformers/models/flava/image_processing_flava.py,sha256=qimlDnZCGEENOX1KHI09-5TKHebHnRcIQ8BJhgIRWaw,37688 +transformers/models/flava/image_processing_flava_fast.py,sha256=iJbfdyw-KeQwWURqvrmYnG7UmJecgxFnxOEymzeJyCM,22502 +transformers/models/flava/modeling_flava.py,sha256=ri_xl_yKna46z6-KiTcAtYkUprQF6Jh2EaE75zUK5lU,94428 +transformers/models/flava/processing_flava.py,sha256=VhcJAQLYGs-TqpmOK3uw9eL9yxI1XQc2Y_lXZ3IIpfc,3899 +transformers/models/flex_olmo/__init__.py,sha256=g2YZth5tFESCUDBUKffzcqm2Z3_u5jYc90XzKMj1jk0,1015 +transformers/models/flex_olmo/__pycache__/__init__.cpython-310.pyc,, +transformers/models/flex_olmo/__pycache__/configuration_flex_olmo.cpython-310.pyc,, +transformers/models/flex_olmo/__pycache__/modeling_flex_olmo.cpython-310.pyc,, +transformers/models/flex_olmo/__pycache__/modular_flex_olmo.cpython-310.pyc,, +transformers/models/flex_olmo/configuration_flex_olmo.py,sha256=4C_2V1KzreoxBUhkba3bFQRgmQPTNdCPJ3s0ZIf4MWE,10575 +transformers/models/flex_olmo/modeling_flex_olmo.py,sha256=mc4SjHIY8Lv-kD3M8wOHXGsHUTX6IebdPDZjQ4OFi6U,31572 +transformers/models/flex_olmo/modular_flex_olmo.py,sha256=ghnphGf4Rjc_6elkSC9xYlt2i6wfg3aV7Dnt9cSy-jc,15593 +transformers/models/florence2/__init__.py,sha256=H4rJT4tWJithwWolb041i7SM693Y_-oO8hhdePbjYpY,1039 +transformers/models/florence2/__pycache__/__init__.cpython-310.pyc,, +transformers/models/florence2/__pycache__/configuration_florence2.cpython-310.pyc,, +transformers/models/florence2/__pycache__/modeling_florence2.cpython-310.pyc,, +transformers/models/florence2/__pycache__/modular_florence2.cpython-310.pyc,, +transformers/models/florence2/__pycache__/processing_florence2.cpython-310.pyc,, +transformers/models/florence2/configuration_florence2.py,sha256=elSEHjPwVE3GcOUCJDVktLEINt_lD2BIJCSAnFqlFhU,9623 +transformers/models/florence2/modeling_florence2.py,sha256=q3mw6pmDDSyERuEyZf_e_0A77FP-C9CVCyO9nTBB1yk,43633 +transformers/models/florence2/modular_florence2.py,sha256=iaQhlKJuACheRoiESyPEZb54_6FiJr8IxHyxxNga1SU,78624 +transformers/models/florence2/processing_florence2.py,sha256=D_Th63wqNZJBgHjNp4FH4SX0yGx8sLPFO_h-qbJU8bM,36775 +transformers/models/fnet/__init__.py,sha256=V3nuz_DsD_K5-RuL-Gt4hr5FVtNz12s46O_Vtx_xvCY,1068 +transformers/models/fnet/__pycache__/__init__.cpython-310.pyc,, +transformers/models/fnet/__pycache__/configuration_fnet.cpython-310.pyc,, +transformers/models/fnet/__pycache__/modeling_fnet.cpython-310.pyc,, +transformers/models/fnet/__pycache__/tokenization_fnet.cpython-310.pyc,, +transformers/models/fnet/__pycache__/tokenization_fnet_fast.cpython-310.pyc,, +transformers/models/fnet/configuration_fnet.py,sha256=oZVGszdEYsE-nJnpSlmU3r4tENCfwHnNKaL4NmrD7N4,5567 +transformers/models/fnet/modeling_fnet.py,sha256=eVQU_D8tFJSy_XEbFbkHWlguyNdOInCx9mTYHdMAP2k,44193 +transformers/models/fnet/tokenization_fnet.py,sha256=1oHKKZ05BkW9gY2Ibq__USJVrfxIL6ee2_kJK3vTH_Y,13537 +transformers/models/fnet/tokenization_fnet_fast.py,sha256=Ed77wG8t5cE351Rx2shX98ysFjQFasEor4-U0zj2wYk,6841 +transformers/models/focalnet/__init__.py,sha256=kFk7pYv4troBIWdCYosHMKh8PAnpXqjlxaRRQ5adkG0,997 +transformers/models/focalnet/__pycache__/__init__.cpython-310.pyc,, +transformers/models/focalnet/__pycache__/configuration_focalnet.cpython-310.pyc,, +transformers/models/focalnet/__pycache__/modeling_focalnet.cpython-310.pyc,, +transformers/models/focalnet/configuration_focalnet.py,sha256=L6CS3mcLLDZTIFeiTqweu8W1MogNQq8ZMrIiD_-g1x4,8057 +transformers/models/focalnet/modeling_focalnet.py,sha256=mDIxh2fvOw-AOZ-0P4UWaUw3Dg0Wiws19HHLa2VamQw,37537 +transformers/models/fsmt/__init__.py,sha256=u_Xx7d3qDicqwR_W0js1h2wPiLKWM1RlMu7fsBdIHy4,1026 +transformers/models/fsmt/__pycache__/__init__.cpython-310.pyc,, +transformers/models/fsmt/__pycache__/configuration_fsmt.cpython-310.pyc,, +transformers/models/fsmt/__pycache__/modeling_fsmt.cpython-310.pyc,, +transformers/models/fsmt/__pycache__/tokenization_fsmt.cpython-310.pyc,, +transformers/models/fsmt/configuration_fsmt.py,sha256=TWNVhQROEA1WMCL6j3HX3nRkyhVsB2n2kwNb6QkE4pY,10363 +transformers/models/fsmt/modeling_fsmt.py,sha256=n7TphdY7Y6y3d7HonFlp4TBw0X0wqx6reIopQAT05vY,53104 +transformers/models/fsmt/tokenization_fsmt.py,sha256=86Txz3pYk6fL5nWcqfbpBSo_EuaC-O6tqqHo5zu9GUw,17944 +transformers/models/funnel/__init__.py,sha256=087Y3Xz6y0HA5SgKe-s2z-ZzUIq1u_axxCRh2__gVro,1182 +transformers/models/funnel/__pycache__/__init__.cpython-310.pyc,, +transformers/models/funnel/__pycache__/configuration_funnel.cpython-310.pyc,, +transformers/models/funnel/__pycache__/modeling_funnel.cpython-310.pyc,, +transformers/models/funnel/__pycache__/modeling_tf_funnel.cpython-310.pyc,, +transformers/models/funnel/__pycache__/tokenization_funnel.cpython-310.pyc,, +transformers/models/funnel/__pycache__/tokenization_funnel_fast.cpython-310.pyc,, +transformers/models/funnel/configuration_funnel.py,sha256=b53gi5CW7KpmzFFAM2klOVODwb1Jq30XbzX1rINu7x8,7682 +transformers/models/funnel/modeling_funnel.py,sha256=k5rkMNmHEkJ2YON2bDDmb5a9krS9z-ZjxZR-1OSIuMo,61585 +transformers/models/funnel/modeling_tf_funnel.py,sha256=ZMdqwNPK3WkhzO-HAfaDtbtoctQwEDjGsfiHsJ_CXWg,80735 +transformers/models/funnel/tokenization_funnel.py,sha256=2VRzAH-LPCQcL_gm0LFKsoIPdAKajzCC3gUhrBWuPRE,22685 +transformers/models/funnel/tokenization_funnel_fast.py,sha256=dMo_pnTLyD926bjcPiormC4L_l6oV3W-Xt7xy858Mfs,8666 +transformers/models/fuyu/__init__.py,sha256=NcygIhTFvIZzXPZUReC1WYReGAVINSpG0xW7KqEmd8c,1065 +transformers/models/fuyu/__pycache__/__init__.cpython-310.pyc,, +transformers/models/fuyu/__pycache__/configuration_fuyu.cpython-310.pyc,, +transformers/models/fuyu/__pycache__/image_processing_fuyu.cpython-310.pyc,, +transformers/models/fuyu/__pycache__/modeling_fuyu.cpython-310.pyc,, +transformers/models/fuyu/__pycache__/processing_fuyu.cpython-310.pyc,, +transformers/models/fuyu/configuration_fuyu.py,sha256=7jgdM3jnzy-Z-IZGjx3VgAhuS5_bnEa7FIO8y6kVTaw,10198 +transformers/models/fuyu/image_processing_fuyu.py,sha256=gwh-EQC7Fd5JajX9bNgnW5SxLnCljbFMQmvVD4-tBVI,33659 +transformers/models/fuyu/modeling_fuyu.py,sha256=4Ezt0hQL6I6uLxTuGyTPzybp73ExTNMf2v2KjNGoHjc,18161 +transformers/models/fuyu/processing_fuyu.py,sha256=uLWX5xTMmnScTYgVxQReqdFGr17V0vK6PDAJ3zSLs-E,36693 +transformers/models/gemma/__init__.py,sha256=xXoIfeCXNQOEnARxU3QucfH5mn-a_AE4wp69YkykT50,1111 +transformers/models/gemma/__pycache__/__init__.cpython-310.pyc,, +transformers/models/gemma/__pycache__/configuration_gemma.cpython-310.pyc,, +transformers/models/gemma/__pycache__/modeling_flax_gemma.cpython-310.pyc,, +transformers/models/gemma/__pycache__/modeling_gemma.cpython-310.pyc,, +transformers/models/gemma/__pycache__/modular_gemma.cpython-310.pyc,, +transformers/models/gemma/__pycache__/tokenization_gemma.cpython-310.pyc,, +transformers/models/gemma/__pycache__/tokenization_gemma_fast.cpython-310.pyc,, +transformers/models/gemma/configuration_gemma.py,sha256=LWnoaGz53xxPIbZT1WzQEuF7Rt_MplPVQ9NvP55XE9I,8375 +transformers/models/gemma/modeling_flax_gemma.py,sha256=rRGlPaBXI_lxtLz47GfwZabrdzM8EHctNgitlXNjz4Q,32439 +transformers/models/gemma/modeling_gemma.py,sha256=eazxkgEDGd7kDjO55lvHL3MFYDSmf1r4VTvSMqnnAI0,21385 +transformers/models/gemma/modular_gemma.py,sha256=tRFQEhUSMg439svs1Gc0gvITGCIPPG3OXmsmS_WMAtc,20809 +transformers/models/gemma/tokenization_gemma.py,sha256=AcVuuIvQS7kCoS03rX8VkC86S_ywQYKPUGq4ouFXdUY,14229 +transformers/models/gemma/tokenization_gemma_fast.py,sha256=iEJm0bejSYb1DmmXbb6UuRZaeGX0SLG1uCx5v625hTI,8097 +transformers/models/gemma2/__init__.py,sha256=H0jWJX-AcGRTjdzkGJagKnjB6GnpqVUG4ODFhMF9OWM,993 +transformers/models/gemma2/__pycache__/__init__.cpython-310.pyc,, +transformers/models/gemma2/__pycache__/configuration_gemma2.cpython-310.pyc,, +transformers/models/gemma2/__pycache__/modeling_gemma2.cpython-310.pyc,, +transformers/models/gemma2/__pycache__/modular_gemma2.cpython-310.pyc,, +transformers/models/gemma2/configuration_gemma2.py,sha256=QfNcLy2BpJAkBadWHmWPzh4AKW1bMHVOQMsizN8lUgs,9602 +transformers/models/gemma2/modeling_gemma2.py,sha256=LFb_IgKELeMdLqs77WWZttD2T6z_EquT2FQ_V71GmLA,25440 +transformers/models/gemma2/modular_gemma2.py,sha256=lV0G2E1ciXujKy6AxQ253Cgn95ehxvLMZBvt5OT2SI8,24906 +transformers/models/gemma3/__init__.py,sha256=yDt-ADg8e57SlRlpfsC7KzQCeYYgUrTz9ZO5VC5v_W4,1121 +transformers/models/gemma3/__pycache__/__init__.cpython-310.pyc,, +transformers/models/gemma3/__pycache__/configuration_gemma3.cpython-310.pyc,, +transformers/models/gemma3/__pycache__/image_processing_gemma3.cpython-310.pyc,, +transformers/models/gemma3/__pycache__/image_processing_gemma3_fast.cpython-310.pyc,, +transformers/models/gemma3/__pycache__/modeling_gemma3.cpython-310.pyc,, +transformers/models/gemma3/__pycache__/modular_gemma3.cpython-310.pyc,, +transformers/models/gemma3/__pycache__/processing_gemma3.cpython-310.pyc,, +transformers/models/gemma3/configuration_gemma3.py,sha256=Dk2pyAJiIgKoqqY_xJCcGSor3eAHj0JQ_9U7SneSGdk,17851 +transformers/models/gemma3/image_processing_gemma3.py,sha256=u1Fo2LBwEIT5Nw_eisuM8cXg87ycrQxIruQdNkfGvhk,20140 +transformers/models/gemma3/image_processing_gemma3_fast.py,sha256=Ta3HqteIYjCou7olRU1rgZ8cqbcsiC5x1HExDnhkJxI,10951 +transformers/models/gemma3/modeling_gemma3.py,sha256=uSAT0FWDgbdrD3TSswiQzTqqnapYomnXoStaXFqOnrc,59213 +transformers/models/gemma3/modular_gemma3.py,sha256=fUsLZ-usLy5osh7wF4KH_MACrffT2XjxW-7ivqKUvPo,55391 +transformers/models/gemma3/processing_gemma3.py,sha256=-b3OzlSoSsGFXHyng8144ioPuhqVEmXS9yLvQpxEuTE,7818 +transformers/models/gemma3n/__init__.py,sha256=ZSrv5oSiULGXY7Vszb--vaJh1l7FBe1lrZD_3LX6cj4,1079 +transformers/models/gemma3n/__pycache__/__init__.cpython-310.pyc,, +transformers/models/gemma3n/__pycache__/configuration_gemma3n.cpython-310.pyc,, +transformers/models/gemma3n/__pycache__/feature_extraction_gemma3n.cpython-310.pyc,, +transformers/models/gemma3n/__pycache__/modeling_gemma3n.cpython-310.pyc,, +transformers/models/gemma3n/__pycache__/modular_gemma3n.cpython-310.pyc,, +transformers/models/gemma3n/__pycache__/processing_gemma3n.cpython-310.pyc,, +transformers/models/gemma3n/configuration_gemma3n.py,sha256=2EcZp94aPITiRM7R4IXJ2UbVl3k-hatbzq5w8TUIABo,36427 +transformers/models/gemma3n/feature_extraction_gemma3n.py,sha256=2S4N0Qn8EvNfqIv-TvMyq5D30f8GzeURmjdDlIKQS8w,15130 +transformers/models/gemma3n/modeling_gemma3n.py,sha256=8WBUcM3Hpfrj_IyLwlOS-DYvfUF4RDk1knEh7sqokvU,112595 +transformers/models/gemma3n/modular_gemma3n.py,sha256=tMejAt4kJcE1jUP7zWijYBn1-ccDlUfGlddBkNEPAQU,130599 +transformers/models/gemma3n/processing_gemma3n.py,sha256=XjOAcZxamgS5ahNXUy1DNe5qspn6zO0Z1zbsnONn0wI,7064 +transformers/models/git/__init__.py,sha256=jY1iLd7UMOmcCfrKgzoUJawLa0DQ55wHN26L09YSwhc,1021 +transformers/models/git/__pycache__/__init__.cpython-310.pyc,, +transformers/models/git/__pycache__/configuration_git.cpython-310.pyc,, +transformers/models/git/__pycache__/modeling_git.cpython-310.pyc,, +transformers/models/git/__pycache__/processing_git.cpython-310.pyc,, +transformers/models/git/configuration_git.py,sha256=SNcI2qHfnAuwDcYWfiP8Sb_TQXPtosHlw1vDY8bEl04,10447 +transformers/models/git/modeling_git.py,sha256=shLXwnA0DhnKnwyN4-3i6W-DN5DxZjhqVle3ZUJx77c,62276 +transformers/models/git/processing_git.py,sha256=PRKMd0E7yqdnPt2wJKxIGWm8H0PmetZCbLpBKXbe6V0,1586 +transformers/models/glm/__init__.py,sha256=fIafw6FAflbbeG_nEM_VPJyMJHnu_NbWHTHjECIAvIs,987 +transformers/models/glm/__pycache__/__init__.cpython-310.pyc,, +transformers/models/glm/__pycache__/configuration_glm.cpython-310.pyc,, +transformers/models/glm/__pycache__/modeling_glm.cpython-310.pyc,, +transformers/models/glm/__pycache__/modular_glm.cpython-310.pyc,, +transformers/models/glm/configuration_glm.py,sha256=0i7hGoGPrP308WOqZ2ZbGCw2-06GRiDvxAv_m2Fd-Fg,7535 +transformers/models/glm/modeling_glm.py,sha256=PcmhFjouRkRc3H6RMJ9_ehnjeINdNj4l-IwOM91bI-I,21384 +transformers/models/glm/modular_glm.py,sha256=YtrteOxgDeA1J9QcLdOc6v17tSUIHW596Zvus6kDPEk,4063 +transformers/models/glm4/__init__.py,sha256=okqViVxR-MUlkyIdKmSwrDKA7u8pGG49OIKtW9X1hvU,989 +transformers/models/glm4/__pycache__/__init__.cpython-310.pyc,, +transformers/models/glm4/__pycache__/configuration_glm4.cpython-310.pyc,, +transformers/models/glm4/__pycache__/modeling_glm4.cpython-310.pyc,, +transformers/models/glm4/__pycache__/modular_glm4.cpython-310.pyc,, +transformers/models/glm4/configuration_glm4.py,sha256=lFRWkK1kw_GDnhi0w0BViKnQ9FBpRp0uMEyjLxNW7dY,7551 +transformers/models/glm4/modeling_glm4.py,sha256=o39KNNchsad68SMulHdYSv9C_K3w-L0d514ZPVqafvo,22267 +transformers/models/glm4/modular_glm4.py,sha256=pch-cNrRSb-uoWzp6zKypU-un2Rf8yvzTophNck8yGA,5369 +transformers/models/glm4_moe/__init__.py,sha256=dfmB1kPUzq5-xfXh3zFtfGdSJu7CDDbfL401u_EayjM,997 +transformers/models/glm4_moe/__pycache__/__init__.cpython-310.pyc,, +transformers/models/glm4_moe/__pycache__/configuration_glm4_moe.cpython-310.pyc,, +transformers/models/glm4_moe/__pycache__/modeling_glm4_moe.cpython-310.pyc,, +transformers/models/glm4_moe/__pycache__/modular_glm4_moe.cpython-310.pyc,, +transformers/models/glm4_moe/configuration_glm4_moe.py,sha256=uhNU910obiitL0_IAnbO_STy7uuIBY_uugscT0caAJE,13422 +transformers/models/glm4_moe/modeling_glm4_moe.py,sha256=aont2BgLfv72td8H3cnUp01zpcUutEXH6GY0_coOtCo,26946 +transformers/models/glm4_moe/modular_glm4_moe.py,sha256=r-tPmAgMGc9TBtllyiKgLxIfI3O1ND0glaPTkdZgNPc,15685 +transformers/models/glm4v/__init__.py,sha256=czqsAA98MYCyclV5YncS0xt0pnQcYUZc7jFgxZUEKmQ,1027 +transformers/models/glm4v/__pycache__/__init__.cpython-310.pyc,, +transformers/models/glm4v/__pycache__/configuration_glm4v.cpython-310.pyc,, +transformers/models/glm4v/__pycache__/image_processing_glm4v.cpython-310.pyc,, +transformers/models/glm4v/__pycache__/image_processing_glm4v_fast.cpython-310.pyc,, +transformers/models/glm4v/__pycache__/modeling_glm4v.cpython-310.pyc,, +transformers/models/glm4v/__pycache__/modular_glm4v.cpython-310.pyc,, +transformers/models/glm4v/__pycache__/processing_glm4v.cpython-310.pyc,, +transformers/models/glm4v/__pycache__/video_processing_glm4v.cpython-310.pyc,, +transformers/models/glm4v/configuration_glm4v.py,sha256=adgac_qGRsUa3-cesp28ffYERnw4_x6x10NTedhmH0s,17605 +transformers/models/glm4v/image_processing_glm4v.py,sha256=cRsxk6J3Vv1WaSHhlqEfsxZI0iUPkQp2Tt9EOzz01R0,24294 +transformers/models/glm4v/image_processing_glm4v_fast.py,sha256=zpNlTEBkartx0XJdMR0o1uuDjPbXB_sjQUK0QuZ3nT4,7701 +transformers/models/glm4v/modeling_glm4v.py,sha256=SOzmwT97HMRSCstcYG2EgAsVavcZ7QwKgkjo72gBwz8,75609 +transformers/models/glm4v/modular_glm4v.py,sha256=bgn1HI5srx1mzSVhDpczs-5YVH0Bacnk_qNmaDPAC5o,80422 +transformers/models/glm4v/processing_glm4v.py,sha256=F7paRqTx8NHcsZ8aWELbtfcWiFgkwBtKl9nrFmtzDa8,15328 +transformers/models/glm4v/video_processing_glm4v.py,sha256=6-I82f2FMwDo9FnJcWRkPxEJDnSFnYs1hp1zUpEykWs,10146 +transformers/models/glm4v_moe/__init__.py,sha256=4MuhU3oMjO5wL4YHEEhn0uU4qIsXz17DJPMs_xqMyHA,999 +transformers/models/glm4v_moe/__pycache__/__init__.cpython-310.pyc,, +transformers/models/glm4v_moe/__pycache__/configuration_glm4v_moe.cpython-310.pyc,, +transformers/models/glm4v_moe/__pycache__/modeling_glm4v_moe.cpython-310.pyc,, +transformers/models/glm4v_moe/__pycache__/modular_glm4v_moe.cpython-310.pyc,, +transformers/models/glm4v_moe/configuration_glm4v_moe.py,sha256=CQJRarut0RCNVDoJXaBlyAPIzqZh1_DdVI4gOjkansc,19575 +transformers/models/glm4v_moe/modeling_glm4v_moe.py,sha256=f_PrRzv0AReddd2K2bge86C5xd9u-6jb0B1-KI8_FrI,81355 +transformers/models/glm4v_moe/modular_glm4v_moe.py,sha256=r1FUSTZQkuJt80hvTWMkeYLPXZJHz5l67WtkJmVevs0,21332 +transformers/models/glpn/__init__.py,sha256=YYoaugUj0un_FnfusrkzFfT_UtvUJEjMDaRDS8IcYAE,1073 +transformers/models/glpn/__pycache__/__init__.cpython-310.pyc,, +transformers/models/glpn/__pycache__/configuration_glpn.cpython-310.pyc,, +transformers/models/glpn/__pycache__/feature_extraction_glpn.cpython-310.pyc,, +transformers/models/glpn/__pycache__/image_processing_glpn.cpython-310.pyc,, +transformers/models/glpn/__pycache__/modeling_glpn.cpython-310.pyc,, +transformers/models/glpn/configuration_glpn.py,sha256=psEiatDZRceSeLe24Ch77es0_ugLEjzmzP81QthIXcI,5998 +transformers/models/glpn/feature_extraction_glpn.py,sha256=QC_SmxGijm3KyJtR_hEGG16TXPHpvv5pa5_0YrQLq0c,1284 +transformers/models/glpn/image_processing_glpn.py,sha256=R6BgbOIi9TBODIRK6Js_t6vC87JLbeWqLY-PS8N1fNI,12758 +transformers/models/glpn/modeling_glpn.py,sha256=I6mg9d1P9BL09ecueLTpGzh7UHJfWdXR_A528UtjM1M,29056 +transformers/models/got_ocr2/__init__.py,sha256=LBVZP8CBfOxaD9NLC2ZbZpLloHLIX7uDyM8m1-W2m6g,1138 +transformers/models/got_ocr2/__pycache__/__init__.cpython-310.pyc,, +transformers/models/got_ocr2/__pycache__/configuration_got_ocr2.cpython-310.pyc,, +transformers/models/got_ocr2/__pycache__/image_processing_got_ocr2.cpython-310.pyc,, +transformers/models/got_ocr2/__pycache__/image_processing_got_ocr2_fast.cpython-310.pyc,, +transformers/models/got_ocr2/__pycache__/modeling_got_ocr2.cpython-310.pyc,, +transformers/models/got_ocr2/__pycache__/modular_got_ocr2.cpython-310.pyc,, +transformers/models/got_ocr2/__pycache__/processing_got_ocr2.cpython-310.pyc,, +transformers/models/got_ocr2/configuration_got_ocr2.py,sha256=n9a3boLFZN7HMCyFSrZhcZH-ceWk3_Ut9XJz1F_cEkI,9455 +transformers/models/got_ocr2/image_processing_got_ocr2.py,sha256=jixsvD8RfdHEtaoKtsfb4OQp-q8e4czkFrkwGQ61Xyk,25643 +transformers/models/got_ocr2/image_processing_got_ocr2_fast.py,sha256=vrmkfS9BNdkc4ZORCuMN9o9pNLFo5glRh4xGafduhvQ,10554 +transformers/models/got_ocr2/modeling_got_ocr2.py,sha256=OOVplKRGFyT4D48xPBW4HML3zFhaie_yF6AsKRAwDtA,36315 +transformers/models/got_ocr2/modular_got_ocr2.py,sha256=gjSNDrIoDUvCCKweW9--AAZHut2cuUvwgMLYwNbluhs,19508 +transformers/models/got_ocr2/processing_got_ocr2.py,sha256=UYg8mmvwvtU45wypto_azkPfxcPe-0uKBjwZabxxBB0,12579 +transformers/models/gpt2/__init__.py,sha256=NRi7aYu3gezDPsiXiiG6dgSpCMHSIvFpC3iI0w-JMA0,1182 +transformers/models/gpt2/__pycache__/__init__.cpython-310.pyc,, +transformers/models/gpt2/__pycache__/configuration_gpt2.cpython-310.pyc,, +transformers/models/gpt2/__pycache__/modeling_flax_gpt2.cpython-310.pyc,, +transformers/models/gpt2/__pycache__/modeling_gpt2.cpython-310.pyc,, +transformers/models/gpt2/__pycache__/modeling_tf_gpt2.cpython-310.pyc,, +transformers/models/gpt2/__pycache__/tokenization_gpt2.cpython-310.pyc,, +transformers/models/gpt2/__pycache__/tokenization_gpt2_fast.cpython-310.pyc,, +transformers/models/gpt2/__pycache__/tokenization_gpt2_tf.cpython-310.pyc,, +transformers/models/gpt2/configuration_gpt2.py,sha256=oWdrBVDmgPqQJ2orzzELbqkbE_hvKk9Op4pwtEXN3hY,12059 +transformers/models/gpt2/modeling_flax_gpt2.py,sha256=IBlHlVFZw-O_BArk5pqMJWk-wsTVNLQLef6MGNDlCRk,32109 +transformers/models/gpt2/modeling_gpt2.py,sha256=tZElPXrK3TljW79vn2_QqX1r5dfPkBB04tlZ_z5HjoA,74275 +transformers/models/gpt2/modeling_tf_gpt2.py,sha256=xWPpjaGyLDObGq4-3zwsb5gQVpuXUZ2ayTZRI4wLB2c,56440 +transformers/models/gpt2/tokenization_gpt2.py,sha256=3bLgxaap-6YpehzZI-DR5s0FU8PM0riJjsmaiqKH_3Q,13154 +transformers/models/gpt2/tokenization_gpt2_fast.py,sha256=pKJ2PVaSzWUSIjXWoLp0r8LiIupthk_8oaTNhD-PhAw,5274 +transformers/models/gpt2/tokenization_gpt2_tf.py,sha256=Ma7Z4lkXDyeJeTw5-wwkJwttvIdUnGptzmnhmvzCX7A,4071 +transformers/models/gpt_bigcode/__init__.py,sha256=KQNb7PO57eZpP345wSbe_C3iL-N4VPscw1GY2mv81uE,1003 +transformers/models/gpt_bigcode/__pycache__/__init__.cpython-310.pyc,, +transformers/models/gpt_bigcode/__pycache__/configuration_gpt_bigcode.cpython-310.pyc,, +transformers/models/gpt_bigcode/__pycache__/modeling_gpt_bigcode.cpython-310.pyc,, +transformers/models/gpt_bigcode/configuration_gpt_bigcode.py,sha256=5pL1meyCVQZXvco9WsIFNvDhEdtpAEVgTOg-xg2cWrw,6375 +transformers/models/gpt_bigcode/modeling_gpt_bigcode.py,sha256=kuYuy6KU1bimkJBHiMsVJCjlH6xBj_SdmdHp6_6Syrs,40349 +transformers/models/gpt_neo/__init__.py,sha256=b25qxianvucgAd3OxuI00Rr5324o-CRes0zrcEIOCZI,1036 +transformers/models/gpt_neo/__pycache__/__init__.cpython-310.pyc,, +transformers/models/gpt_neo/__pycache__/configuration_gpt_neo.cpython-310.pyc,, +transformers/models/gpt_neo/__pycache__/modeling_flax_gpt_neo.cpython-310.pyc,, +transformers/models/gpt_neo/__pycache__/modeling_gpt_neo.cpython-310.pyc,, +transformers/models/gpt_neo/configuration_gpt_neo.py,sha256=zRidKD8M7zf-YbaDWUYw8ScjQesO5BSI6d7YoHnyjwU,11907 +transformers/models/gpt_neo/modeling_flax_gpt_neo.py,sha256=fD4XijeKuru5evmV7NcPQAtgvQha8H-oEyJm2uNlE4Y,28175 +transformers/models/gpt_neo/modeling_gpt_neo.py,sha256=rK-z9sg_2FL7nPhaMszUSr4ty4ycoiHW2v5u8jx5XNE,51567 +transformers/models/gpt_neox/__init__.py,sha256=6CL92CuqBTIDJ-YH_doFwb-oRylAffw7pwxedv3a-40,1043 +transformers/models/gpt_neox/__pycache__/__init__.cpython-310.pyc,, +transformers/models/gpt_neox/__pycache__/configuration_gpt_neox.cpython-310.pyc,, +transformers/models/gpt_neox/__pycache__/modeling_gpt_neox.cpython-310.pyc,, +transformers/models/gpt_neox/__pycache__/modular_gpt_neox.cpython-310.pyc,, +transformers/models/gpt_neox/__pycache__/tokenization_gpt_neox_fast.cpython-310.pyc,, +transformers/models/gpt_neox/configuration_gpt_neox.py,sha256=-z9ztrlOAgyorPeZKTp-fOvSVWOoZuqhiAfq0VTBuNM,10982 +transformers/models/gpt_neox/modeling_gpt_neox.py,sha256=30D1UPcvZX6IrEQwM9zgzxRAMZd0XkmpRou5zUG_J0g,34514 +transformers/models/gpt_neox/modular_gpt_neox.py,sha256=bwULKb0ZJKZPpA0k3UMZ_5ptMkIBADqZFbDU7JPzIw0,28636 +transformers/models/gpt_neox/tokenization_gpt_neox_fast.py,sha256=iivrluP4OTkQlBQjqz1kpn0NhIrarqPafDbCgHGc80o,8986 +transformers/models/gpt_neox_japanese/__init__.py,sha256=z4kbUmZSjE-Hs9ba8ul3Yncc9ZJy7ePufbwwRlfqWqw,1065 +transformers/models/gpt_neox_japanese/__pycache__/__init__.cpython-310.pyc,, +transformers/models/gpt_neox_japanese/__pycache__/configuration_gpt_neox_japanese.cpython-310.pyc,, +transformers/models/gpt_neox_japanese/__pycache__/modeling_gpt_neox_japanese.cpython-310.pyc,, +transformers/models/gpt_neox_japanese/__pycache__/tokenization_gpt_neox_japanese.cpython-310.pyc,, +transformers/models/gpt_neox_japanese/configuration_gpt_neox_japanese.py,sha256=Mae05uoCqq3q20e-da1CoCxCegR_Ng6q5R-1hrcacVI,9122 +transformers/models/gpt_neox_japanese/modeling_gpt_neox_japanese.py,sha256=hOPyMK07om85VSpo7jGnuBwfSB-eKZZooRFzJZKGNgc,32605 +transformers/models/gpt_neox_japanese/tokenization_gpt_neox_japanese.py,sha256=kskjAVPuG8Xb6zm2dwFgi-0BeGz_KZOJUJD-ZdKOQ2o,16938 +transformers/models/gpt_oss/__init__.py,sha256=a3dnVKgP6RwbuxBJW3kodYKj8oVF5Y6pLJixMthP1yA,995 +transformers/models/gpt_oss/__pycache__/__init__.cpython-310.pyc,, +transformers/models/gpt_oss/__pycache__/configuration_gpt_oss.cpython-310.pyc,, +transformers/models/gpt_oss/__pycache__/modeling_gpt_oss.cpython-310.pyc,, +transformers/models/gpt_oss/__pycache__/modular_gpt_oss.cpython-310.pyc,, +transformers/models/gpt_oss/configuration_gpt_oss.py,sha256=K-rizkmb7ItV8Z-tzUOIT7DZ47StGkd0osj8XygKOhk,4881 +transformers/models/gpt_oss/modeling_gpt_oss.py,sha256=uLvO_BapoEmBpn_n5-9AT4YPTs65I9nDdBJCxmnWHdI,32530 +transformers/models/gpt_oss/modular_gpt_oss.py,sha256=r_hRDkuFxu08H6uYh-X25JeRC-i8nFWFm2cqZU7U8II,20470 +transformers/models/gpt_sw3/__init__.py,sha256=-g6WlJ6EhhrJKCCsPf78cgvGD7oWvfeW9GBGBpW6wcM,958 +transformers/models/gpt_sw3/__pycache__/__init__.cpython-310.pyc,, +transformers/models/gpt_sw3/__pycache__/tokenization_gpt_sw3.cpython-310.pyc,, +transformers/models/gpt_sw3/tokenization_gpt_sw3.py,sha256=6z6Yd9eLqFgEKb_Z4ow8kFOuhZVTD0ejrboc9aktNIc,12565 +transformers/models/gptj/__init__.py,sha256=rgFDJcsxcq1ytl7BTZthr7sSmaxqggSbvrIseycmE-s,1063 +transformers/models/gptj/__pycache__/__init__.cpython-310.pyc,, +transformers/models/gptj/__pycache__/configuration_gptj.cpython-310.pyc,, +transformers/models/gptj/__pycache__/modeling_flax_gptj.cpython-310.pyc,, +transformers/models/gptj/__pycache__/modeling_gptj.cpython-310.pyc,, +transformers/models/gptj/__pycache__/modeling_tf_gptj.cpython-310.pyc,, +transformers/models/gptj/configuration_gptj.py,sha256=wJU2oz2LYuleopQEzA2soQauHwae7JinCxJi_hGz2YM,8860 +transformers/models/gptj/modeling_flax_gptj.py,sha256=zod4lQZEi_H8sy4zbtmb2Gn5mEiFSmPZjYbffpztX_8,28620 +transformers/models/gptj/modeling_gptj.py,sha256=L-pUs5-6lk4sdRa71m4g7_MpbAb-VAQF0AIN2OW4Jks,53912 +transformers/models/gptj/modeling_tf_gptj.py,sha256=RHLHR65JSAH9IC-Rp3ZUVZKFkJfahNJZzlVwW--HMxE,47831 +transformers/models/granite/__init__.py,sha256=cDxmZNuphkDCs2U8W5C95Vhu577kdZHKHUWWaQ3vk5U,1015 +transformers/models/granite/__pycache__/__init__.cpython-310.pyc,, +transformers/models/granite/__pycache__/configuration_granite.cpython-310.pyc,, +transformers/models/granite/__pycache__/modeling_granite.cpython-310.pyc,, +transformers/models/granite/__pycache__/modular_granite.cpython-310.pyc,, +transformers/models/granite/configuration_granite.py,sha256=U1CQ2gvTYGx753UX0t5IOfcLllikDU7Jupj7NlOX3Dk,9348 +transformers/models/granite/modeling_granite.py,sha256=kgZ41QO8tnlbpGwblXnCiq0gij_wtz5-AnVOfNnjwZw,24990 +transformers/models/granite/modular_granite.py,sha256=7Rcs_VTOj0bQO9HAQDuVUVxyk7UXOo71MtUmZTxorOU,11884 +transformers/models/granite_speech/__init__.py,sha256=xD_zbTTnBiaB6EEG4yinaWd-yza1waa01GNKVhsGL1M,1107 +transformers/models/granite_speech/__pycache__/__init__.cpython-310.pyc,, +transformers/models/granite_speech/__pycache__/configuration_granite_speech.cpython-310.pyc,, +transformers/models/granite_speech/__pycache__/feature_extraction_granite_speech.cpython-310.pyc,, +transformers/models/granite_speech/__pycache__/modeling_granite_speech.cpython-310.pyc,, +transformers/models/granite_speech/__pycache__/processing_granite_speech.cpython-310.pyc,, +transformers/models/granite_speech/configuration_granite_speech.py,sha256=EYXvGbPHGa6rTZa4FeeR-kg98I_gW9JTiI1MT8XyZwg,8565 +transformers/models/granite_speech/feature_extraction_granite_speech.py,sha256=CrQoQlWFlY3B3vM0mDdZCFM8t_xp21vjGieZl65gErE,7395 +transformers/models/granite_speech/modeling_granite_speech.py,sha256=_6EwamwcEOr9vWVPENvllVH0YZLyUzmRMbPLQ0I8Lv0,26533 +transformers/models/granite_speech/processing_granite_speech.py,sha256=pMT_ByZPVZC3xBkCfFoW8CSLkY-uMdNW_4ufPbTxFP0,3922 +transformers/models/granitemoe/__init__.py,sha256=e4KKtNT7YFkYkPBfcS0VyhpT_1vF0JkR2qdYKPqRUcE,1001 +transformers/models/granitemoe/__pycache__/__init__.cpython-310.pyc,, +transformers/models/granitemoe/__pycache__/configuration_granitemoe.cpython-310.pyc,, +transformers/models/granitemoe/__pycache__/modeling_granitemoe.cpython-310.pyc,, +transformers/models/granitemoe/configuration_granitemoe.py,sha256=bZMMl3W8IDz9VfbN98Y39K12K7C2Mm0D1-41vngyxfU,9513 +transformers/models/granitemoe/modeling_granitemoe.py,sha256=a9iCnweQKgYRaND2AHdLlfypOCqp4QKmwd7zf5W2FO0,44603 +transformers/models/granitemoehybrid/__init__.py,sha256=yiZusdNxb3DK3MNKdwcVNM2bFfeASr76tKQwQwmSJ68,1043 +transformers/models/granitemoehybrid/__pycache__/__init__.cpython-310.pyc,, +transformers/models/granitemoehybrid/__pycache__/configuration_granitemoehybrid.cpython-310.pyc,, +transformers/models/granitemoehybrid/__pycache__/modeling_granitemoehybrid.cpython-310.pyc,, +transformers/models/granitemoehybrid/__pycache__/modular_granitemoehybrid.cpython-310.pyc,, +transformers/models/granitemoehybrid/configuration_granitemoehybrid.py,sha256=PcoscInOieZzcB828m2LxvXuTtyp7zzw3QDS349nzr8,12558 +transformers/models/granitemoehybrid/modeling_granitemoehybrid.py,sha256=laEl9ygG9n1WwlD5x0WEskWqwOEx38umE8YE8TtZLwY,84423 +transformers/models/granitemoehybrid/modular_granitemoehybrid.py,sha256=YnzzsBOwhDHlvy4350oMR4RGa_ihOgYatE0y3mir1f4,16941 +transformers/models/granitemoeshared/__init__.py,sha256=vmY98tLts1c_yvkLn9X-xk6CFtXIKskzYvFGMqQAskc,1013 +transformers/models/granitemoeshared/__pycache__/__init__.cpython-310.pyc,, +transformers/models/granitemoeshared/__pycache__/configuration_granitemoeshared.cpython-310.pyc,, +transformers/models/granitemoeshared/__pycache__/modeling_granitemoeshared.cpython-310.pyc,, +transformers/models/granitemoeshared/__pycache__/modular_granitemoeshared.cpython-310.pyc,, +transformers/models/granitemoeshared/configuration_granitemoeshared.py,sha256=lYbrzbYRHxR5Xf8xb_7GVlw3NAkWGaMe_cVq8H6jIH8,9942 +transformers/models/granitemoeshared/modeling_granitemoeshared.py,sha256=Yqc7_xAcGBilqx1yvn1bdTnmE9UNS3unUjfeF1biNII,46993 +transformers/models/granitemoeshared/modular_granitemoeshared.py,sha256=fU0NhBHvcP_bfBvGRnvpIXXtE655p3UZPgGrEP-c9Q4,8093 +transformers/models/grounding_dino/__init__.py,sha256=nTxZfZioCpS8hj_L80qZQkgPviMZrTxkz14B9sQQJjk,1161 +transformers/models/grounding_dino/__pycache__/__init__.cpython-310.pyc,, +transformers/models/grounding_dino/__pycache__/configuration_grounding_dino.cpython-310.pyc,, +transformers/models/grounding_dino/__pycache__/image_processing_grounding_dino.cpython-310.pyc,, +transformers/models/grounding_dino/__pycache__/image_processing_grounding_dino_fast.cpython-310.pyc,, +transformers/models/grounding_dino/__pycache__/modeling_grounding_dino.cpython-310.pyc,, +transformers/models/grounding_dino/__pycache__/modular_grounding_dino.cpython-310.pyc,, +transformers/models/grounding_dino/__pycache__/processing_grounding_dino.cpython-310.pyc,, +transformers/models/grounding_dino/configuration_grounding_dino.py,sha256=v0jseFxOwfmdOxes3oL75e-GmIdjIEngnJdMNPCES_Q,15246 +transformers/models/grounding_dino/image_processing_grounding_dino.py,sha256=O_FW33pwjUIoIhrbtflKqLoBYGrJDbpPWvq7eObgxZw,72276 +transformers/models/grounding_dino/image_processing_grounding_dino_fast.py,sha256=WNYZo9mYCczm-ABP-6CRUR0s9YrApspPH5O5GFiuCZY,33714 +transformers/models/grounding_dino/modeling_grounding_dino.py,sha256=upjrUqy9in42urWB_Q-bCS_tNXnjfNbmnFXqFTUEsuA,130668 +transformers/models/grounding_dino/modular_grounding_dino.py,sha256=jxpSF3pY9G5a8apSE60KxLFOksSQ1HejZqsO_L_6M6k,5261 +transformers/models/grounding_dino/processing_grounding_dino.py,sha256=ByBNG7-vmk-Ok2fHswOIPxmFDb6pyY9FMCNxxPAAojk,12065 +transformers/models/groupvit/__init__.py,sha256=vrJ-tBa1XOd1CloHhXKMCIlggMxOS4M7jCcqlLQxMo4,1037 +transformers/models/groupvit/__pycache__/__init__.cpython-310.pyc,, +transformers/models/groupvit/__pycache__/configuration_groupvit.cpython-310.pyc,, +transformers/models/groupvit/__pycache__/modeling_groupvit.cpython-310.pyc,, +transformers/models/groupvit/__pycache__/modeling_tf_groupvit.cpython-310.pyc,, +transformers/models/groupvit/configuration_groupvit.py,sha256=HPn7QhjrbFnZvchmlNN_ONEW4Y3pDBlmHuMMk7OgrVs,18672 +transformers/models/groupvit/modeling_groupvit.py,sha256=ts2BpfArCnK63M8izxOw6aeqhRlW7UWgEEIulXUkHw0,60051 +transformers/models/groupvit/modeling_tf_groupvit.py,sha256=EUsn4bjKnjVuOlloMYViw5ZPWRrt7SkPcjcUi9Di6Nw,90065 +transformers/models/helium/__init__.py,sha256=b1Senw5Mr129rzZSd1sW6-Ies2kIAUHfplpzgGeuTFE,993 +transformers/models/helium/__pycache__/__init__.cpython-310.pyc,, +transformers/models/helium/__pycache__/configuration_helium.cpython-310.pyc,, +transformers/models/helium/__pycache__/modeling_helium.cpython-310.pyc,, +transformers/models/helium/__pycache__/modular_helium.cpython-310.pyc,, +transformers/models/helium/configuration_helium.py,sha256=kctXqQTceihfsqRx0vImc_urU3Ii5hyp-cUGy8TUT0E,7380 +transformers/models/helium/modeling_helium.py,sha256=MjwqU7OjiUxdrTWOxauZKIXi0zuRMRqcvdEY-6cUPLs,20908 +transformers/models/helium/modular_helium.py,sha256=Vy5H8kuVy5fJM0JQb0fEGJ4l6VrAbn9FfPiw2B0S9JA,5471 +transformers/models/herbert/__init__.py,sha256=3i5hlRANc-OFP86y2qzb_OCWVjJQ9XQswiglh5KbU7Y,1003 +transformers/models/herbert/__pycache__/__init__.cpython-310.pyc,, +transformers/models/herbert/__pycache__/tokenization_herbert.cpython-310.pyc,, +transformers/models/herbert/__pycache__/tokenization_herbert_fast.cpython-310.pyc,, +transformers/models/herbert/tokenization_herbert.py,sha256=-1q4wQyllXCSydUXL0DO8Nm9OqmAcIGdNhCvgb6rxeg,23808 +transformers/models/herbert/tokenization_herbert_fast.py,sha256=S_47DZCpq7SK9d21QKf8jF5FZvVkRFERzD_iRV2IMg0,4919 +transformers/models/hgnet_v2/__init__.py,sha256=sBFNC0RNpS-oEnOiwtxy2SkUPAJgmI5uXXq2WjSHRd8,999 +transformers/models/hgnet_v2/__pycache__/__init__.cpython-310.pyc,, +transformers/models/hgnet_v2/__pycache__/configuration_hgnet_v2.cpython-310.pyc,, +transformers/models/hgnet_v2/__pycache__/modeling_hgnet_v2.cpython-310.pyc,, +transformers/models/hgnet_v2/__pycache__/modular_hgnet_v2.cpython-310.pyc,, +transformers/models/hgnet_v2/configuration_hgnet_v2.py,sha256=Gr8N48fXLivF_jKgpm62-1mTvqo5QDfw-h0JceCXbjY,8823 +transformers/models/hgnet_v2/modeling_hgnet_v2.py,sha256=GPTGNKK5yPUV8AjQ-kAX-ynFK3uiSPaJdYo7fe-bfTA,17918 +transformers/models/hgnet_v2/modular_hgnet_v2.py,sha256=jC6wqnU6DZsLxf9UHsLgfUyN-3OXdVeUp5BXNAF9zbw,24358 +transformers/models/hiera/__init__.py,sha256=b1kwKtpZVISJZ5Pri421uvH2v3IoRQ6XXHzxFOPHN-g,991 +transformers/models/hiera/__pycache__/__init__.cpython-310.pyc,, +transformers/models/hiera/__pycache__/configuration_hiera.cpython-310.pyc,, +transformers/models/hiera/__pycache__/modeling_hiera.cpython-310.pyc,, +transformers/models/hiera/configuration_hiera.py,sha256=QbF2S73pDapMC0_AoQVnPZTqWgs0tXvWWgSAvjNxEFE,9319 +transformers/models/hiera/modeling_hiera.py,sha256=SgBXF5NmvHHNLxlNV5Cihi-FzuUl0jjtHTbjgA9RvVk,61836 +transformers/models/hubert/__init__.py,sha256=ai560JtgkksShocy0zcDejelkRZnK4IZPVKaTHCOxPQ,1031 +transformers/models/hubert/__pycache__/__init__.cpython-310.pyc,, +transformers/models/hubert/__pycache__/configuration_hubert.cpython-310.pyc,, +transformers/models/hubert/__pycache__/modeling_hubert.cpython-310.pyc,, +transformers/models/hubert/__pycache__/modeling_tf_hubert.cpython-310.pyc,, +transformers/models/hubert/__pycache__/modular_hubert.cpython-310.pyc,, +transformers/models/hubert/configuration_hubert.py,sha256=XFh70tUL-ITYtn-RMt-lZl_Ej2qQ24vJLZZyBYF3PwA,14962 +transformers/models/hubert/modeling_hubert.py,sha256=D0WYbO8xGUHMYntJ7ZNyObytNc4DosDc_A3E73ByYgM,54623 +transformers/models/hubert/modeling_tf_hubert.py,sha256=kNlAqimDX_Tkw4mcrTNa1hByvAZEnsQFs_RhdGW7txg,70566 +transformers/models/hubert/modular_hubert.py,sha256=fhDox-l7V90dmRmOWoJ0bGwhkJZHNmEzAlPLP5BdD-E,11949 +transformers/models/hunyuan_v1_dense/__init__.py,sha256=FZn7rOtjmLA5vwEeH99QcgAveRMl1LbHQOyBKhywPWY,442 +transformers/models/hunyuan_v1_dense/__pycache__/__init__.cpython-310.pyc,, +transformers/models/hunyuan_v1_dense/__pycache__/configuration_hunyuan_v1_dense.cpython-310.pyc,, +transformers/models/hunyuan_v1_dense/__pycache__/modeling_hunyuan_v1_dense.cpython-310.pyc,, +transformers/models/hunyuan_v1_dense/__pycache__/modular_hunyuan_v1_dense.cpython-310.pyc,, +transformers/models/hunyuan_v1_dense/configuration_hunyuan_v1_dense.py,sha256=xfweGl6-PcYJ996VgbIznOxQn4BwrFvQ9hxrtJpNLWM,9921 +transformers/models/hunyuan_v1_dense/modeling_hunyuan_v1_dense.py,sha256=N_fysxaPCJoUwCU6KHiBMxHz_uuSqgTDp9kgnas7uh0,22510 +transformers/models/hunyuan_v1_dense/modular_hunyuan_v1_dense.py,sha256=vgjtOAYjljo1drPQgDFbdu62I2-CSpjqrPiFNkvosGE,7610 +transformers/models/hunyuan_v1_moe/__init__.py,sha256=SrgoAMLn102HlTL_4fm7CwAFeFSlAWDvFGZcUU2S_9o,396 +transformers/models/hunyuan_v1_moe/__pycache__/__init__.cpython-310.pyc,, +transformers/models/hunyuan_v1_moe/__pycache__/configuration_hunyuan_v1_moe.cpython-310.pyc,, +transformers/models/hunyuan_v1_moe/__pycache__/modeling_hunyuan_v1_moe.cpython-310.pyc,, +transformers/models/hunyuan_v1_moe/__pycache__/modular_hunyuan_v1_moe.cpython-310.pyc,, +transformers/models/hunyuan_v1_moe/configuration_hunyuan_v1_moe.py,sha256=IQAJOMECCtBk224-2O9W3enCksVQluXIAW7Gu0sX6JQ,10694 +transformers/models/hunyuan_v1_moe/modeling_hunyuan_v1_moe.py,sha256=mqyxxOSENaEhDPJJuxRV7oRHeLP4RIzCVw_WRVVEKwI,26382 +transformers/models/hunyuan_v1_moe/modular_hunyuan_v1_moe.py,sha256=uggfllo2UDdPc9dFeRzTGeowk_w9wAYULnbOvWgpFe8,11943 +transformers/models/ibert/__init__.py,sha256=UMTcE54y6O9UNF8l9VV2rrTlJSAHooxeNeHNzPSgr_E,991 +transformers/models/ibert/__pycache__/__init__.cpython-310.pyc,, +transformers/models/ibert/__pycache__/configuration_ibert.cpython-310.pyc,, +transformers/models/ibert/__pycache__/modeling_ibert.cpython-310.pyc,, +transformers/models/ibert/__pycache__/quant_modules.cpython-310.pyc,, +transformers/models/ibert/configuration_ibert.py,sha256=nLRgpOzXz8rNprkGfnz5LVuPKWbYnQfkAubJp9sJYyE,7120 +transformers/models/ibert/modeling_ibert.py,sha256=YsclA8wKcXrtT1FoAMDFKiKzX5H5z63U2gizYnHxMGM,51496 +transformers/models/ibert/quant_modules.py,sha256=IRq4JOfDn8BBDan2zDy8Fa70bMJ8Wa2gorNDeNVB6uc,30076 +transformers/models/idefics/__init__.py,sha256=zc4m1Vd6-Szs7Urt0Ry6eUScpza8iD-QPG4cq4xX34g,1116 +transformers/models/idefics/__pycache__/__init__.cpython-310.pyc,, +transformers/models/idefics/__pycache__/configuration_idefics.cpython-310.pyc,, +transformers/models/idefics/__pycache__/image_processing_idefics.cpython-310.pyc,, +transformers/models/idefics/__pycache__/modeling_idefics.cpython-310.pyc,, +transformers/models/idefics/__pycache__/modeling_tf_idefics.cpython-310.pyc,, +transformers/models/idefics/__pycache__/perceiver.cpython-310.pyc,, +transformers/models/idefics/__pycache__/perceiver_tf.cpython-310.pyc,, +transformers/models/idefics/__pycache__/processing_idefics.cpython-310.pyc,, +transformers/models/idefics/__pycache__/vision.cpython-310.pyc,, +transformers/models/idefics/__pycache__/vision_tf.cpython-310.pyc,, +transformers/models/idefics/configuration_idefics.py,sha256=4j7sAul74adsu3fXPiq34FePCqJJaafCg2dmHU9h_GU,15304 +transformers/models/idefics/image_processing_idefics.py,sha256=2UEHQpVQJQZZPoXrwfrhktyiMn-6dfk6PJj51z0R5Eo,9275 +transformers/models/idefics/modeling_idefics.py,sha256=G0RwkaUIUNbxB28pD09aO3HrgOZSycPpMz4g9cOkq-Y,58083 +transformers/models/idefics/modeling_tf_idefics.py,sha256=zEU3dTNxi-2GEeBmDznquODfD__z89bfbB1DfxCByUc,79225 +transformers/models/idefics/perceiver.py,sha256=MkJ34X4dgVNJddcn8wUWyDf0rTioVl4WG3dP5GLXR0Q,9426 +transformers/models/idefics/perceiver_tf.py,sha256=XGRP3FaYcbHbxQa9_NoaLkipFfy9tiymgfx2w1GBT6E,9999 +transformers/models/idefics/processing_idefics.py,sha256=dCqIMvu9voJJ7V4MoblAPCG-yWv8pUPPW2MCZSQXusI,22853 +transformers/models/idefics/vision.py,sha256=oD7jZ2mG07Vv9BboEQmd0IdXR5_Q2uJIQcR5oRhj7I8,21333 +transformers/models/idefics/vision_tf.py,sha256=op9JJArkQWMFNG5_7JoAsXPSWQOyQWmXHiztp8LxCm0,26014 +transformers/models/idefics2/__init__.py,sha256=YmU2OQi-BTXESv52a4jtTwWC2ingparNU4-rXVCPWzQ,1131 +transformers/models/idefics2/__pycache__/__init__.cpython-310.pyc,, +transformers/models/idefics2/__pycache__/configuration_idefics2.cpython-310.pyc,, +transformers/models/idefics2/__pycache__/image_processing_idefics2.cpython-310.pyc,, +transformers/models/idefics2/__pycache__/image_processing_idefics2_fast.cpython-310.pyc,, +transformers/models/idefics2/__pycache__/modeling_idefics2.cpython-310.pyc,, +transformers/models/idefics2/__pycache__/processing_idefics2.cpython-310.pyc,, +transformers/models/idefics2/configuration_idefics2.py,sha256=TUpFg-9WZ_ISWYfKXlVXT3Z5oTh0gxQ4BY-4fbHcRf0,12223 +transformers/models/idefics2/image_processing_idefics2.py,sha256=VY_xZAxXs9pC5jSprzmuPTLEjl5UknWJV34S8I-uRMw,26799 +transformers/models/idefics2/image_processing_idefics2_fast.py,sha256=dr7JFBogQZylKaYHcaVYnzvuJ4m1jm9kHYPEQo6L6_Y,12013 +transformers/models/idefics2/modeling_idefics2.py,sha256=gu5iCM5tf_47F_vX3M8oGAgeZDa1QUqke6d94unENm8,52929 +transformers/models/idefics2/processing_idefics2.py,sha256=8GQM4QkauSzB9zbzAvW01FcTvV6CP9jacVEy7A6vGBs,11805 +transformers/models/idefics3/__init__.py,sha256=zLsOtUFi074lvfGbwZEMVSvV08TZgoq0DVhJJagYoRo,1131 +transformers/models/idefics3/__pycache__/__init__.cpython-310.pyc,, +transformers/models/idefics3/__pycache__/configuration_idefics3.cpython-310.pyc,, +transformers/models/idefics3/__pycache__/image_processing_idefics3.cpython-310.pyc,, +transformers/models/idefics3/__pycache__/image_processing_idefics3_fast.cpython-310.pyc,, +transformers/models/idefics3/__pycache__/modeling_idefics3.cpython-310.pyc,, +transformers/models/idefics3/__pycache__/processing_idefics3.cpython-310.pyc,, +transformers/models/idefics3/configuration_idefics3.py,sha256=fQYZ0Eo-q7InVjNFat2RjL9RZQmR-9nAIlK9v_XNkZE,8566 +transformers/models/idefics3/image_processing_idefics3.py,sha256=pXbyNYn-0BZ8OAfWk8okyFXgPocjMv_DFDwciMxaIto,44086 +transformers/models/idefics3/image_processing_idefics3_fast.py,sha256=r87nPbM_owfX-fyc1e1dpm-zEDCd7lvgpqiymOLnTV0,23465 +transformers/models/idefics3/modeling_idefics3.py,sha256=rQn2A99-xl1Tzovk8yr3dMSpi8Dkiy3Uz4nePot2mHA,43996 +transformers/models/idefics3/processing_idefics3.py,sha256=3Hq7gNzpiXJh8Qi5B1iiyEPzji93WTfGF7OmbPJgaMU,18766 +transformers/models/ijepa/__init__.py,sha256=O0_Jqpy8kmorYC-x0QsoMYSHdqQt3E1j-UZGLQ9aCv0,991 +transformers/models/ijepa/__pycache__/__init__.cpython-310.pyc,, +transformers/models/ijepa/__pycache__/configuration_ijepa.cpython-310.pyc,, +transformers/models/ijepa/__pycache__/modeling_ijepa.cpython-310.pyc,, +transformers/models/ijepa/__pycache__/modular_ijepa.cpython-310.pyc,, +transformers/models/ijepa/configuration_ijepa.py,sha256=8lO360USWRUnrnBXO2SeiZN0ozKHJNb2K2D0_vCKeX8,5445 +transformers/models/ijepa/modeling_ijepa.py,sha256=XZkLqvCBigXntyBuRMiwxkqyNxdCJ4mXs5FAmwB-qjA,23527 +transformers/models/ijepa/modular_ijepa.py,sha256=YA9MMAQN4WEMJBuwI8vN46HS8cz9PjyMRRryx_iT7WI,7621 +transformers/models/imagegpt/__init__.py,sha256=NIc1rPRLS3e06c-xUW5Vk80IOSPK2L1ZrY_PJrHn1GY,1139 +transformers/models/imagegpt/__pycache__/__init__.cpython-310.pyc,, +transformers/models/imagegpt/__pycache__/configuration_imagegpt.cpython-310.pyc,, +transformers/models/imagegpt/__pycache__/feature_extraction_imagegpt.cpython-310.pyc,, +transformers/models/imagegpt/__pycache__/image_processing_imagegpt.cpython-310.pyc,, +transformers/models/imagegpt/__pycache__/image_processing_imagegpt_fast.cpython-310.pyc,, +transformers/models/imagegpt/__pycache__/modeling_imagegpt.cpython-310.pyc,, +transformers/models/imagegpt/configuration_imagegpt.py,sha256=bp6I42shNZUoPmwpTOWEiyUH3-UQkDzK7AkSLgsMZCo,8799 +transformers/models/imagegpt/feature_extraction_imagegpt.py,sha256=sU7HaHR9bGhzHYLuRDnvcHRCnxlJHkfTVItQYn7ZS5E,1316 +transformers/models/imagegpt/image_processing_imagegpt.py,sha256=SSJt-s0ozRQZzvwp4D94v59meSoirNEr1MOPveajDV4,15044 +transformers/models/imagegpt/image_processing_imagegpt_fast.py,sha256=eeOL5tDmrD2CdVsvMcWVgOacORGkQtdIOCpz-Q_uhps,8185 +transformers/models/imagegpt/modeling_imagegpt.py,sha256=mS8TemFYe-PZln9te9xkx-23NpNGB6QGaD52Ah9U6mM,45860 +transformers/models/informer/__init__.py,sha256=L-BwVQfdq5ve06VJJ-OnTh-m_YqSMNcpDQ1z6sbDtNI,997 +transformers/models/informer/__pycache__/__init__.cpython-310.pyc,, +transformers/models/informer/__pycache__/configuration_informer.cpython-310.pyc,, +transformers/models/informer/__pycache__/modeling_informer.cpython-310.pyc,, +transformers/models/informer/__pycache__/modular_informer.cpython-310.pyc,, +transformers/models/informer/configuration_informer.py,sha256=w_Si5k5ZakGLXANemPDBY7RX_j3rfcLQr_NawdVURcA,12488 +transformers/models/informer/modeling_informer.py,sha256=bdoc9Sl4FKfLt5U0jlBM3yPzGmAHcm67JKEblvgIsvQ,107068 +transformers/models/informer/modular_informer.py,sha256=mKtONM7e6FcHRYXaBZMhfPaSAKfl8qewSGHKK6jVkug,48642 +transformers/models/instructblip/__init__.py,sha256=gI7F0N1dRSYdZtTumtuoPcIJcuBI8PO4DEOQS4_nWuc,1048 +transformers/models/instructblip/__pycache__/__init__.cpython-310.pyc,, +transformers/models/instructblip/__pycache__/configuration_instructblip.cpython-310.pyc,, +transformers/models/instructblip/__pycache__/modeling_instructblip.cpython-310.pyc,, +transformers/models/instructblip/__pycache__/processing_instructblip.cpython-310.pyc,, +transformers/models/instructblip/configuration_instructblip.py,sha256=_EYzBIHXuM6DThV5EfpJVuglsL7OCu-axvN0u_Yfk2M,15823 +transformers/models/instructblip/modeling_instructblip.py,sha256=RCS8iMZBI3ZbTyuljRDZlzrAY_-en2jHDD0yAPeV2Mo,67652 +transformers/models/instructblip/processing_instructblip.py,sha256=vXnmWgHSp-zqIRtBe-Uc7VAlAKwPkykcG529dGqeeeQ,8846 +transformers/models/instructblipvideo/__init__.py,sha256=sgK7MEwrqKB6mQyEvhxcgOQc_OAtMDc9tAZqKF0sxfM,1171 +transformers/models/instructblipvideo/__pycache__/__init__.cpython-310.pyc,, +transformers/models/instructblipvideo/__pycache__/configuration_instructblipvideo.cpython-310.pyc,, +transformers/models/instructblipvideo/__pycache__/image_processing_instructblipvideo.cpython-310.pyc,, +transformers/models/instructblipvideo/__pycache__/modeling_instructblipvideo.cpython-310.pyc,, +transformers/models/instructblipvideo/__pycache__/modular_instructblipvideo.cpython-310.pyc,, +transformers/models/instructblipvideo/__pycache__/processing_instructblipvideo.cpython-310.pyc,, +transformers/models/instructblipvideo/__pycache__/video_processing_instructblipvideo.cpython-310.pyc,, +transformers/models/instructblipvideo/configuration_instructblipvideo.py,sha256=RWJu0fOE-UcvZRLYLCZB0MHmXOUReRv3YhN9lsliQ68,16931 +transformers/models/instructblipvideo/image_processing_instructblipvideo.py,sha256=APQbLGFQG66fFLgDXa9pLPCRTnebrcNdd7M6gEN8tm4,17072 +transformers/models/instructblipvideo/modeling_instructblipvideo.py,sha256=psqlloauG-ZRsqHhP6FjWwv5jT3jnoJAK9MnkNiCVLY,71031 +transformers/models/instructblipvideo/modular_instructblipvideo.py,sha256=TNW5LRAom0_qSh4I-rRRgOGu45GWeu2i9Zw5LGIf1qQ,27290 +transformers/models/instructblipvideo/processing_instructblipvideo.py,sha256=tcQHwvKN5MZNnx5WZ5J4LIJOdT6MTnwCPlG7PoZ_yB4,9771 +transformers/models/instructblipvideo/video_processing_instructblipvideo.py,sha256=BlJwdsPnik5G6gHdDOi9WFmEF6LcaWCJ-HGZ88WLv8k,4069 +transformers/models/internvl/__init__.py,sha256=tNXeZ8TIWlY70CelRiihyPOudKQtRBZp-c9WqglJ8ss,1081 +transformers/models/internvl/__pycache__/__init__.cpython-310.pyc,, +transformers/models/internvl/__pycache__/configuration_internvl.cpython-310.pyc,, +transformers/models/internvl/__pycache__/modeling_internvl.cpython-310.pyc,, +transformers/models/internvl/__pycache__/modular_internvl.cpython-310.pyc,, +transformers/models/internvl/__pycache__/processing_internvl.cpython-310.pyc,, +transformers/models/internvl/__pycache__/video_processing_internvl.cpython-310.pyc,, +transformers/models/internvl/configuration_internvl.py,sha256=pHPwAbDBs-a2mCoadTGA-86y8w9io-9rn-mhFSMFe20,10622 +transformers/models/internvl/modeling_internvl.py,sha256=yByI-LFolfe3vpdhFnk_e1d4K3My8zKPMZ7B3iMKJ8M,39332 +transformers/models/internvl/modular_internvl.py,sha256=VBEh6V5CXxZzoZxm6GrhQIlxRz_YJCvZ3IF3aU2CG2I,26002 +transformers/models/internvl/processing_internvl.py,sha256=nFaEAvLfcx6uAUpGUeh8Z60j4nnex98Q7hTvO6DJZFY,15988 +transformers/models/internvl/video_processing_internvl.py,sha256=0NdBoCThQVnypaAOEsTm_p7r3gw-ni8aRXGoXnUQdlk,6599 +transformers/models/jamba/__init__.py,sha256=zN7Rmr--d5GCEJzMA7gxIz-BYFydPN3cyuif85YU0Fk,991 +transformers/models/jamba/__pycache__/__init__.cpython-310.pyc,, +transformers/models/jamba/__pycache__/configuration_jamba.cpython-310.pyc,, +transformers/models/jamba/__pycache__/modeling_jamba.cpython-310.pyc,, +transformers/models/jamba/configuration_jamba.py,sha256=_tAnWFB7DxGv4MF3dq2rSmzJ3Ys-8jamkEtN67mTPWQ,11745 +transformers/models/jamba/modeling_jamba.py,sha256=5Zeb2E0Hblb06w0E1c661KQgXOhNfmMakwSJxdGcSIM,68890 +transformers/models/janus/__init__.py,sha256=rTnJnHMmmoPxIVasip4sdS5aZ1wvetOtZUobIMYMHX4,1132 +transformers/models/janus/__pycache__/__init__.cpython-310.pyc,, +transformers/models/janus/__pycache__/configuration_janus.cpython-310.pyc,, +transformers/models/janus/__pycache__/image_processing_janus.cpython-310.pyc,, +transformers/models/janus/__pycache__/image_processing_janus_fast.cpython-310.pyc,, +transformers/models/janus/__pycache__/modeling_janus.cpython-310.pyc,, +transformers/models/janus/__pycache__/modular_janus.cpython-310.pyc,, +transformers/models/janus/__pycache__/processing_janus.cpython-310.pyc,, +transformers/models/janus/configuration_janus.py,sha256=7fL58_kFc-hWwhpq-6N_BJG82194A3uHz9QEmRK0A14,14908 +transformers/models/janus/image_processing_janus.py,sha256=MCGyQXhTCKI8i7azs9FyFF20sTG4CNvDvGKzSSM_i8g,26231 +transformers/models/janus/image_processing_janus_fast.py,sha256=QBOCNYnicSmhm55GqydGT7V2iRLvQLnThVnHjlPkcr0,9104 +transformers/models/janus/modeling_janus.py,sha256=GMJewKE6i7xtCe2pAgiCp52Hzyx0Pg9JWplp2MqojEc,61915 +transformers/models/janus/modular_janus.py,sha256=rEVkWNIlW8IsMeZyQRQlU0WzBrfIIjg0y96BRblS2ZI,77517 +transformers/models/janus/processing_janus.py,sha256=5JEIn8wvEtNh7DZJoWTXqAQrTXp2Ngb05DinunZNn7o,7538 +transformers/models/jetmoe/__init__.py,sha256=zhqtP2ZDCCl3Fp3VBnnuaA044Ztbh7fsUKogAKABOt0,993 +transformers/models/jetmoe/__pycache__/__init__.cpython-310.pyc,, +transformers/models/jetmoe/__pycache__/configuration_jetmoe.cpython-310.pyc,, +transformers/models/jetmoe/__pycache__/modeling_jetmoe.cpython-310.pyc,, +transformers/models/jetmoe/configuration_jetmoe.py,sha256=65oV7AlRZZEsz_4BlbWEf4DvdyqywSjew9KjE3Uzj_U,6851 +transformers/models/jetmoe/modeling_jetmoe.py,sha256=c-7YbteDWnb4QcfdbaxGLME8UR9QwImY9aVXVckFDbU,53752 +transformers/models/kosmos2/__init__.py,sha256=Ow8cLelhxl6fm5XvXzNQtPLt1xjIdVmGUwz5NoVVVto,1033 +transformers/models/kosmos2/__pycache__/__init__.cpython-310.pyc,, +transformers/models/kosmos2/__pycache__/configuration_kosmos2.cpython-310.pyc,, +transformers/models/kosmos2/__pycache__/modeling_kosmos2.cpython-310.pyc,, +transformers/models/kosmos2/__pycache__/processing_kosmos2.cpython-310.pyc,, +transformers/models/kosmos2/configuration_kosmos2.py,sha256=J8MCJ8SzDJ03_8DiSMNiYyU46i0tl6LEc2K_u1dnUY8,11888 +transformers/models/kosmos2/modeling_kosmos2.py,sha256=XzHvet6cnlBwGxYKsSzf6LAYV3g_wtedSCM4PKnZ1wo,82065 +transformers/models/kosmos2/processing_kosmos2.py,sha256=Q5NPmkXRcIltvykzUASwobWc7xOQbbaMh5_hPD48WPQ,30907 +transformers/models/kosmos2_5/__init__.py,sha256=rn3igfupnqkSt_O0QLvLmrTy_fX_N7EIFPdHtr2ud7o,1179 +transformers/models/kosmos2_5/__pycache__/__init__.cpython-310.pyc,, +transformers/models/kosmos2_5/__pycache__/configuration_kosmos2_5.cpython-310.pyc,, +transformers/models/kosmos2_5/__pycache__/image_processing_kosmos2_5.cpython-310.pyc,, +transformers/models/kosmos2_5/__pycache__/image_processing_kosmos2_5_fast.cpython-310.pyc,, +transformers/models/kosmos2_5/__pycache__/modeling_kosmos2_5.cpython-310.pyc,, +transformers/models/kosmos2_5/__pycache__/processing_kosmos2_5.cpython-310.pyc,, +transformers/models/kosmos2_5/configuration_kosmos2_5.py,sha256=KwVBazDcAinxR9TQ2Z6wejbw_E9L2F5Scfk-cFaCm9Y,11654 +transformers/models/kosmos2_5/image_processing_kosmos2_5.py,sha256=6GYOgPTQeLEGgcHX7h9kPq3_XJprwWU6EjSUcIe7Re0,15011 +transformers/models/kosmos2_5/image_processing_kosmos2_5_fast.py,sha256=9IA6EagLo1L0j1vR8vZkgFWjEYhaS4YoeqgBjrnRTRg,12282 +transformers/models/kosmos2_5/modeling_kosmos2_5.py,sha256=Z5z08l1_wn9oHIW4TzD__GsL1-2lwSzrPGWeMhHE9EU,83002 +transformers/models/kosmos2_5/processing_kosmos2_5.py,sha256=oD6PEWiNb-aIjTO-ZQbfM8A9zN1ly5Us5xTfEzdaBEs,6441 +transformers/models/kyutai_speech_to_text/__init__.py,sha256=KxatXD7pSOmwZWzs7nFOXG9Hc2wxaAS3CYwxg54lq9g,1135 +transformers/models/kyutai_speech_to_text/__pycache__/__init__.cpython-310.pyc,, +transformers/models/kyutai_speech_to_text/__pycache__/configuration_kyutai_speech_to_text.cpython-310.pyc,, +transformers/models/kyutai_speech_to_text/__pycache__/feature_extraction_kyutai_speech_to_text.cpython-310.pyc,, +transformers/models/kyutai_speech_to_text/__pycache__/modeling_kyutai_speech_to_text.cpython-310.pyc,, +transformers/models/kyutai_speech_to_text/__pycache__/modular_kyutai_speech_to_text.cpython-310.pyc,, +transformers/models/kyutai_speech_to_text/__pycache__/processing_kyutai_speech_to_text.cpython-310.pyc,, +transformers/models/kyutai_speech_to_text/configuration_kyutai_speech_to_text.py,sha256=eeBUzFfZnDlhcCuhQzaFchNFT_Wq-2-mBxXPJ_lelnI,9030 +transformers/models/kyutai_speech_to_text/feature_extraction_kyutai_speech_to_text.py,sha256=PfGZhywYO9o3sbbO5fLfrJtXLsbhl1CRJmnPeUHbBgw,11808 +transformers/models/kyutai_speech_to_text/modeling_kyutai_speech_to_text.py,sha256=sEy7F1NTLL9QAmuJZ6aZw_Kh9DeDQoI8RayUmyTFkas,64505 +transformers/models/kyutai_speech_to_text/modular_kyutai_speech_to_text.py,sha256=GRCWOSiQY8rd5Sl_mfPdMcscZ8--0i7oJC_1fECdxVk,23366 +transformers/models/kyutai_speech_to_text/processing_kyutai_speech_to_text.py,sha256=EHRvOqyvO1vuQj7AyBAmaQHhgeocHfCWeQNT8KgmFgo,1504 +transformers/models/layoutlm/__init__.py,sha256=Mv-k01_9_SxbADuSx2pWoNGBxgUe4IH15Kcg-vc_0OI,1124 +transformers/models/layoutlm/__pycache__/__init__.cpython-310.pyc,, +transformers/models/layoutlm/__pycache__/configuration_layoutlm.cpython-310.pyc,, +transformers/models/layoutlm/__pycache__/modeling_layoutlm.cpython-310.pyc,, +transformers/models/layoutlm/__pycache__/modeling_tf_layoutlm.cpython-310.pyc,, +transformers/models/layoutlm/__pycache__/tokenization_layoutlm.cpython-310.pyc,, +transformers/models/layoutlm/__pycache__/tokenization_layoutlm_fast.cpython-310.pyc,, +transformers/models/layoutlm/configuration_layoutlm.py,sha256=lJpmBnPMPzNQ07IhYWznczuR_Xra5E7znijzmFuBzmM,8416 +transformers/models/layoutlm/modeling_layoutlm.py,sha256=F3q9we9P-5P4n_8jL3KtonK9RqoVpW-0dWSgzMFEx2M,47591 +transformers/models/layoutlm/modeling_tf_layoutlm.py,sha256=nbnFaMwHF6o4H37KjumFss3PkBG1JvR9bqSaCUgeQO0,73207 +transformers/models/layoutlm/tokenization_layoutlm.py,sha256=xmr9ECm3iKIekmGUFJCh6doTOuto43pZoGRJtOaAsnc,20141 +transformers/models/layoutlm/tokenization_layoutlm_fast.py,sha256=LQl2LTmosc0mhrdir332AMepzHmuwxCDrM8RxYxUrJM,6691 +transformers/models/layoutlmv2/__init__.py,sha256=8f9dWBf1riaQI2KAw-gIrQGNKP4f2uUdJxyRKNVD2lI,1281 +transformers/models/layoutlmv2/__pycache__/__init__.cpython-310.pyc,, +transformers/models/layoutlmv2/__pycache__/configuration_layoutlmv2.cpython-310.pyc,, +transformers/models/layoutlmv2/__pycache__/feature_extraction_layoutlmv2.cpython-310.pyc,, +transformers/models/layoutlmv2/__pycache__/image_processing_layoutlmv2.cpython-310.pyc,, +transformers/models/layoutlmv2/__pycache__/image_processing_layoutlmv2_fast.cpython-310.pyc,, +transformers/models/layoutlmv2/__pycache__/modeling_layoutlmv2.cpython-310.pyc,, +transformers/models/layoutlmv2/__pycache__/processing_layoutlmv2.cpython-310.pyc,, +transformers/models/layoutlmv2/__pycache__/tokenization_layoutlmv2.cpython-310.pyc,, +transformers/models/layoutlmv2/__pycache__/tokenization_layoutlmv2_fast.cpython-310.pyc,, +transformers/models/layoutlmv2/configuration_layoutlmv2.py,sha256=LmhbEBUesm93DINDXZRfWIKrB0Agy3cflhMh7UCMtqY,10914 +transformers/models/layoutlmv2/feature_extraction_layoutlmv2.py,sha256=C-PxmCgb7CMj-nrs7-yOEvGwLcW1okgKjK2OvIsKjHE,1313 +transformers/models/layoutlmv2/image_processing_layoutlmv2.py,sha256=T1A2IEzQR8Du5lqcnpTZ4yDJKqcZfv5rOLwwGC5g5tk,13625 +transformers/models/layoutlmv2/image_processing_layoutlmv2_fast.py,sha256=F9vFWyyPyzWK2Iz6ghmdWRDod4Gl97gzXLEvCsp5VvI,5578 +transformers/models/layoutlmv2/modeling_layoutlmv2.py,sha256=dmMHao3__jjv095y3E94KIZ3RlLKWceISvJ5ERixoa4,61926 +transformers/models/layoutlmv2/processing_layoutlmv2.py,sha256=UGximtXB_J9XJ6_L1Zt9jQGbNLHz-nfhBQ6WaIE3bdg,8511 +transformers/models/layoutlmv2/tokenization_layoutlmv2.py,sha256=NPwb7mXxwLzRHqfDHqcKww8QEXePE8W-25cyJXYpeSg,72137 +transformers/models/layoutlmv2/tokenization_layoutlmv2_fast.py,sha256=kszD7kD1-Zi6tos9t3gSTja-wWCi0k8e3D5uhZjR3ws,37064 +transformers/models/layoutlmv3/__init__.py,sha256=N-Ty2DqEyDqyd5i-k89LMi2qSbojaasZ-ozSTxs1GHo,1323 +transformers/models/layoutlmv3/__pycache__/__init__.cpython-310.pyc,, +transformers/models/layoutlmv3/__pycache__/configuration_layoutlmv3.cpython-310.pyc,, +transformers/models/layoutlmv3/__pycache__/feature_extraction_layoutlmv3.cpython-310.pyc,, +transformers/models/layoutlmv3/__pycache__/image_processing_layoutlmv3.cpython-310.pyc,, +transformers/models/layoutlmv3/__pycache__/image_processing_layoutlmv3_fast.cpython-310.pyc,, +transformers/models/layoutlmv3/__pycache__/modeling_layoutlmv3.cpython-310.pyc,, +transformers/models/layoutlmv3/__pycache__/modeling_tf_layoutlmv3.cpython-310.pyc,, +transformers/models/layoutlmv3/__pycache__/processing_layoutlmv3.cpython-310.pyc,, +transformers/models/layoutlmv3/__pycache__/tokenization_layoutlmv3.cpython-310.pyc,, +transformers/models/layoutlmv3/__pycache__/tokenization_layoutlmv3_fast.cpython-310.pyc,, +transformers/models/layoutlmv3/configuration_layoutlmv3.py,sha256=-FaapM8qkEUrlkfsFAG27v5hPJh-SmkQkXSYb5OiBjU,13288 +transformers/models/layoutlmv3/feature_extraction_layoutlmv3.py,sha256=G2oB86aN-ebGJjw6YMsuEVuSfnIAylsteMWpZR3Gcvs,1313 +transformers/models/layoutlmv3/image_processing_layoutlmv3.py,sha256=dvQJqhk5gb76eDjOqR81Ds2JBAmE9doUXIBH7wADwtQ,18581 +transformers/models/layoutlmv3/image_processing_layoutlmv3_fast.py,sha256=L8SmPIaIQcfKWrqtOaD3aXtsajnJuwIgtKe7PzMY0_s,6165 +transformers/models/layoutlmv3/modeling_layoutlmv3.py,sha256=BrUTHHIbuqu4MXYeqDtekXBwQ-WjLLYSvpdzpBRCJ3c,53566 +transformers/models/layoutlmv3/modeling_tf_layoutlmv3.py,sha256=QMYgY31NUVETlCDaX9WIwSnPZwb5ZfHl8N0JfwVIEJc,76633 +transformers/models/layoutlmv3/processing_layoutlmv3.py,sha256=f4RPc5nM-8SRU02j_v34rm3QnGCKnYkTmxp34eTaEws,8362 +transformers/models/layoutlmv3/tokenization_layoutlmv3.py,sha256=17kZ8YegVDFnv0aUn14xeLWV2LTxQn8cZrgw1OXa6jE,73235 +transformers/models/layoutlmv3/tokenization_layoutlmv3_fast.py,sha256=l7JmjZ3uMA3fRimszuxqpQF5_0AFB-wjXwTwSwj7Rcg,39917 +transformers/models/layoutxlm/__init__.py,sha256=djfI2YGJISwww_XDfyf4kCj3a_HiC6Hld1rlaHRtHPg,1047 +transformers/models/layoutxlm/__pycache__/__init__.cpython-310.pyc,, +transformers/models/layoutxlm/__pycache__/processing_layoutxlm.cpython-310.pyc,, +transformers/models/layoutxlm/__pycache__/tokenization_layoutxlm.cpython-310.pyc,, +transformers/models/layoutxlm/__pycache__/tokenization_layoutxlm_fast.cpython-310.pyc,, +transformers/models/layoutxlm/processing_layoutxlm.py,sha256=E09g63s0vHiFjoqe2kbhlGNNSAG0Y8bd2GKWChimpRs,8442 +transformers/models/layoutxlm/tokenization_layoutxlm.py,sha256=BLbZIliyQIRcXAtExyWN0sIV2ZRf1FqFdsnlKsB-iIo,58329 +transformers/models/layoutxlm/tokenization_layoutxlm_fast.py,sha256=1J_rW1fGdTsQsJRbLfVhbWngXnKecX-xELBtYmu98QA,40471 +transformers/models/led/__init__.py,sha256=KaOht9jIet9WQrPRli8DwD7q5fzTWsffxf7LK-sQuw4,1099 +transformers/models/led/__pycache__/__init__.cpython-310.pyc,, +transformers/models/led/__pycache__/configuration_led.cpython-310.pyc,, +transformers/models/led/__pycache__/modeling_led.cpython-310.pyc,, +transformers/models/led/__pycache__/modeling_tf_led.cpython-310.pyc,, +transformers/models/led/__pycache__/tokenization_led.cpython-310.pyc,, +transformers/models/led/__pycache__/tokenization_led_fast.cpython-310.pyc,, +transformers/models/led/configuration_led.py,sha256=wuLDY2wIywEU_23WuDfcoGW8-bg_X8SmP843xnYFyZQ,7455 +transformers/models/led/modeling_led.py,sha256=7pgIWN-0sJdOfM06jLsGit64R61BeahlkP3MsLm4xIw,125061 +transformers/models/led/modeling_tf_led.py,sha256=WPRKVHYflyt5aYEvIum-rqs2lrEj629KCfHFMBSQeKM,123085 +transformers/models/led/tokenization_led.py,sha256=m7FhNIvAQer9k9t_WqYMGSE3k59yn7L5tIuB3JH7uzE,19843 +transformers/models/led/tokenization_led_fast.py,sha256=yO0G0Q6yGmsPCyEII9t-AnYQeEaJ-HQDbLjfAcGI9Cs,14170 +transformers/models/levit/__init__.py,sha256=acEjEeDtpQ9q3a-hf90z6TZ0js04BtZvbCcn4HGWCyk,1124 +transformers/models/levit/__pycache__/__init__.cpython-310.pyc,, +transformers/models/levit/__pycache__/configuration_levit.cpython-310.pyc,, +transformers/models/levit/__pycache__/feature_extraction_levit.cpython-310.pyc,, +transformers/models/levit/__pycache__/image_processing_levit.cpython-310.pyc,, +transformers/models/levit/__pycache__/image_processing_levit_fast.cpython-310.pyc,, +transformers/models/levit/__pycache__/modeling_levit.cpython-310.pyc,, +transformers/models/levit/configuration_levit.py,sha256=UOtUDcZK6i4kPrtjYgCoWpZsxf7A1BQZeZjCYoXnMek,5772 +transformers/models/levit/feature_extraction_levit.py,sha256=sR1MZBqvbep8KdqX45Sw3V--ZqCe3fePzC1CT9cv4Js,1317 +transformers/models/levit/image_processing_levit.py,sha256=n5z9mpFYTLFgyoIZ0MZ4b_mD8zh3BEA72ohMelsXIKk,16738 +transformers/models/levit/image_processing_levit_fast.py,sha256=ijtU7Idez27Re4fPgVNZ6mW9UqoXL6mgYk4T874IJLY,3733 +transformers/models/levit/modeling_levit.py,sha256=jIk0WOgBkwMUpFhzRlHDtFfS2ynaHWLZWOWGOxipu38,25251 +transformers/models/lfm2/__init__.py,sha256=9fNMRtqveDp18iRtUjNqCu0XELuvwJOmizUyI1h0zHw,989 +transformers/models/lfm2/__pycache__/__init__.cpython-310.pyc,, +transformers/models/lfm2/__pycache__/configuration_lfm2.cpython-310.pyc,, +transformers/models/lfm2/__pycache__/modeling_lfm2.cpython-310.pyc,, +transformers/models/lfm2/__pycache__/modular_lfm2.cpython-310.pyc,, +transformers/models/lfm2/configuration_lfm2.py,sha256=6jJ2kBds8PYg6DyAHBFdpMIcJW7rBv-bkMrM1LLVgII,7831 +transformers/models/lfm2/modeling_lfm2.py,sha256=i7QUrGd6AP6PreFlXGatCvcRGCLWKcu8EsMcLbd5Qh4,32195 +transformers/models/lfm2/modular_lfm2.py,sha256=YoX6B058cwdrf17ozF7M2VMcVe5N14eVFI25KcbVP-E,20988 +transformers/models/lfm2_vl/__init__.py,sha256=qKhv0-rYp9emO4HCSVPOpPCB8hUy62P2v2rYjkBeTAI,1082 +transformers/models/lfm2_vl/__pycache__/__init__.cpython-310.pyc,, +transformers/models/lfm2_vl/__pycache__/configuration_lfm2_vl.cpython-310.pyc,, +transformers/models/lfm2_vl/__pycache__/image_processing_lfm2_vl_fast.cpython-310.pyc,, +transformers/models/lfm2_vl/__pycache__/modeling_lfm2_vl.cpython-310.pyc,, +transformers/models/lfm2_vl/__pycache__/modular_lfm2_vl.cpython-310.pyc,, +transformers/models/lfm2_vl/__pycache__/processing_lfm2_vl.cpython-310.pyc,, +transformers/models/lfm2_vl/configuration_lfm2_vl.py,sha256=0nhn4M3gkICFzmLWdX3kZ6SzUdoXu4eAIkUkIlS3mXo,3846 +transformers/models/lfm2_vl/image_processing_lfm2_vl_fast.py,sha256=xKeZ7ZXgvIisvbPlxvUBCkszN_JsXvO6fQlmtgMNXe8,21323 +transformers/models/lfm2_vl/modeling_lfm2_vl.py,sha256=QP1V4tNhzdCWas74mdUuH-NqB2Vw_kOc_DuqYMxRvj4,20569 +transformers/models/lfm2_vl/modular_lfm2_vl.py,sha256=k6yTLP3bupZgYA5cIqUM5AesGVj-4fogVZHGsXUn-Yc,14130 +transformers/models/lfm2_vl/processing_lfm2_vl.py,sha256=QPexFW1QoQsE07xihNfH1d2iXUCg8RkE5Q9b8rnx8sI,11768 +transformers/models/lightglue/__init__.py,sha256=xdtDUaVLHRf2vWjlv-l2JWlllw6Obz8ZRZeV297Ds1Y,1045 +transformers/models/lightglue/__pycache__/__init__.cpython-310.pyc,, +transformers/models/lightglue/__pycache__/configuration_lightglue.cpython-310.pyc,, +transformers/models/lightglue/__pycache__/image_processing_lightglue.cpython-310.pyc,, +transformers/models/lightglue/__pycache__/modeling_lightglue.cpython-310.pyc,, +transformers/models/lightglue/__pycache__/modular_lightglue.cpython-310.pyc,, +transformers/models/lightglue/configuration_lightglue.py,sha256=jijJsgjlZEZ-MSZARQ1kKUiW_1VU5B-FVlHGtxWX4bc,8135 +transformers/models/lightglue/image_processing_lightglue.py,sha256=x2zCoHpti6yXIZMKhBxs9PQpdOvrERish-saiQh6I34,24864 +transformers/models/lightglue/modeling_lightglue.py,sha256=KqR-586C7yiEVJUnXFM2bZ1X1OJna0uL5wdKWWZYaEM,43590 +transformers/models/lightglue/modular_lightglue.py,sha256=7W4PXheKZc1FUG2Omk2c55WTsBOdTRtWP7yJRGEKxlw,51228 +transformers/models/lilt/__init__.py,sha256=9XEq7kJwN0mKO469mR0mtlRUdljjq7V80gejpqb59K0,989 +transformers/models/lilt/__pycache__/__init__.cpython-310.pyc,, +transformers/models/lilt/__pycache__/configuration_lilt.cpython-310.pyc,, +transformers/models/lilt/__pycache__/modeling_lilt.cpython-310.pyc,, +transformers/models/lilt/configuration_lilt.py,sha256=rPA7P9f9B2f29_Q74Dx93-WXyhK1JT5W67PoSrDOoQc,6737 +transformers/models/lilt/modeling_lilt.py,sha256=lHQ05B0KSgoocU-4ecavt-2kNg2lhnrA3X5eE1LGETU,48235 +transformers/models/llama/__init__.py,sha256=k1HnOc4-BwvgSizE8E0IlrkCh_TVgv1XX8G-xozfgLo,1111 +transformers/models/llama/__pycache__/__init__.cpython-310.pyc,, +transformers/models/llama/__pycache__/configuration_llama.cpython-310.pyc,, +transformers/models/llama/__pycache__/modeling_flax_llama.cpython-310.pyc,, +transformers/models/llama/__pycache__/modeling_llama.cpython-310.pyc,, +transformers/models/llama/__pycache__/tokenization_llama.cpython-310.pyc,, +transformers/models/llama/__pycache__/tokenization_llama_fast.cpython-310.pyc,, +transformers/models/llama/configuration_llama.py,sha256=m-ywRVkzFiivG0ty9E1ooHJlvQyV44PRHUxdpe06QI4,12077 +transformers/models/llama/modeling_flax_llama.py,sha256=3_PSmX_OPr7ENnUScfAyuepDwejN-2qFRj5vmy8y-KM,30675 +transformers/models/llama/modeling_llama.py,sha256=Mb9mCmYyWRNDJLxl2k4VWVHcicXKRkcdIyWpk46FniY,20714 +transformers/models/llama/tokenization_llama.py,sha256=KQOtC9Jzm6vs9ugT--SyHjb_XLOUFZ4MwTNZuU6gUm8,18729 +transformers/models/llama/tokenization_llama_fast.py,sha256=nYK5v4GRDhoLkxhtgEoLqq8koigofPTAuRv8-rSvk8U,10965 +transformers/models/llama4/__init__.py,sha256=YLpUGkKivYWky6rr715H2yMb9fCPr_3AV8OwWd2mrpA,1078 +transformers/models/llama4/__pycache__/__init__.cpython-310.pyc,, +transformers/models/llama4/__pycache__/configuration_llama4.cpython-310.pyc,, +transformers/models/llama4/__pycache__/image_processing_llama4_fast.cpython-310.pyc,, +transformers/models/llama4/__pycache__/modeling_llama4.cpython-310.pyc,, +transformers/models/llama4/__pycache__/processing_llama4.cpython-310.pyc,, +transformers/models/llama4/configuration_llama4.py,sha256=5z4QQiJeuOOhz0qg3mRDsuUoR4rjdQuj7XHJAfinHAg,23277 +transformers/models/llama4/image_processing_llama4_fast.py,sha256=jIRVlT7pR8DgSnc3cgD_IBb3D5O4gz-lCpp2dkt962Y,18006 +transformers/models/llama4/modeling_llama4.py,sha256=_VHS5P4XYGxVmWM-A8104dpt50faWaJWA0EsFT_rm0w,59348 +transformers/models/llama4/processing_llama4.py,sha256=y7ZsQ8JsAYSs_FMzm64a4NpOTLn8L7qnGrRCOzCEhkA,16112 +transformers/models/llava/__init__.py,sha256=h7TDiwhtiqDQbay9v760sbmBGM6yWs3J1tmnIr3PCys,1074 +transformers/models/llava/__pycache__/__init__.cpython-310.pyc,, +transformers/models/llava/__pycache__/configuration_llava.cpython-310.pyc,, +transformers/models/llava/__pycache__/image_processing_llava.cpython-310.pyc,, +transformers/models/llava/__pycache__/image_processing_llava_fast.cpython-310.pyc,, +transformers/models/llava/__pycache__/modeling_llava.cpython-310.pyc,, +transformers/models/llava/__pycache__/processing_llava.cpython-310.pyc,, +transformers/models/llava/configuration_llava.py,sha256=MzKTXjeGMlr-KNFW7L8T4hg0bx-oZ9Yh2bhVtv3QUt4,5760 +transformers/models/llava/image_processing_llava.py,sha256=0SQZJ6fM4oXt1OL_qr-KSb7K0u7MZ1MiZ797eOUpExI,21257 +transformers/models/llava/image_processing_llava_fast.py,sha256=LrKEahtnD1Mx-GHSz-UQP3tlgIaf_b8N7-yRspytvPQ,6751 +transformers/models/llava/modeling_llava.py,sha256=9IPrz21NTWnAp-3SSXERY5bvGQMKoWVh_7FHSyXLoXw,20455 +transformers/models/llava/processing_llava.py,sha256=1Weh6NnTrmJwZT3y_nZTbrn_tmwXLN-FgJUBVipXTig,10038 +transformers/models/llava_next/__init__.py,sha256=gyT3qcEjuxecgCiFoQoz-tf10ShqzfOL8IzPOhpjfto,1141 +transformers/models/llava_next/__pycache__/__init__.cpython-310.pyc,, +transformers/models/llava_next/__pycache__/configuration_llava_next.cpython-310.pyc,, +transformers/models/llava_next/__pycache__/image_processing_llava_next.cpython-310.pyc,, +transformers/models/llava_next/__pycache__/image_processing_llava_next_fast.cpython-310.pyc,, +transformers/models/llava_next/__pycache__/modeling_llava_next.cpython-310.pyc,, +transformers/models/llava_next/__pycache__/processing_llava_next.cpython-310.pyc,, +transformers/models/llava_next/configuration_llava_next.py,sha256=8LvnjmDgKsNRvsrlqZRkN2NQsuHZXkPmEo-H-8PzkUI,6776 +transformers/models/llava_next/image_processing_llava_next.py,sha256=Tl0FEIv-6OqzB82QMSaTWWDCbOL9kS1t2cFky-1WGCM,35823 +transformers/models/llava_next/image_processing_llava_next_fast.py,sha256=Mp8KwvaE7IBm5rfYclF86zx43sOUcA6XK38ecRIM6NM,10701 +transformers/models/llava_next/modeling_llava_next.py,sha256=NwN0k3t4iQgWjTzDyWnQsZq2ObFq44WP3YejNEdje_I,35878 +transformers/models/llava_next/processing_llava_next.py,sha256=p8fbiv9bowT87QGrvatUKo1VNb3nTd5LoI02yK3N_B0,12794 +transformers/models/llava_next_video/__init__.py,sha256=OGiUL7X9x0bzmsnZi0KA6Sl2ycalLQHkTgOpISYu3q8,1113 +transformers/models/llava_next_video/__pycache__/__init__.cpython-310.pyc,, +transformers/models/llava_next_video/__pycache__/configuration_llava_next_video.cpython-310.pyc,, +transformers/models/llava_next_video/__pycache__/image_processing_llava_next_video.cpython-310.pyc,, +transformers/models/llava_next_video/__pycache__/modeling_llava_next_video.cpython-310.pyc,, +transformers/models/llava_next_video/__pycache__/modular_llava_next_video.cpython-310.pyc,, +transformers/models/llava_next_video/__pycache__/processing_llava_next_video.cpython-310.pyc,, +transformers/models/llava_next_video/__pycache__/video_processing_llava_next_video.cpython-310.pyc,, +transformers/models/llava_next_video/configuration_llava_next_video.py,sha256=XG-wMKQFmGwGhbQSE8bivrfVS2RPQgSqmW0PEbZRoCU,8266 +transformers/models/llava_next_video/image_processing_llava_next_video.py,sha256=J6cr5S2SrCPU0fNjXAq3pZ0CEhEtd3-y_VmCgjXwyhk,21316 +transformers/models/llava_next_video/modeling_llava_next_video.py,sha256=PewB3MWGrlT7Mc6DkGXpEAyy1_SQdjSGlLMfEXHSvxk,46224 +transformers/models/llava_next_video/modular_llava_next_video.py,sha256=Nlvy-hLpEFX6IN9wkfyjO1XZGqBeqDfpQsv4mGxeeRs,34656 +transformers/models/llava_next_video/processing_llava_next_video.py,sha256=McOf61VhnBdY6kyy4S2F1i8IVxcRID3roJIsxmyY3j4,15572 +transformers/models/llava_next_video/video_processing_llava_next_video.py,sha256=2YSNAjUMjIEOfoC8Z2kfRaGjitAedlCDj7ILYKZwfKo,1703 +transformers/models/llava_onevision/__init__.py,sha256=Eeg8yGcfdjCxwjSCg_zoXG48JG6gSYH8_aXBcOxQvnA,1218 +transformers/models/llava_onevision/__pycache__/__init__.cpython-310.pyc,, +transformers/models/llava_onevision/__pycache__/configuration_llava_onevision.cpython-310.pyc,, +transformers/models/llava_onevision/__pycache__/image_processing_llava_onevision.cpython-310.pyc,, +transformers/models/llava_onevision/__pycache__/image_processing_llava_onevision_fast.cpython-310.pyc,, +transformers/models/llava_onevision/__pycache__/modeling_llava_onevision.cpython-310.pyc,, +transformers/models/llava_onevision/__pycache__/modular_llava_onevision.cpython-310.pyc,, +transformers/models/llava_onevision/__pycache__/processing_llava_onevision.cpython-310.pyc,, +transformers/models/llava_onevision/__pycache__/video_processing_llava_onevision.cpython-310.pyc,, +transformers/models/llava_onevision/configuration_llava_onevision.py,sha256=eGeC9jBTNHeouYrJ8KP_IUYVLSbjO8ySj0oFNvGIJFA,8061 +transformers/models/llava_onevision/image_processing_llava_onevision.py,sha256=MGSsSMyaZLhsVuuJZ0wFtXluoILgozCPlOmsSk6q4Ug,38350 +transformers/models/llava_onevision/image_processing_llava_onevision_fast.py,sha256=KI5Q0XKB0NoVird15WaWi8237LAzXteEuJMk6_R_HH4,14756 +transformers/models/llava_onevision/modeling_llava_onevision.py,sha256=YzCIX-L5Wbcgk2_3W1LhrqFp0VGhHrKw_zYDC8Cjcfc,45637 +transformers/models/llava_onevision/modular_llava_onevision.py,sha256=JkdjGN4ohsuRajNW9Pe9gzW_BkDSJ_o9rHJvXzBLU-E,34808 +transformers/models/llava_onevision/processing_llava_onevision.py,sha256=M6OkrKryC7wxAfpaidHhNZi0riVVeFzIXVkiE-rFDgo,16862 +transformers/models/llava_onevision/video_processing_llava_onevision.py,sha256=Gupdo_ysxPfM0TAe-qUDEnnd-GsyOLPLnNXdjnVlae4,1713 +transformers/models/longcat_flash/__init__.py,sha256=0AQcD2MU3TfVLepEHTsarPZaT15FYuZRcFS8P5jc9Jg,1040 +transformers/models/longcat_flash/__pycache__/__init__.cpython-310.pyc,, +transformers/models/longcat_flash/__pycache__/configuration_longcat_flash.cpython-310.pyc,, +transformers/models/longcat_flash/__pycache__/modeling_longcat_flash.cpython-310.pyc,, +transformers/models/longcat_flash/__pycache__/modular_longcat_flash.cpython-310.pyc,, +transformers/models/longcat_flash/configuration_longcat_flash.py,sha256=zbQlcUkStgZfm6AI8vOvEL6z_uc5RO2HeCCeS3o22mM,11038 +transformers/models/longcat_flash/modeling_longcat_flash.py,sha256=NEvpwV4rmtgG6RPadSdf8R7Kl2Xt8aQKGRjgJnwAA0Y,29855 +transformers/models/longcat_flash/modular_longcat_flash.py,sha256=zLM9Mjb8v-ZK-zorIwYSAqkMBkMDo2kQYMW2AF2fRxs,15173 +transformers/models/longformer/__init__.py,sha256=vg5ScmyEX2D-xPfnxNNBhdj6-Xj0t3HoPmt709PQjTE,1134 +transformers/models/longformer/__pycache__/__init__.cpython-310.pyc,, +transformers/models/longformer/__pycache__/configuration_longformer.cpython-310.pyc,, +transformers/models/longformer/__pycache__/modeling_longformer.cpython-310.pyc,, +transformers/models/longformer/__pycache__/modeling_tf_longformer.cpython-310.pyc,, +transformers/models/longformer/__pycache__/tokenization_longformer.cpython-310.pyc,, +transformers/models/longformer/__pycache__/tokenization_longformer_fast.cpython-310.pyc,, +transformers/models/longformer/configuration_longformer.py,sha256=2AwcxPAnCJw5CbCdgTXndYBTlJTWi4QzDnilgG_63T0,8867 +transformers/models/longformer/modeling_longformer.py,sha256=GAwna49OZxXBXd9Ufaf5Aj11bzErUk4xZJjTyjz_yUI,108058 +transformers/models/longformer/modeling_tf_longformer.py,sha256=u-n2NW5EPB7UBMyIFWd5Jm_stpO7O9nlV74QHNBs-4E,129534 +transformers/models/longformer/tokenization_longformer.py,sha256=cK8ke6cLfMRWXlXw_8FpjTIzLoaBi3iY7Mgf4brMRu8,16818 +transformers/models/longformer/tokenization_longformer_fast.py,sha256=Gg8zvjr0Mwqi4aHupJZLykCilqE7jeXREXbMo59ziqQ,11230 +transformers/models/longt5/__init__.py,sha256=TzoI1JGkvJIf9NlHDQY8_EUuW-upkQZ23wh_8Urtet0,1033 +transformers/models/longt5/__pycache__/__init__.cpython-310.pyc,, +transformers/models/longt5/__pycache__/configuration_longt5.cpython-310.pyc,, +transformers/models/longt5/__pycache__/modeling_flax_longt5.cpython-310.pyc,, +transformers/models/longt5/__pycache__/modeling_longt5.cpython-310.pyc,, +transformers/models/longt5/configuration_longt5.py,sha256=ktQfrCmI60usRiyk-hcZinOpcs7p94zfOV47l_jQnWc,8116 +transformers/models/longt5/modeling_flax_longt5.py,sha256=lNP-l4MlXq4zGNYlo0gyF3oXvcNCk-9qDLQYkBElGE8,105838 +transformers/models/longt5/modeling_longt5.py,sha256=wX-CS3sX6SOUgQnYs4VmiVUR0X8EGjAR62bzOQeMWow,104896 +transformers/models/luke/__init__.py,sha256=YQL403sV6tk5t8sjvi-4hgvx1rvyThx45l7S4T4xpEE,1026 +transformers/models/luke/__pycache__/__init__.cpython-310.pyc,, +transformers/models/luke/__pycache__/configuration_luke.cpython-310.pyc,, +transformers/models/luke/__pycache__/modeling_luke.cpython-310.pyc,, +transformers/models/luke/__pycache__/tokenization_luke.cpython-310.pyc,, +transformers/models/luke/configuration_luke.py,sha256=q_QLFRDrJfABob9_6-xvSy7ES4VMYKg9A3_gG8DsxAM,6628 +transformers/models/luke/modeling_luke.py,sha256=6BylGCAFPj9-hVCDjHTD7vSegB9aFbuyDEnxG_xdbtk,98940 +transformers/models/luke/tokenization_luke.py,sha256=SHtnsAm-h1VwdHWjMPXQ0leHSCoqVFVdLA2KEJI2RpE,85643 +transformers/models/lxmert/__init__.py,sha256=iUyLmlBuiz_av7H5ghaQB4RNbpw275N7wwdmiiV0PAc,1114 +transformers/models/lxmert/__pycache__/__init__.cpython-310.pyc,, +transformers/models/lxmert/__pycache__/configuration_lxmert.cpython-310.pyc,, +transformers/models/lxmert/__pycache__/modeling_lxmert.cpython-310.pyc,, +transformers/models/lxmert/__pycache__/modeling_tf_lxmert.cpython-310.pyc,, +transformers/models/lxmert/__pycache__/tokenization_lxmert.cpython-310.pyc,, +transformers/models/lxmert/__pycache__/tokenization_lxmert_fast.cpython-310.pyc,, +transformers/models/lxmert/configuration_lxmert.py,sha256=etr-nrYjobgiPW4H9-PTC9VuGgOdR13DRiqifXFkna4,8934 +transformers/models/lxmert/modeling_lxmert.py,sha256=aG5GYE6DL2xFFLOMe_g6t8YSl1ZUSW2kbW8sSArPQns,63580 +transformers/models/lxmert/modeling_tf_lxmert.py,sha256=aGYP4T1uTzZchJkhZZNZXMgACuFe5TFNkHm8jTIX4S4,72722 +transformers/models/lxmert/tokenization_lxmert.py,sha256=He3yKkZAcjAoy0l7rNzc-W3mk_93FAWRB4YX8awnCU4,20165 +transformers/models/lxmert/tokenization_lxmert_fast.py,sha256=5E0lKrkPi1dSrXcZ2BxipbDtMMBVjcwFStrOBVELRv8,6625 +transformers/models/m2m_100/__init__.py,sha256=0uPov299rgQmMwwSyM_m0yGFejP5djgaUY37GkNGnC8,1035 +transformers/models/m2m_100/__pycache__/__init__.cpython-310.pyc,, +transformers/models/m2m_100/__pycache__/configuration_m2m_100.cpython-310.pyc,, +transformers/models/m2m_100/__pycache__/modeling_m2m_100.cpython-310.pyc,, +transformers/models/m2m_100/__pycache__/tokenization_m2m_100.cpython-310.pyc,, +transformers/models/m2m_100/configuration_m2m_100.py,sha256=iwR_eDM_JlooTz08PGdw8zqeFmXNq3_3ttNe1ivQjj0,13454 +transformers/models/m2m_100/modeling_m2m_100.py,sha256=ck-nTnujQ060LYDp0CKgH1HMGPJtt2Oh48W4NJYqWu4,67446 +transformers/models/m2m_100/tokenization_m2m_100.py,sha256=ZWAVadNEoJ9YCCDSe7lEzGIvp9tdBC9RfCELTGR1wHg,16416 +transformers/models/mamba/__init__.py,sha256=4oGJySQbwoALRGVWMEwXBm0A6fhKsr4Raly46a5g1G0,991 +transformers/models/mamba/__pycache__/__init__.cpython-310.pyc,, +transformers/models/mamba/__pycache__/configuration_mamba.cpython-310.pyc,, +transformers/models/mamba/__pycache__/modeling_mamba.cpython-310.pyc,, +transformers/models/mamba/configuration_mamba.py,sha256=krht7Qj-1yfYxdMr3zB9WhBVqUKiINt2o5BvDC8v-XI,7433 +transformers/models/mamba/modeling_mamba.py,sha256=Sl3rHMnCJ1eCasXdo0P1oMO5KMUKxdnHyGDiR7zgbN8,40131 +transformers/models/mamba2/__init__.py,sha256=Ui4j-I2cnPEEszkzRTLSUW42SE4Qg1YTuW6hGeaOFZg,993 +transformers/models/mamba2/__pycache__/__init__.cpython-310.pyc,, +transformers/models/mamba2/__pycache__/configuration_mamba2.cpython-310.pyc,, +transformers/models/mamba2/__pycache__/modeling_mamba2.cpython-310.pyc,, +transformers/models/mamba2/configuration_mamba2.py,sha256=YWJ7Y_-cEiTLv45b5oChKdzHFh61VWFUMdDZhcjNygU,8214 +transformers/models/mamba2/modeling_mamba2.py,sha256=nOrvEkjTXjUxQDA7ejuLl2WSyXoOtjH-y6jcXiSV0Xg,47716 +transformers/models/marian/__init__.py,sha256=Yg8jbvM0Hf6WXua0__v_G-34dvG6zFib5R5e_qHtmYM,1110 +transformers/models/marian/__pycache__/__init__.cpython-310.pyc,, +transformers/models/marian/__pycache__/configuration_marian.cpython-310.pyc,, +transformers/models/marian/__pycache__/modeling_flax_marian.cpython-310.pyc,, +transformers/models/marian/__pycache__/modeling_marian.cpython-310.pyc,, +transformers/models/marian/__pycache__/modeling_tf_marian.cpython-310.pyc,, +transformers/models/marian/__pycache__/tokenization_marian.cpython-310.pyc,, +transformers/models/marian/configuration_marian.py,sha256=2Sv1CzVYYIXvLBnytaLG0T4k-ptoyphVLAJk-zRcsyw,18420 +transformers/models/marian/modeling_flax_marian.py,sha256=qkUUpKC4MPHmESuI0wjGQ95uu0Fs0jIjQMpKU_0-xMM,64429 +transformers/models/marian/modeling_marian.py,sha256=ibG5SSh_Gepa29z4Hz65D3CvFm041Fb1bcrI7NyVZgo,79177 +transformers/models/marian/modeling_tf_marian.py,sha256=5bdZNB0AV82RWOvPMGe86hUelH97WrVQPtqIIxKK4rQ,72668 +transformers/models/marian/tokenization_marian.py,sha256=4Ox1R818g5c4x_pR41JgJfOhAZOaLXTRDgOQPQrOkRU,16868 +transformers/models/markuplm/__init__.py,sha256=PyhrxFsms-oD4SOBO5j3t2mIPLN3PHjKBjTGaUTITMY,1170 +transformers/models/markuplm/__pycache__/__init__.cpython-310.pyc,, +transformers/models/markuplm/__pycache__/configuration_markuplm.cpython-310.pyc,, +transformers/models/markuplm/__pycache__/feature_extraction_markuplm.cpython-310.pyc,, +transformers/models/markuplm/__pycache__/modeling_markuplm.cpython-310.pyc,, +transformers/models/markuplm/__pycache__/processing_markuplm.cpython-310.pyc,, +transformers/models/markuplm/__pycache__/tokenization_markuplm.cpython-310.pyc,, +transformers/models/markuplm/__pycache__/tokenization_markuplm_fast.cpython-310.pyc,, +transformers/models/markuplm/configuration_markuplm.py,sha256=VhCY0oVEMneuTZNQZFjxwkNIsTEWJ5q5W66t__gS52A,7235 +transformers/models/markuplm/feature_extraction_markuplm.py,sha256=WquMM3IybHzSpniaKvRUux-liOst9-l3Z1ZmfDNab80,6443 +transformers/models/markuplm/modeling_markuplm.py,sha256=MvEq-OFaFOLqt6tuJ0ktpBEmto8ZTVVp7FV5K8jtevY,43375 +transformers/models/markuplm/processing_markuplm.py,sha256=UtpKUu8Obib8WGnF124p7hzen62ECfbOxgUhtpLzBWI,5629 +transformers/models/markuplm/tokenization_markuplm.py,sha256=dRfXzjXAgSlHgTnXHMQKNUOF9id4l-NbmvQWdsmOlRg,70151 +transformers/models/markuplm/tokenization_markuplm_fast.py,sha256=G_2BWkPgi0FMRqxFlZhL0ecalVeqx2uQVcpthoLBjQE,43320 +transformers/models/mask2former/__init__.py,sha256=ceWZ-4gEaZxvgdhdvM-K18wZxuovtdS8vXkQIFNlfr4,1104 +transformers/models/mask2former/__pycache__/__init__.cpython-310.pyc,, +transformers/models/mask2former/__pycache__/configuration_mask2former.cpython-310.pyc,, +transformers/models/mask2former/__pycache__/image_processing_mask2former.cpython-310.pyc,, +transformers/models/mask2former/__pycache__/image_processing_mask2former_fast.cpython-310.pyc,, +transformers/models/mask2former/__pycache__/modeling_mask2former.cpython-310.pyc,, +transformers/models/mask2former/__pycache__/modular_mask2former.cpython-310.pyc,, +transformers/models/mask2former/configuration_mask2former.py,sha256=6fJ8GbDInXB2Cly_QbrYx5xU4hNv-T8TV_9glVUiCtM,12588 +transformers/models/mask2former/image_processing_mask2former.py,sha256=6Po2kHXx_fnwAFC_e5zOl2nVA47vSHcrDy-4KLm6rPk,59164 +transformers/models/mask2former/image_processing_mask2former_fast.py,sha256=jmf-uq4oEKweyyB-aJK06Xait9PCw5nXD6L197utbYs,33574 +transformers/models/mask2former/modeling_mask2former.py,sha256=Q1fWIX2-u69gPuwV_WRjpDIINeErK9VukcwU8x4shD4,117039 +transformers/models/mask2former/modular_mask2former.py,sha256=S5ase8l-KaOejnGhY7PSa1qMeyAdqx2buLDHHgces6Y,15725 +transformers/models/maskformer/__init__.py,sha256=DWCF0SA7DGofmzu3y-j05x1NLeuKZHADvyyx4XfJwkw,1242 +transformers/models/maskformer/__pycache__/__init__.cpython-310.pyc,, +transformers/models/maskformer/__pycache__/configuration_maskformer.cpython-310.pyc,, +transformers/models/maskformer/__pycache__/configuration_maskformer_swin.cpython-310.pyc,, +transformers/models/maskformer/__pycache__/feature_extraction_maskformer.cpython-310.pyc,, +transformers/models/maskformer/__pycache__/image_processing_maskformer.cpython-310.pyc,, +transformers/models/maskformer/__pycache__/image_processing_maskformer_fast.cpython-310.pyc,, +transformers/models/maskformer/__pycache__/modeling_maskformer.cpython-310.pyc,, +transformers/models/maskformer/__pycache__/modeling_maskformer_swin.cpython-310.pyc,, +transformers/models/maskformer/configuration_maskformer.py,sha256=KBU5bzrkpaNiYZM8f3JX_EfVybtiSls5CeC5iTiXAW0,10673 +transformers/models/maskformer/configuration_maskformer_swin.py,sha256=-72GuV7OyDeU0wCX7OltUAcMPSpKZqwlqJwdsLWlijE,7253 +transformers/models/maskformer/feature_extraction_maskformer.py,sha256=QYnLeWeCeAJDLO9bK1W8hVhZ8QdUslC9nJK-3qNdaUc,1332 +transformers/models/maskformer/image_processing_maskformer.py,sha256=oH_AziQhua4OGicCdaPVxtPgMwRPqHQnlW5YtKv_xgA,60013 +transformers/models/maskformer/image_processing_maskformer_fast.py,sha256=OO3Cwwzaw-MLlVKtDxcH8s-D7Y-cYEga5CdTLnkazGA,34932 +transformers/models/maskformer/modeling_maskformer.py,sha256=jseYI6tv5QeDlcE0yCxe-P_sQTauzEO_GHWhTKMcioo,84617 +transformers/models/maskformer/modeling_maskformer_swin.py,sha256=1wrGgKy3HiaGPZ9vyIi6B8tGaKx9PVS6gmABmH7mMYc,40579 +transformers/models/mbart/__init__.py,sha256=VefKwprf7OVOTgkXowKV2hT8X3mM369sRJXDY5a49ig,1148 +transformers/models/mbart/__pycache__/__init__.cpython-310.pyc,, +transformers/models/mbart/__pycache__/configuration_mbart.cpython-310.pyc,, +transformers/models/mbart/__pycache__/modeling_flax_mbart.cpython-310.pyc,, +transformers/models/mbart/__pycache__/modeling_mbart.cpython-310.pyc,, +transformers/models/mbart/__pycache__/modeling_tf_mbart.cpython-310.pyc,, +transformers/models/mbart/__pycache__/tokenization_mbart.cpython-310.pyc,, +transformers/models/mbart/__pycache__/tokenization_mbart_fast.cpython-310.pyc,, +transformers/models/mbart/configuration_mbart.py,sha256=aWNWjpmHjvRVH6hw6JccAsXbameD2-fXBxuvd7xTmR8,18252 +transformers/models/mbart/modeling_flax_mbart.py,sha256=zKLyi2BuhINSDYU-WfFy48LSzz9hJBBoR3EZmeBBFRI,75373 +transformers/models/mbart/modeling_mbart.py,sha256=L7W_INSyg85bXlDFIRn9P3Fvl7ivizLJ8M08MxpztPY,88907 +transformers/models/mbart/modeling_tf_mbart.py,sha256=U_LB_z7NNp5ASoQf0HdfEPdPpL_KmeEP-AJ8C60SVHk,74106 +transformers/models/mbart/tokenization_mbart.py,sha256=5Qeg8LmCiYRQA_kgdnsHalP1Nux7VwBYJamfs-E6ERA,14200 +transformers/models/mbart/tokenization_mbart_fast.py,sha256=744tsO1V7FtO_MM_9E0OnGk98UViv9VKHB-g-KK0y-M,10880 +transformers/models/mbart50/__init__.py,sha256=9ukVFi1NqU3OoJcCJ-iKpJUZiu-K0t8yINuJHGltup0,1003 +transformers/models/mbart50/__pycache__/__init__.cpython-310.pyc,, +transformers/models/mbart50/__pycache__/tokenization_mbart50.cpython-310.pyc,, +transformers/models/mbart50/__pycache__/tokenization_mbart50_fast.cpython-310.pyc,, +transformers/models/mbart50/tokenization_mbart50.py,sha256=bHfZAjdxNKAsVruUc-gQ6768ga1qPzgLJwugIrarNgU,16403 +transformers/models/mbart50/tokenization_mbart50_fast.py,sha256=cNhawmrk4KjiiA4LVgsh1oUUAWMJzkZgSePFdHMi1Gc,11479 +transformers/models/megatron_bert/__init__.py,sha256=u1UIYjQlrfHcy81i2FzehRDJpt6KNfNJ4AePQYKgwOU,1007 +transformers/models/megatron_bert/__pycache__/__init__.cpython-310.pyc,, +transformers/models/megatron_bert/__pycache__/configuration_megatron_bert.cpython-310.pyc,, +transformers/models/megatron_bert/__pycache__/modeling_megatron_bert.cpython-310.pyc,, +transformers/models/megatron_bert/configuration_megatron_bert.py,sha256=Z8A_6hWPyBaC_64AHDlvxGB-08uqpGAyHlX12ty1k2s,6517 +transformers/models/megatron_bert/modeling_megatron_bert.py,sha256=z6pNdzh7Wf4_R0buFmpEW6ymBNTFjLigPxFEvEfWAVU,72123 +transformers/models/megatron_gpt2/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +transformers/models/megatron_gpt2/__pycache__/__init__.cpython-310.pyc,, +transformers/models/megatron_gpt2/__pycache__/checkpoint_reshaping_and_interoperability.cpython-310.pyc,, +transformers/models/megatron_gpt2/checkpoint_reshaping_and_interoperability.py,sha256=3Oe0z75_0SQSM4OR-hRtH_w24LmhSV9AgsyzwKA2R9Y,37650 +transformers/models/metaclip_2/__init__.py,sha256=S5n45gZa_DwDJ3PtBbKzcjqDd6uOY4sbsSXR227oFZI,1001 +transformers/models/metaclip_2/__pycache__/__init__.cpython-310.pyc,, +transformers/models/metaclip_2/__pycache__/configuration_metaclip_2.cpython-310.pyc,, +transformers/models/metaclip_2/__pycache__/modeling_metaclip_2.cpython-310.pyc,, +transformers/models/metaclip_2/__pycache__/modular_metaclip_2.cpython-310.pyc,, +transformers/models/metaclip_2/configuration_metaclip_2.py,sha256=k49lWYQ7r8em6hr9ouPgk1B22xRS29lLi10L6W6AlQY,17801 +transformers/models/metaclip_2/modeling_metaclip_2.py,sha256=0iPTq4xJuqqJIsZtpOjp4OQ6SqTVAv9-kRnz9WRxHsU,57677 +transformers/models/metaclip_2/modular_metaclip_2.py,sha256=X7Tf8oAmTqm0SwUA_lWzlEH12rFVVzWw4_qEAc7RAWs,35628 +transformers/models/mgp_str/__init__.py,sha256=Qb3mXPCrWbQ1ksMRYMeXorrva97OOFNr1zoy4YQg-9k,1073 +transformers/models/mgp_str/__pycache__/__init__.cpython-310.pyc,, +transformers/models/mgp_str/__pycache__/configuration_mgp_str.cpython-310.pyc,, +transformers/models/mgp_str/__pycache__/modeling_mgp_str.cpython-310.pyc,, +transformers/models/mgp_str/__pycache__/processing_mgp_str.cpython-310.pyc,, +transformers/models/mgp_str/__pycache__/tokenization_mgp_str.cpython-310.pyc,, +transformers/models/mgp_str/configuration_mgp_str.py,sha256=Pvwj6oBIFPp219NkKV3b4kisp77UzkN2JCCy31z2RZQ,5810 +transformers/models/mgp_str/modeling_mgp_str.py,sha256=J2dpfa0_Xo-hoQm5E7-CLNu0cCSTRfAoRVjI6BQkKl8,18912 +transformers/models/mgp_str/processing_mgp_str.py,sha256=bPRD7T2XRsGhR_mGidVZeToZTxw_u9MnMJqWykLNb3M,9226 +transformers/models/mgp_str/tokenization_mgp_str.py,sha256=VKVCt4TKcIK2yhqPTWgtPdaLz7v1-I2rn6LuoN4OvFw,3793 +transformers/models/mimi/__init__.py,sha256=VXRZ-D8-AyOYcmRGvSxhjwTYQcSNXcCXi5ubks6Qxhk,989 +transformers/models/mimi/__pycache__/__init__.cpython-310.pyc,, +transformers/models/mimi/__pycache__/configuration_mimi.cpython-310.pyc,, +transformers/models/mimi/__pycache__/modeling_mimi.cpython-310.pyc,, +transformers/models/mimi/configuration_mimi.py,sha256=WNqutFlBjEvuNA4zuNJMX6_LA_ldn2EwTjhILJfqEbk,13507 +transformers/models/mimi/modeling_mimi.py,sha256=PaQYxZeDGmEpYRF_xqJrmNpNUc9DtGQyNTT5DyWHrMQ,79714 +transformers/models/minimax/__init__.py,sha256=3Ob5TqJX21OU-wQ5NF6aeyRbTRXRmoGzeaFFqtzkf7c,1028 +transformers/models/minimax/__pycache__/__init__.cpython-310.pyc,, +transformers/models/minimax/__pycache__/configuration_minimax.cpython-310.pyc,, +transformers/models/minimax/__pycache__/modeling_minimax.cpython-310.pyc,, +transformers/models/minimax/__pycache__/modular_minimax.cpython-310.pyc,, +transformers/models/minimax/configuration_minimax.py,sha256=aNAEtvqIgY0x2PC0ZxFF6Rv1-HA4ZrhY0cMXeptYR5A,11833 +transformers/models/minimax/modeling_minimax.py,sha256=MGhU3KXOrWzGVqghDaGazUlgUh8JVePv8_1oYYlmHvE,42043 +transformers/models/minimax/modular_minimax.py,sha256=PESBmdmw3ZxWI1-RKwy4GMvHNqDgG_xEHX_DxL2yxic,27727 +transformers/models/ministral/__init__.py,sha256=618E2UYWKhHRaJQnG5YToNFqqiEPQBnYNlAVyZq889c,1019 +transformers/models/ministral/__pycache__/__init__.cpython-310.pyc,, +transformers/models/ministral/__pycache__/configuration_ministral.cpython-310.pyc,, +transformers/models/ministral/__pycache__/modeling_ministral.cpython-310.pyc,, +transformers/models/ministral/__pycache__/modular_ministral.cpython-310.pyc,, +transformers/models/ministral/configuration_ministral.py,sha256=TviU9iKkveoR8VFyn7B_4qws7jM40VI3hE0ZUsHwg8E,8227 +transformers/models/ministral/modeling_ministral.py,sha256=23BL-INd_iRupMUwBotXahzHWs1schgMQ1ztRADORK0,21592 +transformers/models/ministral/modular_ministral.py,sha256=EUrqAnuijEYx_-1TN1sE5ximyFcppGsCmGYBBuHpbjA,11862 +transformers/models/mistral/__init__.py,sha256=PDX9s8k0BrsBlmNShhdijHKAp6zC3QYBUwgl1Dx9EsM,1095 +transformers/models/mistral/__pycache__/__init__.cpython-310.pyc,, +transformers/models/mistral/__pycache__/configuration_mistral.cpython-310.pyc,, +transformers/models/mistral/__pycache__/modeling_flax_mistral.cpython-310.pyc,, +transformers/models/mistral/__pycache__/modeling_mistral.cpython-310.pyc,, +transformers/models/mistral/__pycache__/modeling_tf_mistral.cpython-310.pyc,, +transformers/models/mistral/__pycache__/modular_mistral.cpython-310.pyc,, +transformers/models/mistral/configuration_mistral.py,sha256=vpsbjAdonF4w2vMU6I1O_GZIOPpcNp9-PEtIV0pHJ4I,8001 +transformers/models/mistral/modeling_flax_mistral.py,sha256=JVQ590d9nxhPZ2FhmsmOE1316MSrKCmapoDRt8EWZYI,31805 +transformers/models/mistral/modeling_mistral.py,sha256=P7tiAjdqH99XFm0ZndTUP4Eiax4GNOyLYdyxrefeFT4,20743 +transformers/models/mistral/modeling_tf_mistral.py,sha256=_n7kgEEYJkaK7EhpDZQ2v8RdjDZLV7ODikhbjGnJQ-4,44357 +transformers/models/mistral/modular_mistral.py,sha256=GJkCU0nvsbKR5A5fOqjkgerz_TgwxZq31rVGcFBcEdU,7657 +transformers/models/mistral3/__init__.py,sha256=ccR4AQqjFkPl8JVYyVmVvbVm618FlOw4cpwT7N-8ZD4,1036 +transformers/models/mistral3/__pycache__/__init__.cpython-310.pyc,, +transformers/models/mistral3/__pycache__/configuration_mistral3.cpython-310.pyc,, +transformers/models/mistral3/__pycache__/modeling_mistral3.cpython-310.pyc,, +transformers/models/mistral3/__pycache__/modular_mistral3.cpython-310.pyc,, +transformers/models/mistral3/configuration_mistral3.py,sha256=__X0uaVt64fl_wrOlXLiMbg7RUMj0Palwyp44-zdAwc,5710 +transformers/models/mistral3/modeling_mistral3.py,sha256=iJuwZmxJdNxuyaB4uJ7Ko7hPB2IJLaCXxbxyH7nuP94,23442 +transformers/models/mistral3/modular_mistral3.py,sha256=GMNBdHR-J0d5fUc1kW4fVXzGTPui00WOoMAaPxodx8w,14388 +transformers/models/mixtral/__init__.py,sha256=_i66uHDx5A0-UBwgR2nwibxSf0ZePqpTa_Qsm0Cg_Bs,1015 +transformers/models/mixtral/__pycache__/__init__.cpython-310.pyc,, +transformers/models/mixtral/__pycache__/configuration_mixtral.cpython-310.pyc,, +transformers/models/mixtral/__pycache__/modeling_mixtral.cpython-310.pyc,, +transformers/models/mixtral/__pycache__/modular_mixtral.cpython-310.pyc,, +transformers/models/mixtral/configuration_mixtral.py,sha256=7OMbg8pfaU0WfYnGIIqq5nDzx98x8NPKi-NOb3oSAdk,9073 +transformers/models/mixtral/modeling_mixtral.py,sha256=JgeNxWLAU42G0O9fuSxSYN6LwfJQx1ZBDCni4uGcBy0,30280 +transformers/models/mixtral/modular_mixtral.py,sha256=cNEtBX6GS1GIn4r1S3kNqy-PM2SebtwYUSEtoFZg71Q,18953 +transformers/models/mlcd/__init__.py,sha256=hLiLB1E0jT7sI3s8TraLb_Z1WOpwS69zac5kyHNfx4E,989 +transformers/models/mlcd/__pycache__/__init__.cpython-310.pyc,, +transformers/models/mlcd/__pycache__/configuration_mlcd.cpython-310.pyc,, +transformers/models/mlcd/__pycache__/modeling_mlcd.cpython-310.pyc,, +transformers/models/mlcd/__pycache__/modular_mlcd.cpython-310.pyc,, +transformers/models/mlcd/configuration_mlcd.py,sha256=8WPScG0ONO9SbjrfdhSZtxIGCR5NNOl21sleN6Q4hQI,5805 +transformers/models/mlcd/modeling_mlcd.py,sha256=1HdAYVTP77B7_ucDw2FFupJzE1IktTRSPXYTp1BFumg,27365 +transformers/models/mlcd/modular_mlcd.py,sha256=oasTUnxnhqD37aoliw5Xg5K9w06IJPndIhM1B3zFcZw,23393 +transformers/models/mllama/__init__.py,sha256=2lTGCiL6EZirXNcu4aKV7vSmv50iRsQnCV-c9sahNXg,1073 +transformers/models/mllama/__pycache__/__init__.cpython-310.pyc,, +transformers/models/mllama/__pycache__/configuration_mllama.cpython-310.pyc,, +transformers/models/mllama/__pycache__/image_processing_mllama.cpython-310.pyc,, +transformers/models/mllama/__pycache__/modeling_mllama.cpython-310.pyc,, +transformers/models/mllama/__pycache__/processing_mllama.cpython-310.pyc,, +transformers/models/mllama/configuration_mllama.py,sha256=xNSwdFPE4V0MAKsiCljoK3UFekwLvRvMdSrNi_L5qZ0,18209 +transformers/models/mllama/image_processing_mllama.py,sha256=CJzTqSoe9n3tJnvo7XqPjVxjtQWE1zoxAMNcoH0HD58,38258 +transformers/models/mllama/modeling_mllama.py,sha256=XOI7l2y29BbB7mOSX-K_Ci4PRqy9m4b1fhF5sbo7tx0,79044 +transformers/models/mllama/processing_mllama.py,sha256=oa4t3yHIMoIadyRmlgHCxgy156NzAYHQutkWCHmw0RM,17653 +transformers/models/mluke/__init__.py,sha256=e_3cNftWOmhNXk-zsA1-2DOBT9L56SHr-6qev0xI7Ws,956 +transformers/models/mluke/__pycache__/__init__.cpython-310.pyc,, +transformers/models/mluke/__pycache__/tokenization_mluke.cpython-310.pyc,, +transformers/models/mluke/tokenization_mluke.py,sha256=PpWmJFXmwp40fIQvDN_m7Xo4LJNtWNAt6x5JH6Wm0us,82153 +transformers/models/mm_grounding_dino/__init__.py,sha256=mk2hUY_rZw6JSjfkqSL4hVYJKxh5ViM3TZfib-09kpc,1015 +transformers/models/mm_grounding_dino/__pycache__/__init__.cpython-310.pyc,, +transformers/models/mm_grounding_dino/__pycache__/configuration_mm_grounding_dino.cpython-310.pyc,, +transformers/models/mm_grounding_dino/__pycache__/modeling_mm_grounding_dino.cpython-310.pyc,, +transformers/models/mm_grounding_dino/__pycache__/modular_mm_grounding_dino.cpython-310.pyc,, +transformers/models/mm_grounding_dino/configuration_mm_grounding_dino.py,sha256=1r6ZcJHNxQdIxGK_PYsvhfXVAmThPIVvIgSEL99T4KE,15282 +transformers/models/mm_grounding_dino/modeling_mm_grounding_dino.py,sha256=mxH878CgFMRV8Vc9M2SdGn821z0ZpHj9mRsXa7z4D_Y,129461 +transformers/models/mm_grounding_dino/modular_mm_grounding_dino.py,sha256=Njd8tx8Mg6YQwOCXNdNJeSQD3jhq5QsQtsrMLcPC2HI,19389 +transformers/models/mobilebert/__init__.py,sha256=Jy7IZ2oQAjyE_KOoT-I7Z9bqPRVLfsOwx8XY3Y43RFc,1134 +transformers/models/mobilebert/__pycache__/__init__.cpython-310.pyc,, +transformers/models/mobilebert/__pycache__/configuration_mobilebert.cpython-310.pyc,, +transformers/models/mobilebert/__pycache__/modeling_mobilebert.cpython-310.pyc,, +transformers/models/mobilebert/__pycache__/modeling_tf_mobilebert.cpython-310.pyc,, +transformers/models/mobilebert/__pycache__/tokenization_mobilebert.cpython-310.pyc,, +transformers/models/mobilebert/__pycache__/tokenization_mobilebert_fast.cpython-310.pyc,, +transformers/models/mobilebert/configuration_mobilebert.py,sha256=kSjUZXRAtgvEjp4C2pxC8Po5MS6rM4i4v_xAzvqqHVk,8283 +transformers/models/mobilebert/modeling_mobilebert.py,sha256=icrVzODm-Ep83hkqQzFqygFEKKLpB5yxltVhi1BXc28,63164 +transformers/models/mobilebert/modeling_tf_mobilebert.py,sha256=kTa_oE6_AnYfGoWefuzHT1PXzB7GLMwVmkwocK3kDNw,83932 +transformers/models/mobilebert/tokenization_mobilebert.py,sha256=u3_ex8yv14oHz90QsfBjkELZaDwQDNicgNFgXDgtkvU,20149 +transformers/models/mobilebert/tokenization_mobilebert_fast.py,sha256=_cLnh_Vn7JHMg973Q4kjdkO35VIpNOW9UQt9OIGAvok,6703 +transformers/models/mobilenet_v1/__init__.py,sha256=kS0kf8Q0rDhNcqIJM6iI6iVufztYwEl-TsOzVQZwn-Y,1159 +transformers/models/mobilenet_v1/__pycache__/__init__.cpython-310.pyc,, +transformers/models/mobilenet_v1/__pycache__/configuration_mobilenet_v1.cpython-310.pyc,, +transformers/models/mobilenet_v1/__pycache__/feature_extraction_mobilenet_v1.cpython-310.pyc,, +transformers/models/mobilenet_v1/__pycache__/image_processing_mobilenet_v1.cpython-310.pyc,, +transformers/models/mobilenet_v1/__pycache__/image_processing_mobilenet_v1_fast.cpython-310.pyc,, +transformers/models/mobilenet_v1/__pycache__/modeling_mobilenet_v1.cpython-310.pyc,, +transformers/models/mobilenet_v1/configuration_mobilenet_v1.py,sha256=aR3QacEyWEphbgo_mcEvHS7NOVOwxQUhDvoWziA-q54,4939 +transformers/models/mobilenet_v1/feature_extraction_mobilenet_v1.py,sha256=Yydhc-fHuAzWeUOk7qrLrrs-HzMeaLE_IWeploaoOQc,1341 +transformers/models/mobilenet_v1/image_processing_mobilenet_v1.py,sha256=2QhRLV0yySXPOqwnZWoroOXwWuJO0G367igwHcD_YBE,15403 +transformers/models/mobilenet_v1/image_processing_mobilenet_v1_fast.py,sha256=RQI4Ujpx8yV9YFFvXzZEVZxqiZrQ97JSHnP_640V6Bs,1498 +transformers/models/mobilenet_v1/modeling_mobilenet_v1.py,sha256=EdpkzqoKflLLd57I4IiBO4f8l0t1hY-5kP5FkB275v0,15263 +transformers/models/mobilenet_v2/__init__.py,sha256=PGEnF5QRb3bZg_Iux0DuD7VPysu8nA0WxJEd6YOXtmw,1159 +transformers/models/mobilenet_v2/__pycache__/__init__.cpython-310.pyc,, +transformers/models/mobilenet_v2/__pycache__/configuration_mobilenet_v2.cpython-310.pyc,, +transformers/models/mobilenet_v2/__pycache__/feature_extraction_mobilenet_v2.cpython-310.pyc,, +transformers/models/mobilenet_v2/__pycache__/image_processing_mobilenet_v2.cpython-310.pyc,, +transformers/models/mobilenet_v2/__pycache__/image_processing_mobilenet_v2_fast.cpython-310.pyc,, +transformers/models/mobilenet_v2/__pycache__/modeling_mobilenet_v2.cpython-310.pyc,, +transformers/models/mobilenet_v2/configuration_mobilenet_v2.py,sha256=kEuy8U-ShxevXr2lGluqA4BRAq_3-UsWN4YutMm1yoc,6835 +transformers/models/mobilenet_v2/feature_extraction_mobilenet_v2.py,sha256=aO5lNZnnoRPfhoBEiDiLwuctZkGlFsX1Io-u167A7QU,1341 +transformers/models/mobilenet_v2/image_processing_mobilenet_v2.py,sha256=bdWTBTRZNIxkbjUpDdTYuX0cMbfoEVxRdFtZGIRCluw,24792 +transformers/models/mobilenet_v2/image_processing_mobilenet_v2_fast.py,sha256=KMUcJrCCXbjURFjjxAaLW43up6UAuiJ8P9L-OT6So7g,9722 +transformers/models/mobilenet_v2/modeling_mobilenet_v2.py,sha256=TzKMWwVX0WPcMjtthx5rVHj4ThUTj4zWSsAag6HQ8NQ,30987 +transformers/models/mobilevit/__init__.py,sha256=-pqcwwjQsaYPNEPlRiS9B06Rl9kZf4b8yWGWtW3d4K0,1185 +transformers/models/mobilevit/__pycache__/__init__.cpython-310.pyc,, +transformers/models/mobilevit/__pycache__/configuration_mobilevit.cpython-310.pyc,, +transformers/models/mobilevit/__pycache__/feature_extraction_mobilevit.cpython-310.pyc,, +transformers/models/mobilevit/__pycache__/image_processing_mobilevit.cpython-310.pyc,, +transformers/models/mobilevit/__pycache__/image_processing_mobilevit_fast.cpython-310.pyc,, +transformers/models/mobilevit/__pycache__/modeling_mobilevit.cpython-310.pyc,, +transformers/models/mobilevit/__pycache__/modeling_tf_mobilevit.cpython-310.pyc,, +transformers/models/mobilevit/configuration_mobilevit.py,sha256=tyQANkpBRv8MHvXm8nYGlMI_5gQJQekS25pQTQcbfPw,7596 +transformers/models/mobilevit/feature_extraction_mobilevit.py,sha256=rS3UvVaXJwUDc7ZsVoi33DAvQewGdnC4SOgqdxISEwk,1324 +transformers/models/mobilevit/image_processing_mobilevit.py,sha256=C-YObQ84n3UDfbnwFUAJl5rtRR9JrTRQHtOK230Uypg,23559 +transformers/models/mobilevit/image_processing_mobilevit_fast.py,sha256=9bkNGORXwIWH07GlgR7YYsfv31MTennEe45n_5CdZA8,9879 +transformers/models/mobilevit/modeling_mobilevit.py,sha256=-1iHPTcto0YydQYc5ojWtnYPxaXrR3AJhiZJUdDKARg,36742 +transformers/models/mobilevit/modeling_tf_mobilevit.py,sha256=VW-iXvdwlgflYrmmW_tfgb_QKE4ASB1I_5cbrjEvQUM,54753 +transformers/models/mobilevitv2/__init__.py,sha256=pAGk_9X22yOYvlcwbqTc4nm6fL4rPhAhDpdBguna5Q0,1003 +transformers/models/mobilevitv2/__pycache__/__init__.cpython-310.pyc,, +transformers/models/mobilevitv2/__pycache__/configuration_mobilevitv2.cpython-310.pyc,, +transformers/models/mobilevitv2/__pycache__/modeling_mobilevitv2.cpython-310.pyc,, +transformers/models/mobilevitv2/configuration_mobilevitv2.py,sha256=2mQCHZ8tq2bfrswTfb1fnottcJfY3p_g_vLoWXjkmBE,7159 +transformers/models/mobilevitv2/modeling_mobilevitv2.py,sha256=YgyCwMybqDGiDEoJ_jsuG2OMaRbY4lSD5VdY3LxNJ5s,34491 +transformers/models/modernbert/__init__.py,sha256=BEQFRFfcKvUlphA1ibW3s34Vkbm-MUuyqzaLbrIFiAA,1006 +transformers/models/modernbert/__pycache__/__init__.cpython-310.pyc,, +transformers/models/modernbert/__pycache__/configuration_modernbert.cpython-310.pyc,, +transformers/models/modernbert/__pycache__/modeling_modernbert.cpython-310.pyc,, +transformers/models/modernbert/__pycache__/modular_modernbert.cpython-310.pyc,, +transformers/models/modernbert/configuration_modernbert.py,sha256=HQK0ucX7it6g0ilY3vHTUyRupzHOz50KpLNyNWsP92g,11493 +transformers/models/modernbert/modeling_modernbert.py,sha256=GyPbL1nT-AvZr4n7bfPOFa_9kLX_wJkl5zJFDmlIaP8,67793 +transformers/models/modernbert/modular_modernbert.py,sha256=RsZTbedS0GveVB7gUj2Y5Nhy_7bHofHOMSnmsVl0fRw,73478 +transformers/models/modernbert_decoder/__init__.py,sha256=RjLebVKPcGgNEORY5xypTPd8oYWcnFmbGm3hBqQX-HE,1022 +transformers/models/modernbert_decoder/__pycache__/__init__.cpython-310.pyc,, +transformers/models/modernbert_decoder/__pycache__/configuration_modernbert_decoder.cpython-310.pyc,, +transformers/models/modernbert_decoder/__pycache__/modeling_modernbert_decoder.cpython-310.pyc,, +transformers/models/modernbert_decoder/__pycache__/modular_modernbert_decoder.cpython-310.pyc,, +transformers/models/modernbert_decoder/configuration_modernbert_decoder.py,sha256=08paqhKhXbw-sTasdy5vNsujOFc5wGVCyxWJmtAqkHk,10629 +transformers/models/modernbert_decoder/modeling_modernbert_decoder.py,sha256=47E1Ei76GfYLbmdh8mYQJV41v2xU_3H3RgHP4XiYmhQ,32356 +transformers/models/modernbert_decoder/modular_modernbert_decoder.py,sha256=pi-DvqalIz1MSuGZvgAaGjbbV8Rvnioz4SbRMq0okss,34854 +transformers/models/moonshine/__init__.py,sha256=eBgvc9LtoDnB6HnNvrObDWL3h_L4Sgn5-D-hepNfAmI,999 +transformers/models/moonshine/__pycache__/__init__.cpython-310.pyc,, +transformers/models/moonshine/__pycache__/configuration_moonshine.cpython-310.pyc,, +transformers/models/moonshine/__pycache__/modeling_moonshine.cpython-310.pyc,, +transformers/models/moonshine/__pycache__/modular_moonshine.cpython-310.pyc,, +transformers/models/moonshine/configuration_moonshine.py,sha256=FCiqs9BayGl3oUGFh4FIAFz-3eZKlpqQOGusZvhFBZ8,13524 +transformers/models/moonshine/modeling_moonshine.py,sha256=0NtUzUmCyYSowGvfZ9LcKHde-IW8gf_sAn4P4N32OvU,49054 +transformers/models/moonshine/modular_moonshine.py,sha256=XBj2m4oizweDyYADB3eQBFTmFcx9SDI8aJHv_8RDPzg,43684 +transformers/models/moshi/__init__.py,sha256=uW4oqTKZdbmURZaC_xwwHXnYEMyLJrMEJAlfbUzSWO8,991 +transformers/models/moshi/__pycache__/__init__.cpython-310.pyc,, +transformers/models/moshi/__pycache__/configuration_moshi.cpython-310.pyc,, +transformers/models/moshi/__pycache__/modeling_moshi.cpython-310.pyc,, +transformers/models/moshi/configuration_moshi.py,sha256=zVqARdo5wQHERpun-Z1f1mw1_ddLTn0fQsvs2SjE5J8,16104 +transformers/models/moshi/modeling_moshi.py,sha256=S0HaI322DCLsG8HTYllVAlh73QyYnWtzwwesCaLYnyE,123767 +transformers/models/mpnet/__init__.py,sha256=agt4uraqHTtlIphsDB17XVAPzCKHaPBKlVaQkKHxRyM,1109 +transformers/models/mpnet/__pycache__/__init__.cpython-310.pyc,, +transformers/models/mpnet/__pycache__/configuration_mpnet.cpython-310.pyc,, +transformers/models/mpnet/__pycache__/modeling_mpnet.cpython-310.pyc,, +transformers/models/mpnet/__pycache__/modeling_tf_mpnet.cpython-310.pyc,, +transformers/models/mpnet/__pycache__/tokenization_mpnet.cpython-310.pyc,, +transformers/models/mpnet/__pycache__/tokenization_mpnet_fast.cpython-310.pyc,, +transformers/models/mpnet/configuration_mpnet.py,sha256=DsCgTVE6hDGcaVxd2yqEPj7Ph-JLE2nPyt1AJlVZkx4,5327 +transformers/models/mpnet/modeling_mpnet.py,sha256=3SI7QLERArtBqN0rRbsTMaskn_GynI-8V7DGSnob9xA,37898 +transformers/models/mpnet/modeling_tf_mpnet.py,sha256=tIjgRjIel676orRDAYK6oQ1YnPsPMY7rlCD0cMBdc_Y,55535 +transformers/models/mpnet/tokenization_mpnet.py,sha256=NNYv8Zwj-6RFWQ7Rynjpe1oIvEZSOBl209DlaBju-Ro,22442 +transformers/models/mpnet/tokenization_mpnet_fast.py,sha256=2j7lcdtgYzsQy52RV-dTbGUwgczxY5qO6siJauxsnuY,9180 +transformers/models/mpt/__init__.py,sha256=DAIIAY0kPL-bXMkPUvxmP97HCXPi-SoM3NLnlJJYarg,987 +transformers/models/mpt/__pycache__/__init__.cpython-310.pyc,, +transformers/models/mpt/__pycache__/configuration_mpt.cpython-310.pyc,, +transformers/models/mpt/__pycache__/modeling_mpt.cpython-310.pyc,, +transformers/models/mpt/configuration_mpt.py,sha256=S-Ah1uArFpNIGv97PC0mNcW_JBvM5I83TRjM61KjNZ0,10499 +transformers/models/mpt/modeling_mpt.py,sha256=tqttIJvVRzR8enDLj0KtVSX4ZHxm2kk9a312LZZYy1g,35426 +transformers/models/mra/__init__.py,sha256=51mnm4DFq6aWxOsmaaVZDL28QozNauXyTtbEihDxUQU,987 +transformers/models/mra/__pycache__/__init__.cpython-310.pyc,, +transformers/models/mra/__pycache__/configuration_mra.cpython-310.pyc,, +transformers/models/mra/__pycache__/modeling_mra.cpython-310.pyc,, +transformers/models/mra/configuration_mra.py,sha256=oNhRz6PdvUK_ugoiAhHDuNkGgBNyDguATgQdKeTJBnY,6536 +transformers/models/mra/modeling_mra.py,sha256=bcVhUeWeW7dP6M6heiSwSMrzqXzXOQKfGS7wNwpxqh4,57289 +transformers/models/mt5/__init__.py,sha256=UK8vGX9r6fPdzPaJKCbGJ7RCqKOdIo-7H9V-Qp8rwEg,1095 +transformers/models/mt5/__pycache__/__init__.cpython-310.pyc,, +transformers/models/mt5/__pycache__/configuration_mt5.cpython-310.pyc,, +transformers/models/mt5/__pycache__/modeling_flax_mt5.cpython-310.pyc,, +transformers/models/mt5/__pycache__/modeling_mt5.cpython-310.pyc,, +transformers/models/mt5/__pycache__/modeling_tf_mt5.cpython-310.pyc,, +transformers/models/mt5/__pycache__/tokenization_mt5.cpython-310.pyc,, +transformers/models/mt5/__pycache__/tokenization_mt5_fast.cpython-310.pyc,, +transformers/models/mt5/configuration_mt5.py,sha256=oXTmtVxXx5i-S70WEcmaZo_kI1CUKCaxA7aeos5iX7k,8011 +transformers/models/mt5/modeling_flax_mt5.py,sha256=9WjlLB_EV9WDiy-rBxzVUPocsHrv02cEa4OB8lVR6EA,4329 +transformers/models/mt5/modeling_mt5.py,sha256=DZLh3cjsngyRoG1X6YHjtWmviHi7oTcBJuIhQe0Gve4,113688 +transformers/models/mt5/modeling_tf_mt5.py,sha256=EIUkWvuApAbiaX6qhveT1KC43s_NDmQazLrbYT45aao,3406 +transformers/models/mt5/tokenization_mt5.py,sha256=AckaXSw5OojOGLezMhrsv2a9BMZXwzhy5IsT3hvp_Q8,746 +transformers/models/mt5/tokenization_mt5_fast.py,sha256=1npEFH_c4nDQxOFNoqcGNW30KCWe04BpLrrv7aDcDQ8,762 +transformers/models/musicgen/__init__.py,sha256=iwtW9pg6iDe5D2dWVC4IRU8QbNmRK5kMqPCM8fsUSgo,1036 +transformers/models/musicgen/__pycache__/__init__.cpython-310.pyc,, +transformers/models/musicgen/__pycache__/configuration_musicgen.cpython-310.pyc,, +transformers/models/musicgen/__pycache__/modeling_musicgen.cpython-310.pyc,, +transformers/models/musicgen/__pycache__/processing_musicgen.cpython-310.pyc,, +transformers/models/musicgen/configuration_musicgen.py,sha256=YpsrhRaEqRAOYYlkx5uyelz5iq2dwvU8_mkknRIN9AM,10959 +transformers/models/musicgen/modeling_musicgen.py,sha256=SYb95MPeR2euWCbqhILTLXN0uTxE13EupONfT4ECS3w,118192 +transformers/models/musicgen/processing_musicgen.py,sha256=wmNkDWi3myrHNBldIVy6ikOdz9nRJKeqUSimsEw_23U,4591 +transformers/models/musicgen_melody/__init__.py,sha256=WVEsVs7g0XlpO_yd1X0X4QnMjhG0h_n6T41FpdJcnS8,1011 +transformers/models/musicgen_melody/__pycache__/__init__.cpython-310.pyc,, +transformers/models/musicgen_melody/__pycache__/configuration_musicgen_melody.cpython-310.pyc,, +transformers/models/musicgen_melody/__pycache__/feature_extraction_musicgen_melody.cpython-310.pyc,, +transformers/models/musicgen_melody/__pycache__/modeling_musicgen_melody.cpython-310.pyc,, +transformers/models/musicgen_melody/__pycache__/processing_musicgen_melody.cpython-310.pyc,, +transformers/models/musicgen_melody/configuration_musicgen_melody.py,sha256=wlnZBqJQ0XElTRvI2zPc1PGLarzMsWBQaHKYmkensmk,12016 +transformers/models/musicgen_melody/feature_extraction_musicgen_melody.py,sha256=onUVyD4VSztogKli3SlXeuhd6cNn5EnH6PSjx6Lj36Y,15359 +transformers/models/musicgen_melody/modeling_musicgen_melody.py,sha256=wU_GuVDCdGR-ju824mDJFr1DW12Rxd5HNgviT-t8qmM,111404 +transformers/models/musicgen_melody/processing_musicgen_melody.py,sha256=gUo8sWpKuyZTneOnx5r_HPw7QE8Ed3Togmz7g8fGJBs,6085 +transformers/models/mvp/__init__.py,sha256=0e0-wP4EkfzPiO_BlHlmyVUEq-1kb9RHY2Ikbk66W7s,1064 +transformers/models/mvp/__pycache__/__init__.cpython-310.pyc,, +transformers/models/mvp/__pycache__/configuration_mvp.cpython-310.pyc,, +transformers/models/mvp/__pycache__/modeling_mvp.cpython-310.pyc,, +transformers/models/mvp/__pycache__/tokenization_mvp.cpython-310.pyc,, +transformers/models/mvp/__pycache__/tokenization_mvp_fast.cpython-310.pyc,, +transformers/models/mvp/configuration_mvp.py,sha256=Ah_EG0nItOD3_y_WDad6cnCcgGY2TXWuJzxuLJQ6fq4,8451 +transformers/models/mvp/modeling_mvp.py,sha256=xWrWpErKHzXD1z57_52NKB3ht1TOUCmlugUhPOFl-P8,82194 +transformers/models/mvp/tokenization_mvp.py,sha256=7Q1V8hHo1hd9RCKu-A1lv2WNAcTbxhBidKNPHOLjwyc,16206 +transformers/models/mvp/tokenization_mvp_fast.py,sha256=xQrPiI91_CG7II-gQEJs7rtTSMRbKNARc185MOa5JQs,11819 +transformers/models/myt5/__init__.py,sha256=MFQX-RuvZujGb_twBWBQpTt4NZq6FxreEysWmF2fFGI,955 +transformers/models/myt5/__pycache__/__init__.cpython-310.pyc,, +transformers/models/myt5/__pycache__/tokenization_myt5.cpython-310.pyc,, +transformers/models/myt5/tokenization_myt5.py,sha256=GdQXAMMCaCIbfJI-Hry-9myIFXO2TLpoO6D8VC1HpAs,15535 +transformers/models/nemotron/__init__.py,sha256=ZwaMH1AQ0VIuFnouYe0Sx0HcCGA7PaCp3-_yw3xjeQA,997 +transformers/models/nemotron/__pycache__/__init__.cpython-310.pyc,, +transformers/models/nemotron/__pycache__/configuration_nemotron.cpython-310.pyc,, +transformers/models/nemotron/__pycache__/modeling_nemotron.cpython-310.pyc,, +transformers/models/nemotron/configuration_nemotron.py,sha256=QMH_Mw48ZgCvovfE3MtUM6W_34DVUb7unpr27JaVTIg,7399 +transformers/models/nemotron/modeling_nemotron.py,sha256=p9LxqWzWN6axZVNfiHtnLkIw1TkU9tksiX_kgwXfmh4,43986 +transformers/models/nllb/__init__.py,sha256=MLFrxhOJ3xvOAcRulvCEMoKsajLuudllZLMrYDYQOas,997 +transformers/models/nllb/__pycache__/__init__.cpython-310.pyc,, +transformers/models/nllb/__pycache__/tokenization_nllb.cpython-310.pyc,, +transformers/models/nllb/__pycache__/tokenization_nllb_fast.cpython-310.pyc,, +transformers/models/nllb/tokenization_nllb.py,sha256=nHIf5mrI6gDEugszKVOwpB3mWPE5a1KcBFK2qRTrg-E,19158 +transformers/models/nllb/tokenization_nllb_fast.py,sha256=uT2QAtg_upIEJ9W6lKkDi7EDHOqrB08oUH6OTGNagm4,15822 +transformers/models/nllb_moe/__init__.py,sha256=sAfoAnhHK_reU1a2WUoF1rFtPBckeGGrzJCD8gUv54A,997 +transformers/models/nllb_moe/__pycache__/__init__.cpython-310.pyc,, +transformers/models/nllb_moe/__pycache__/configuration_nllb_moe.cpython-310.pyc,, +transformers/models/nllb_moe/__pycache__/modeling_nllb_moe.cpython-310.pyc,, +transformers/models/nllb_moe/configuration_nllb_moe.py,sha256=jHKoRpGbrlNEcBiOk3b2fPOo1m6OD7Tx11F9r8SSd1Y,11222 +transformers/models/nllb_moe/modeling_nllb_moe.py,sha256=kESo7r71_BREOivYAb-OBSqmBa7AYNAkUnTcADyVCLw,82111 +transformers/models/nougat/__init__.py,sha256=sFYK9O1tIETKks9tQ5d6X3gGWAFfTXNge06ZdnnKV9s,1090 +transformers/models/nougat/__pycache__/__init__.cpython-310.pyc,, +transformers/models/nougat/__pycache__/image_processing_nougat.cpython-310.pyc,, +transformers/models/nougat/__pycache__/image_processing_nougat_fast.cpython-310.pyc,, +transformers/models/nougat/__pycache__/processing_nougat.cpython-310.pyc,, +transformers/models/nougat/__pycache__/tokenization_nougat_fast.cpython-310.pyc,, +transformers/models/nougat/image_processing_nougat.py,sha256=tOeyzKQYt9uaENoWNdHCfyqi5l_AHqRpJqMnKt7wL_A,24225 +transformers/models/nougat/image_processing_nougat_fast.py,sha256=uZRGpPlOrwmWS7am2kBIc2ytCEfAUAlXD6AIksQpHWE,11315 +transformers/models/nougat/processing_nougat.py,sha256=1gOCgHjtvBLDNF82ckjBAgpNjIlewP1y_vaMKhkdcac,6255 +transformers/models/nougat/tokenization_nougat_fast.py,sha256=Z0T6qwb5Frgn_QCDRMectgQbKaxnt943q8QOFjenC40,24560 +transformers/models/nystromformer/__init__.py,sha256=CwEg6m4nJW_AfNDws_MIv1O1x5IO3xPp-FYqirlFXwk,1007 +transformers/models/nystromformer/__pycache__/__init__.cpython-310.pyc,, +transformers/models/nystromformer/__pycache__/configuration_nystromformer.cpython-310.pyc,, +transformers/models/nystromformer/__pycache__/modeling_nystromformer.cpython-310.pyc,, +transformers/models/nystromformer/configuration_nystromformer.py,sha256=UyLmPF2li3_ADTz9tS1h5t4CDY5d5GzsfeC9hG42RzI,6402 +transformers/models/nystromformer/modeling_nystromformer.py,sha256=bHXMtBDSPg8BtHRf_kP8R46evgvKQjiYkDtUvZ-8PYE,43471 +transformers/models/olmo/__init__.py,sha256=x9u_5vqI52-uBuj89-6aYucGDlvBUEPSOhPLLB1asok,1009 +transformers/models/olmo/__pycache__/__init__.cpython-310.pyc,, +transformers/models/olmo/__pycache__/configuration_olmo.cpython-310.pyc,, +transformers/models/olmo/__pycache__/modeling_olmo.cpython-310.pyc,, +transformers/models/olmo/__pycache__/modular_olmo.cpython-310.pyc,, +transformers/models/olmo/configuration_olmo.py,sha256=s_YotovUtp-VmB7q9RV4B1TKgjhp3gE6Ucqg72I3GJc,9423 +transformers/models/olmo/modeling_olmo.py,sha256=0umK9ECWQ4j5XD6gMBt1cV4q5tR1cIsAYzchP6rA_ko,19886 +transformers/models/olmo/modular_olmo.py,sha256=UTS-10TNLe_ZDV2qVLIw6y03ub4IY3j602iXn2UupQc,7102 +transformers/models/olmo2/__init__.py,sha256=Frt9nEMsfPszod1lkFTAJUobU50IjOFlqI6uJkuQVcY,1011 +transformers/models/olmo2/__pycache__/__init__.cpython-310.pyc,, +transformers/models/olmo2/__pycache__/configuration_olmo2.cpython-310.pyc,, +transformers/models/olmo2/__pycache__/modeling_olmo2.cpython-310.pyc,, +transformers/models/olmo2/__pycache__/modular_olmo2.cpython-310.pyc,, +transformers/models/olmo2/configuration_olmo2.py,sha256=kqBjnAs0k-pZ-Y8zNMRWQ-6gav-YpOpg6oy9LZ-AhpE,9439 +transformers/models/olmo2/modeling_olmo2.py,sha256=lSTTMPbTZyLq8p3PbespqegStM5SmLMNlPa2FqT8ttE,20315 +transformers/models/olmo2/modular_olmo2.py,sha256=9O8WahU9g_bYicjUvuzxdT6sxdZ7IWt-8UVDLw7dffY,14200 +transformers/models/olmo3/__init__.py,sha256=l35_AKxpPmjrZIpeDw2nAA_BT59faflVjx3mXAVx9ro,1007 +transformers/models/olmo3/__pycache__/__init__.cpython-310.pyc,, +transformers/models/olmo3/__pycache__/configuration_olmo3.cpython-310.pyc,, +transformers/models/olmo3/__pycache__/modeling_olmo3.cpython-310.pyc,, +transformers/models/olmo3/__pycache__/modular_olmo3.cpython-310.pyc,, +transformers/models/olmo3/configuration_olmo3.py,sha256=-yRbWIsHxwTEd0CqyVMapJDcWKCRoQwTZrAUmC3oJX8,12229 +transformers/models/olmo3/modeling_olmo3.py,sha256=jTukEaidvT9wOyShF9A4FN55Uv29UaTN9kGGUm8DlGQ,22264 +transformers/models/olmo3/modular_olmo3.py,sha256=BHe0QjEPezYJS-_5AhixHdqo8l6w0q2yf1997VuvtQY,19666 +transformers/models/olmoe/__init__.py,sha256=eQ6mx9aBIcA4RiK3p7dbqORokkuMfQNRss06E8uWNrk,991 +transformers/models/olmoe/__pycache__/__init__.cpython-310.pyc,, +transformers/models/olmoe/__pycache__/configuration_olmoe.cpython-310.pyc,, +transformers/models/olmoe/__pycache__/modeling_olmoe.cpython-310.pyc,, +transformers/models/olmoe/configuration_olmoe.py,sha256=_NEJ3nvuHqEOJND_jWjpqfV-mR7-CB9lUnVPoDmhCp4,9069 +transformers/models/olmoe/modeling_olmoe.py,sha256=JIcXqEd_vLSxbOZIqazoKbay9KACGRp_ZO5yDrZfTA0,51495 +transformers/models/omdet_turbo/__init__.py,sha256=XIckpuo9tkT7NB5uTs9wLdpxr9GDedQPVJL2P8XU-7Q,1045 +transformers/models/omdet_turbo/__pycache__/__init__.cpython-310.pyc,, +transformers/models/omdet_turbo/__pycache__/configuration_omdet_turbo.cpython-310.pyc,, +transformers/models/omdet_turbo/__pycache__/modeling_omdet_turbo.cpython-310.pyc,, +transformers/models/omdet_turbo/__pycache__/processing_omdet_turbo.cpython-310.pyc,, +transformers/models/omdet_turbo/configuration_omdet_turbo.py,sha256=2XMjtVGwInCV4GpQW-FHqsvXCoce1rsiBMT9j2BXevo,14933 +transformers/models/omdet_turbo/modeling_omdet_turbo.py,sha256=-FNbrykecMvG2PmYHGvshaidc9sePisxL7semsnaLRE,74062 +transformers/models/omdet_turbo/processing_omdet_turbo.py,sha256=lh2Pk0x04IXmSE8TcvnmP-FRoP48T2Ev39u64OeMocY,16871 +transformers/models/oneformer/__init__.py,sha256=MrdVp7ZBJOVbWMpwojOPnEzDDW2HSqs5oSZG81jdCQI,1136 +transformers/models/oneformer/__pycache__/__init__.cpython-310.pyc,, +transformers/models/oneformer/__pycache__/configuration_oneformer.cpython-310.pyc,, +transformers/models/oneformer/__pycache__/image_processing_oneformer.cpython-310.pyc,, +transformers/models/oneformer/__pycache__/image_processing_oneformer_fast.cpython-310.pyc,, +transformers/models/oneformer/__pycache__/modeling_oneformer.cpython-310.pyc,, +transformers/models/oneformer/__pycache__/processing_oneformer.cpython-310.pyc,, +transformers/models/oneformer/configuration_oneformer.py,sha256=GeVa40j8P2XaKbU58JWE9C2EYXNhgUJjY13kUzXliMU,13678 +transformers/models/oneformer/image_processing_oneformer.py,sha256=ahDeXLk5CA-nXd32iTPy5otK7i27xxJNp_HWKTrcxuA,60667 +transformers/models/oneformer/image_processing_oneformer_fast.py,sha256=sBclZOyjttl_lbchZ_aO90q_v3DrTv5g8sLV3ShNJUU,41187 +transformers/models/oneformer/modeling_oneformer.py,sha256=hCDHd4bwMUCdKms9u96h17GMAzhr0B4PWnm-n_ZgZ7Q,139862 +transformers/models/oneformer/processing_oneformer.py,sha256=dUSYgtezsucPHd9xJB5p2Tad6R-AI2h_rFe0MiM-9FI,9179 +transformers/models/openai/__init__.py,sha256=q0fAl8ajoJyknHe5A3ZHuHH3zww8xdupt_j49lIaObY,1114 +transformers/models/openai/__pycache__/__init__.cpython-310.pyc,, +transformers/models/openai/__pycache__/configuration_openai.cpython-310.pyc,, +transformers/models/openai/__pycache__/modeling_openai.cpython-310.pyc,, +transformers/models/openai/__pycache__/modeling_tf_openai.cpython-310.pyc,, +transformers/models/openai/__pycache__/tokenization_openai.cpython-310.pyc,, +transformers/models/openai/__pycache__/tokenization_openai_fast.cpython-310.pyc,, +transformers/models/openai/configuration_openai.py,sha256=ERFfcrsaGEuG-8WnuBDfYyHR7uc5ihEr9JfItBMGZm0,7109 +transformers/models/openai/modeling_openai.py,sha256=w-NnaXEUNT03W7lvl1_EFj7pyHSVLkZujxftr94VnHg,37721 +transformers/models/openai/modeling_tf_openai.py,sha256=mZWr6qc8fCXTR6y6GXLc_E_FgHn5-CB6dzMOhGXbfVM,40857 +transformers/models/openai/tokenization_openai.py,sha256=MhxS6G-hQLHLdmarGxOPBpvMEbNLHuFRZehOjzg-o90,15159 +transformers/models/openai/tokenization_openai_fast.py,sha256=qBalVcRbqq9AZAnzkFvYTbokp4eU-BvgO3QIWYoqndo,2553 +transformers/models/opt/__init__.py,sha256=Xk3Z-OdrOC4Y5J0KOEIB74Pp4PsfAllBI503NT7yFk8,1059 +transformers/models/opt/__pycache__/__init__.cpython-310.pyc,, +transformers/models/opt/__pycache__/configuration_opt.cpython-310.pyc,, +transformers/models/opt/__pycache__/modeling_flax_opt.cpython-310.pyc,, +transformers/models/opt/__pycache__/modeling_opt.cpython-310.pyc,, +transformers/models/opt/__pycache__/modeling_tf_opt.cpython-310.pyc,, +transformers/models/opt/configuration_opt.py,sha256=nEHN7nBCghjCfcU_vueoTL5TfCMc6JUE6cUH6knhnxM,6694 +transformers/models/opt/modeling_flax_opt.py,sha256=a1OCINHVTj-osjuJUxfYZgTS-1j7r6EPT-TgAD9lP74,31631 +transformers/models/opt/modeling_opt.py,sha256=uCv1_ZVaFaWLz2ip711WZMiB-tZcf71rvJXk2OwXPlY,48327 +transformers/models/opt/modeling_tf_opt.py,sha256=gZ8xHAIaZDYmsvHbxNI66ITB0QIaYoYdbLF7uNVuTEg,49360 +transformers/models/ovis2/__init__.py,sha256=df6-Fy8DbIIuQ9a29Ko9XPCSZm0Yh8hNEnTLR4NUgj0,1137 +transformers/models/ovis2/__pycache__/__init__.cpython-310.pyc,, +transformers/models/ovis2/__pycache__/configuration_ovis2.cpython-310.pyc,, +transformers/models/ovis2/__pycache__/image_processing_ovis2.cpython-310.pyc,, +transformers/models/ovis2/__pycache__/image_processing_ovis2_fast.cpython-310.pyc,, +transformers/models/ovis2/__pycache__/modeling_ovis2.cpython-310.pyc,, +transformers/models/ovis2/__pycache__/modular_ovis2.cpython-310.pyc,, +transformers/models/ovis2/__pycache__/processing_ovis2.cpython-310.pyc,, +transformers/models/ovis2/configuration_ovis2.py,sha256=TPLM3X-fnZ5IYjF8vyZ-bxtF9ob8Wu5QvrxX4pR7eWg,8187 +transformers/models/ovis2/image_processing_ovis2.py,sha256=3mY4y7qwfa-gsnQK9SOO3Iy-IyAqTMSpboFSQ7KgBP4,27859 +transformers/models/ovis2/image_processing_ovis2_fast.py,sha256=e_FV-wBDDcOAe9j-oAc_fuw_K05y0S5M48SbT1ZR9nc,10837 +transformers/models/ovis2/modeling_ovis2.py,sha256=UltZ0Poulsn9LkhgeTsMsp3N7JMKJsCaRRtgEVg4_Vw,34467 +transformers/models/ovis2/modular_ovis2.py,sha256=wgtKNriRoUz-rzByYPH62ysnlXrGTJv12RtYFlXPjC4,17240 +transformers/models/ovis2/processing_ovis2.py,sha256=r_b1_6K-vQ4tj1-ziX1luv4A_IEd1pjzS0jKN9h3ltQ,7972 +transformers/models/owlv2/__init__.py,sha256=vHnQwYJ0hEc12ofOV3b1k9fHscBgfQEXcLLgo4-H3GU,1116 +transformers/models/owlv2/__pycache__/__init__.cpython-310.pyc,, +transformers/models/owlv2/__pycache__/configuration_owlv2.cpython-310.pyc,, +transformers/models/owlv2/__pycache__/image_processing_owlv2.cpython-310.pyc,, +transformers/models/owlv2/__pycache__/image_processing_owlv2_fast.cpython-310.pyc,, +transformers/models/owlv2/__pycache__/modeling_owlv2.cpython-310.pyc,, +transformers/models/owlv2/__pycache__/modular_owlv2.cpython-310.pyc,, +transformers/models/owlv2/__pycache__/processing_owlv2.cpython-310.pyc,, +transformers/models/owlv2/configuration_owlv2.py,sha256=18Krr0RoZ25eU0eCSPegHXXKAoA64zw-bknsCeBkPTs,13134 +transformers/models/owlv2/image_processing_owlv2.py,sha256=hPbsaQX5Grzdj9il2MpCUZY0ky0nFVed4Ff1jifaIlI,28051 +transformers/models/owlv2/image_processing_owlv2_fast.py,sha256=DnSdjtmXQr_v-wQT5vexBEg8Sumv2qvSjoMIutkyz5Y,18089 +transformers/models/owlv2/modeling_owlv2.py,sha256=GZdyChUvGMt1PU_uGUKpOEofRD9ZxkdkQgtNoKCh8ec,77981 +transformers/models/owlv2/modular_owlv2.py,sha256=jXNLUwp8xViq1yy_r1xFMSghhv99MKnaH1Zie4o_4VA,8725 +transformers/models/owlv2/processing_owlv2.py,sha256=akRzrulhauF5WtoA0nhTufMmIENKjjkqtCqSGboKS0Q,14533 +transformers/models/owlvit/__init__.py,sha256=Nhrrja_j2RZtj-rQS6TDJ8upQqnMptnFukq49QAkito,1166 +transformers/models/owlvit/__pycache__/__init__.cpython-310.pyc,, +transformers/models/owlvit/__pycache__/configuration_owlvit.cpython-310.pyc,, +transformers/models/owlvit/__pycache__/feature_extraction_owlvit.cpython-310.pyc,, +transformers/models/owlvit/__pycache__/image_processing_owlvit.cpython-310.pyc,, +transformers/models/owlvit/__pycache__/image_processing_owlvit_fast.cpython-310.pyc,, +transformers/models/owlvit/__pycache__/modeling_owlvit.cpython-310.pyc,, +transformers/models/owlvit/__pycache__/processing_owlvit.cpython-310.pyc,, +transformers/models/owlvit/configuration_owlvit.py,sha256=KxKdzp6xBZOAEBDSGu_LRGYBKhjEg7tU8dfqLQXv6wo,14435 +transformers/models/owlvit/feature_extraction_owlvit.py,sha256=49Ic56gmQQtE_WEmzzyE9bVBdS5RMkG3vOK1cBcjc5g,1300 +transformers/models/owlvit/image_processing_owlvit.py,sha256=cuE9jtFrwcGN_3mkd-0ZguU-oU7wVFDVeo1I0xTAVAE,29481 +transformers/models/owlvit/image_processing_owlvit_fast.py,sha256=bUbcbutdaVZWbQ1Taz5rJX40PR401uSSy12JGqhm948,10519 +transformers/models/owlvit/modeling_owlvit.py,sha256=8Dp2cnnWqFjiiM2JGwYgf9XABORJ2RPdG0KhypB95VU,73411 +transformers/models/owlvit/processing_owlvit.py,sha256=LcKsqDVAPZobncWWhJAJAjjAMMfaUmoz7CbMO0FrGVA,15279 +transformers/models/paligemma/__init__.py,sha256=nKnTTLC8XYlI7uYfS8h-D4vz3gFhknkNeDlZIwZlZ9w,1039 +transformers/models/paligemma/__pycache__/__init__.cpython-310.pyc,, +transformers/models/paligemma/__pycache__/configuration_paligemma.cpython-310.pyc,, +transformers/models/paligemma/__pycache__/modeling_paligemma.cpython-310.pyc,, +transformers/models/paligemma/__pycache__/processing_paligemma.cpython-310.pyc,, +transformers/models/paligemma/configuration_paligemma.py,sha256=BTK5bsUZwUovhsGqWHIzYidzy-XyBEtDEROPh3IZJ9w,5362 +transformers/models/paligemma/modeling_paligemma.py,sha256=ta1GVvFatkYZY6o-N-N7oJxD8aVhA4WTxC-awk18DNk,27366 +transformers/models/paligemma/processing_paligemma.py,sha256=nDroihOWd88xWiNPNoJHpumP-KzHhTy0MwfCf7VRgEc,15172 +transformers/models/parakeet/__init__.py,sha256=hUBWAelpUTDzNsO6U5c1w2mts5ePvfNbov_OzhNh8X4,1090 +transformers/models/parakeet/__pycache__/__init__.cpython-310.pyc,, +transformers/models/parakeet/__pycache__/configuration_parakeet.cpython-310.pyc,, +transformers/models/parakeet/__pycache__/feature_extraction_parakeet.cpython-310.pyc,, +transformers/models/parakeet/__pycache__/modeling_parakeet.cpython-310.pyc,, +transformers/models/parakeet/__pycache__/modular_parakeet.cpython-310.pyc,, +transformers/models/parakeet/__pycache__/processing_parakeet.cpython-310.pyc,, +transformers/models/parakeet/__pycache__/tokenization_parakeet_fast.cpython-310.pyc,, +transformers/models/parakeet/configuration_parakeet.py,sha256=iEzIGIAuJs33gfxpPLHuI-tWEZEd6tmxowuFzMXsxWs,10195 +transformers/models/parakeet/feature_extraction_parakeet.py,sha256=x6dbut6ur6acWsyvF7EMzh5qKwxmB1FcMkkYavVMDHU,13147 +transformers/models/parakeet/modeling_parakeet.py,sha256=QQaS7teyQxrMmtCOn2QCuWvIfTVgVBsdp8zD53iz-Yw,32328 +transformers/models/parakeet/modular_parakeet.py,sha256=N2nswbg8Psd8P4bQSRplTQVD_KhK08alWNLInmO_C7M,26649 +transformers/models/parakeet/processing_parakeet.py,sha256=Av8YnWOgSzRM7ENuo0VU_gBkSO9roQB0PR2q7q_f1n4,3221 +transformers/models/parakeet/tokenization_parakeet_fast.py,sha256=5oWBkuJpIQKxYKaea1bw_ju8Wrq0bGz2wdVvQi5IaRs,1946 +transformers/models/patchtsmixer/__init__.py,sha256=deFjF_Tu67XcAcNHaq1PXO77N4kVW9wG80SnXBaeagE,1005 +transformers/models/patchtsmixer/__pycache__/__init__.cpython-310.pyc,, +transformers/models/patchtsmixer/__pycache__/configuration_patchtsmixer.cpython-310.pyc,, +transformers/models/patchtsmixer/__pycache__/modeling_patchtsmixer.cpython-310.pyc,, +transformers/models/patchtsmixer/configuration_patchtsmixer.py,sha256=h1w-YRD_Q9AgQUKBRvzxi2JBEW35NbDap8xkdui-c3U,12580 +transformers/models/patchtsmixer/modeling_patchtsmixer.py,sha256=Tb4GZWfKaXEwNt12Rr6TNZp4nQsBXq_lzmUfRR4EyS8,85134 +transformers/models/patchtst/__init__.py,sha256=lrpuBvP25Yq6HZOCyS4yWVYZ47qWzK--rqC0AOIGGPE,997 +transformers/models/patchtst/__pycache__/__init__.cpython-310.pyc,, +transformers/models/patchtst/__pycache__/configuration_patchtst.cpython-310.pyc,, +transformers/models/patchtst/__pycache__/modeling_patchtst.cpython-310.pyc,, +transformers/models/patchtst/configuration_patchtst.py,sha256=FdiHfYFiHvo7kIuOV_zSGPHZ2Q-QYbPEB1ZkqLOc5qE,12309 +transformers/models/patchtst/modeling_patchtst.py,sha256=fYVkC0X1QFCMEmNF9yRMp-hYFphSQPjuwgZTQa-4Rh0,84642 +transformers/models/pegasus/__init__.py,sha256=4b7vCYJfIWUPuKrbcBGTG7LtobUdZ5ZjeQhloScTrXs,1160 +transformers/models/pegasus/__pycache__/__init__.cpython-310.pyc,, +transformers/models/pegasus/__pycache__/configuration_pegasus.cpython-310.pyc,, +transformers/models/pegasus/__pycache__/modeling_flax_pegasus.cpython-310.pyc,, +transformers/models/pegasus/__pycache__/modeling_pegasus.cpython-310.pyc,, +transformers/models/pegasus/__pycache__/modeling_tf_pegasus.cpython-310.pyc,, +transformers/models/pegasus/__pycache__/tokenization_pegasus.cpython-310.pyc,, +transformers/models/pegasus/__pycache__/tokenization_pegasus_fast.cpython-310.pyc,, +transformers/models/pegasus/configuration_pegasus.py,sha256=78-WMVFtUhigUXXJ4PabYJA8S3VpfQW9-2NcM5t8Hlo,7517 +transformers/models/pegasus/modeling_flax_pegasus.py,sha256=Rkc0964DKuqgYPMmzKNcZx4_g3hOqV8kD5udpqy-wRE,66161 +transformers/models/pegasus/modeling_pegasus.py,sha256=TpgN32E98jPHuDqQUd-JTOdcYRjiiuPSGwN2-aVmi0w,77934 +transformers/models/pegasus/modeling_tf_pegasus.py,sha256=_WR-vfHxUBGzBUJVEsw7pajamDJQAeZZYsMvEU_HV_4,74149 +transformers/models/pegasus/tokenization_pegasus.py,sha256=Mlf8ZdllYQGJMktD0ci2aD46NczeKcuw-NZNgt9bkgw,13231 +transformers/models/pegasus/tokenization_pegasus_fast.py,sha256=c6xFEwXqtpScjYMasosqrAlwJMsdJCC_Sjp_BYniK7s,9833 +transformers/models/pegasus_x/__init__.py,sha256=qSLaqKRA1upZOobapHW5MjSZvIEzf-ij-ZmY1VGzqaE,999 +transformers/models/pegasus_x/__pycache__/__init__.cpython-310.pyc,, +transformers/models/pegasus_x/__pycache__/configuration_pegasus_x.cpython-310.pyc,, +transformers/models/pegasus_x/__pycache__/modeling_pegasus_x.cpython-310.pyc,, +transformers/models/pegasus_x/configuration_pegasus_x.py,sha256=RasKHKP1N0ZEvsl81J2Y3jhNAJo0zplnAKI2ZqYJdv4,8132 +transformers/models/pegasus_x/modeling_pegasus_x.py,sha256=30KSzN9JuE7Sbpi6uvBgd8lWGCvV4v1UWf351GcwrjE,79137 +transformers/models/perceiver/__init__.py,sha256=LKUlUJfZGRC1jU6TNkG-4kNy8aIeHIqvAnwLI_33AVY,1186 +transformers/models/perceiver/__pycache__/__init__.cpython-310.pyc,, +transformers/models/perceiver/__pycache__/configuration_perceiver.cpython-310.pyc,, +transformers/models/perceiver/__pycache__/feature_extraction_perceiver.cpython-310.pyc,, +transformers/models/perceiver/__pycache__/image_processing_perceiver.cpython-310.pyc,, +transformers/models/perceiver/__pycache__/image_processing_perceiver_fast.cpython-310.pyc,, +transformers/models/perceiver/__pycache__/modeling_perceiver.cpython-310.pyc,, +transformers/models/perceiver/__pycache__/tokenization_perceiver.cpython-310.pyc,, +transformers/models/perceiver/configuration_perceiver.py,sha256=0h5NCC6iJiA_cOv9gvcpxNgiFc0r25Rvv7PIHh1jp6Q,12236 +transformers/models/perceiver/feature_extraction_perceiver.py,sha256=JK3Y4won5macefR13tx-zdUF_TaHE4RrJllJyYzIhWU,1324 +transformers/models/perceiver/image_processing_perceiver.py,sha256=3Ise4hPNUhsVyIXIUGqKz0KZ1vG1melYTP2AovLJ-Po,17591 +transformers/models/perceiver/image_processing_perceiver_fast.py,sha256=ePz69sn2_CkJmkDJlAnyg9-2ItD_gn3WY4Bc5qPMiPA,5045 +transformers/models/perceiver/modeling_perceiver.py,sha256=8-u-KZuhu7LD5uFA4vaOXHFr2fz5SWcAMhu0Q3pz2K8,137484 +transformers/models/perceiver/tokenization_perceiver.py,sha256=9cCQTtfKJUzwWoUQ3YEBdsh9RrJgsL4N2kxA8fPQuqc,8034 +transformers/models/perception_lm/__init__.py,sha256=RVEjQWlzsHJm3D-3JXLThzBjJLSCMpvFslQMIkvRKiA,1106 +transformers/models/perception_lm/__pycache__/__init__.cpython-310.pyc,, +transformers/models/perception_lm/__pycache__/configuration_perception_lm.cpython-310.pyc,, +transformers/models/perception_lm/__pycache__/image_processing_perception_lm_fast.cpython-310.pyc,, +transformers/models/perception_lm/__pycache__/modeling_perception_lm.cpython-310.pyc,, +transformers/models/perception_lm/__pycache__/modular_perception_lm.cpython-310.pyc,, +transformers/models/perception_lm/__pycache__/processing_perception_lm.cpython-310.pyc,, +transformers/models/perception_lm/__pycache__/video_processing_perception_lm.cpython-310.pyc,, +transformers/models/perception_lm/configuration_perception_lm.py,sha256=ZrA3gpUzZJf3POf1aLhGMU9mVwC5IreP5wOrvvVwqCQ,3888 +transformers/models/perception_lm/image_processing_perception_lm_fast.py,sha256=zw3SaD_dQrx48y98RONJlzInByn1YAADByqIfBPMtU4,13971 +transformers/models/perception_lm/modeling_perception_lm.py,sha256=7dOFsqbr-JdLqtcZoyse8WCyYYM3Kd4ZQXJH-zZ9taM,21281 +transformers/models/perception_lm/modular_perception_lm.py,sha256=ajMCR1lvIHeC58c_nhhhyAbk9-SNvvruFJNIqzqEaXs,18890 +transformers/models/perception_lm/processing_perception_lm.py,sha256=Nx9FdDxaa4RaaOj5EYO43qM9RHOr-zTZ0h8tVPYIeuQ,11407 +transformers/models/perception_lm/video_processing_perception_lm.py,sha256=TOkzfeCdZRTUIQlqojwEOMNkZKpDj25PmNB1ocUJzZw,1575 +transformers/models/persimmon/__init__.py,sha256=T1WqyE78N2TO74u9a9QdRIGaMowYqP6vWv8KhPojkLg,999 +transformers/models/persimmon/__pycache__/__init__.cpython-310.pyc,, +transformers/models/persimmon/__pycache__/configuration_persimmon.cpython-310.pyc,, +transformers/models/persimmon/__pycache__/modeling_persimmon.cpython-310.pyc,, +transformers/models/persimmon/configuration_persimmon.py,sha256=6KV-r-B5sqC9d2Ybzind_YDxqnM0lITfbH5zPqGg6K4,9149 +transformers/models/persimmon/modeling_persimmon.py,sha256=BKE9-S7HM4P8Y3zxSNrWj7PkkG6Jm7mibpoEf6X7lKI,33528 +transformers/models/phi/__init__.py,sha256=4DUgmUqGKcGXxzTrxUVGcacZ43uv3SzXsOV_Ke6oeGg,1006 +transformers/models/phi/__pycache__/__init__.cpython-310.pyc,, +transformers/models/phi/__pycache__/configuration_phi.cpython-310.pyc,, +transformers/models/phi/__pycache__/modeling_phi.cpython-310.pyc,, +transformers/models/phi/__pycache__/modular_phi.cpython-310.pyc,, +transformers/models/phi/configuration_phi.py,sha256=xYk2xva2KXG5k_Dk8ND3JObDjcfPuklUdSkNIT0DYJ8,11172 +transformers/models/phi/modeling_phi.py,sha256=GFPVx4EHr12LylOXMEUezAYKkQY6hHssCswuso4c_08,22131 +transformers/models/phi/modular_phi.py,sha256=v9h_mx4Z4ZIF_czVLBUGGgnfwPL3piLR5jGqL97OJa4,11618 +transformers/models/phi3/__init__.py,sha256=dxyO-jIh0yB6t2Dzs173aRrEnTceVMIYIkg6JxIeyWs,989 +transformers/models/phi3/__pycache__/__init__.cpython-310.pyc,, +transformers/models/phi3/__pycache__/configuration_phi3.cpython-310.pyc,, +transformers/models/phi3/__pycache__/modeling_phi3.cpython-310.pyc,, +transformers/models/phi3/__pycache__/modular_phi3.cpython-310.pyc,, +transformers/models/phi3/configuration_phi3.py,sha256=Yamd8nkyPdC_AtCPA9w0tjSEjaBmxgGKvxA0n0FIIAc,11573 +transformers/models/phi3/modeling_phi3.py,sha256=Oy4ZuDltRyxrrSzIbRCVDDSqWhPevNkojaqO4Cb3w70,23278 +transformers/models/phi3/modular_phi3.py,sha256=mWO0wTSb-MHy6xVvECvFOO-ia331UjLV6BhnK-7fZXE,11132 +transformers/models/phi4_multimodal/__init__.py,sha256=EqoKUvkh9f14qg07g-4MLclztlyiyLfN2qqEp3RGp2w,1170 +transformers/models/phi4_multimodal/__pycache__/__init__.cpython-310.pyc,, +transformers/models/phi4_multimodal/__pycache__/configuration_phi4_multimodal.cpython-310.pyc,, +transformers/models/phi4_multimodal/__pycache__/feature_extraction_phi4_multimodal.cpython-310.pyc,, +transformers/models/phi4_multimodal/__pycache__/image_processing_phi4_multimodal_fast.cpython-310.pyc,, +transformers/models/phi4_multimodal/__pycache__/modeling_phi4_multimodal.cpython-310.pyc,, +transformers/models/phi4_multimodal/__pycache__/modular_phi4_multimodal.cpython-310.pyc,, +transformers/models/phi4_multimodal/__pycache__/processing_phi4_multimodal.cpython-310.pyc,, +transformers/models/phi4_multimodal/configuration_phi4_multimodal.py,sha256=SaLExfxMFf8BaAQCtrmmqbCwpx_mQuEAwhMuKJ5Wcyo,24363 +transformers/models/phi4_multimodal/feature_extraction_phi4_multimodal.py,sha256=T1R76IxQCkMh-_jeP8zrBecywvbDnG5hNt_VJAKs2nk,13413 +transformers/models/phi4_multimodal/image_processing_phi4_multimodal_fast.py,sha256=_E8MwzhMegAXyUxzVhV8HESmNA8RCIUA3GSpEzJLXow,10497 +transformers/models/phi4_multimodal/modeling_phi4_multimodal.py,sha256=LI9RNO4Wy-iHSY4Wgc2yaGlwr70urA0cSoNogF-48c4,79499 +transformers/models/phi4_multimodal/modular_phi4_multimodal.py,sha256=R1s5BsOsYU-mLsGzTc8JFN2BOXLKm9yI1IWqVQuTYHw,77180 +transformers/models/phi4_multimodal/processing_phi4_multimodal.py,sha256=6N61sgrHtffBZSLsWsY6fYBgG0EYIfE4cwbuuKElsO4,8107 +transformers/models/phimoe/__init__.py,sha256=wGasPysu0EH_q0QGaZmXqQL57GxfZn8NTsvB2I6U2ro,1013 +transformers/models/phimoe/__pycache__/__init__.cpython-310.pyc,, +transformers/models/phimoe/__pycache__/configuration_phimoe.cpython-310.pyc,, +transformers/models/phimoe/__pycache__/modeling_phimoe.cpython-310.pyc,, +transformers/models/phimoe/configuration_phimoe.py,sha256=bmX2NBq89oFKQ5PnFmkcknw5dT6A9w2D9psS8jubltw,10238 +transformers/models/phimoe/modeling_phimoe.py,sha256=zh6xRbDkvqbFwpWWh1PCLlbs_isWPcH3KDzlvN6CYw8,59885 +transformers/models/phobert/__init__.py,sha256=mau-2HIOzSk8qGIhxivVBPPYTx3hhdgoKPtnptDF38M,958 +transformers/models/phobert/__pycache__/__init__.cpython-310.pyc,, +transformers/models/phobert/__pycache__/tokenization_phobert.cpython-310.pyc,, +transformers/models/phobert/tokenization_phobert.py,sha256=0ItqQt-YiRb44Wqyp6e59UQOc_wSmErRFAziorm_w6o,13111 +transformers/models/pix2struct/__init__.py,sha256=ivncogrVjZZ6ag6FYHJ0XqyCMJYbsCYlh5boqxe09Yo,1089 +transformers/models/pix2struct/__pycache__/__init__.cpython-310.pyc,, +transformers/models/pix2struct/__pycache__/configuration_pix2struct.cpython-310.pyc,, +transformers/models/pix2struct/__pycache__/image_processing_pix2struct.cpython-310.pyc,, +transformers/models/pix2struct/__pycache__/modeling_pix2struct.cpython-310.pyc,, +transformers/models/pix2struct/__pycache__/processing_pix2struct.cpython-310.pyc,, +transformers/models/pix2struct/configuration_pix2struct.py,sha256=eHg19KzSW5bh2dVTgMH7vhZPZu2yg6iEpy8DNO6bk8U,15370 +transformers/models/pix2struct/image_processing_pix2struct.py,sha256=WZ9JONvTc8PYZMvPJ2JYY7b3OFUws47VTwFi4iwYpHE,19799 +transformers/models/pix2struct/modeling_pix2struct.py,sha256=P_bq-C7wvfFlx7pWIw4ChVPctobvrzXJgIcClInfwwQ,72168 +transformers/models/pix2struct/processing_pix2struct.py,sha256=d_oNjxTHgeu06zbPe5ZjHUvcignufU4Wql8XBhvvgwk,5677 +transformers/models/pixtral/__init__.py,sha256=WKCxuWpCeTYsYSaTH1XnUcGkIHEx5BIIXwwwqG_E83s,1126 +transformers/models/pixtral/__pycache__/__init__.cpython-310.pyc,, +transformers/models/pixtral/__pycache__/configuration_pixtral.cpython-310.pyc,, +transformers/models/pixtral/__pycache__/image_processing_pixtral.cpython-310.pyc,, +transformers/models/pixtral/__pycache__/image_processing_pixtral_fast.cpython-310.pyc,, +transformers/models/pixtral/__pycache__/modeling_pixtral.cpython-310.pyc,, +transformers/models/pixtral/__pycache__/processing_pixtral.cpython-310.pyc,, +transformers/models/pixtral/configuration_pixtral.py,sha256=86cY74VW7J8XqU1JbvpxLqOXnnzoPh7I_9zja8j3Wng,4237 +transformers/models/pixtral/image_processing_pixtral.py,sha256=LBgaL_2tIZxryRkONb8iS9c5Fl6R1DEgTgPJkPDkF10,22081 +transformers/models/pixtral/image_processing_pixtral_fast.py,sha256=ypfQ2Bi-y3wkCovLvXlGL5hhKSPXe66eCCTcnzzShIU,7851 +transformers/models/pixtral/modeling_pixtral.py,sha256=QMwr3lbVL0SE3MdU3sj04S49LPojvbj0-5zXFx1TQFE,20982 +transformers/models/pixtral/processing_pixtral.py,sha256=dX0I3wGEgrD7gXndAK6Qa1OevpD_ppcBIKfxDZmhfsA,11896 +transformers/models/plbart/__init__.py,sha256=jmP857QTG7jGfr9n0qK3TB_1-hdVDD1ajtJvP6C7FIw,1032 +transformers/models/plbart/__pycache__/__init__.cpython-310.pyc,, +transformers/models/plbart/__pycache__/configuration_plbart.cpython-310.pyc,, +transformers/models/plbart/__pycache__/modeling_plbart.cpython-310.pyc,, +transformers/models/plbart/__pycache__/modular_plbart.cpython-310.pyc,, +transformers/models/plbart/__pycache__/tokenization_plbart.cpython-310.pyc,, +transformers/models/plbart/configuration_plbart.py,sha256=N3T4lbCCGP3nYNIHYah1yMvDy1FiJqgpdHIAKJFfcTQ,8621 +transformers/models/plbart/modeling_plbart.py,sha256=RUbyPW9QC03iF0lyIjd4ByIU6IScd9GLPl2U4e2ydYE,80652 +transformers/models/plbart/modular_plbart.py,sha256=_7kGkI9nakn2y-itDsNamyT8qtjNG_2bnbNb4lN0LkY,31220 +transformers/models/plbart/tokenization_plbart.py,sha256=ytGwNtPfgHXoKdK85Qm1fz68tBU-qbrYwdMLd96d2Xs,18910 +transformers/models/poolformer/__init__.py,sha256=FgSXHIGeF8uz-Ye67HSRQefjounknzaqm0ZCOiMj4zo,1149 +transformers/models/poolformer/__pycache__/__init__.cpython-310.pyc,, +transformers/models/poolformer/__pycache__/configuration_poolformer.cpython-310.pyc,, +transformers/models/poolformer/__pycache__/feature_extraction_poolformer.cpython-310.pyc,, +transformers/models/poolformer/__pycache__/image_processing_poolformer.cpython-310.pyc,, +transformers/models/poolformer/__pycache__/image_processing_poolformer_fast.cpython-310.pyc,, +transformers/models/poolformer/__pycache__/modeling_poolformer.cpython-310.pyc,, +transformers/models/poolformer/configuration_poolformer.py,sha256=mU4fQSyfdSwP-vB3UIAkNuYI6wyqhxu2R3SOupiY2pc,5641 +transformers/models/poolformer/feature_extraction_poolformer.py,sha256=8NBHTCScDnuQAjwNVL1Mxs4xllp9FnJCSonL_ceF_lg,1332 +transformers/models/poolformer/image_processing_poolformer.py,sha256=74zcQtTYc9H2wxlDNEpDyAdyMVEXRrgYZ87keKgLbJ4,17942 +transformers/models/poolformer/image_processing_poolformer_fast.py,sha256=g802FsnPFcYBaiNRx0WTfN98vi-HDVwBLWuIfOvwGdA,10315 +transformers/models/poolformer/modeling_poolformer.py,sha256=x8Yy0-jihy_4u9M0PWWBheEkNbd6E3OeSzOtfbwsV9o,14839 +transformers/models/pop2piano/__init__.py,sha256=I2PPcFi-p0X5py7dLqobymv3E9g-mUv1QRn0luyPlIk,999 +transformers/models/pop2piano/__pycache__/__init__.cpython-310.pyc,, +transformers/models/pop2piano/__pycache__/configuration_pop2piano.cpython-310.pyc,, +transformers/models/pop2piano/__pycache__/feature_extraction_pop2piano.cpython-310.pyc,, +transformers/models/pop2piano/__pycache__/modeling_pop2piano.cpython-310.pyc,, +transformers/models/pop2piano/__pycache__/processing_pop2piano.cpython-310.pyc,, +transformers/models/pop2piano/__pycache__/tokenization_pop2piano.cpython-310.pyc,, +transformers/models/pop2piano/configuration_pop2piano.py,sha256=dd4YFUQuLykahr1WPmw096ZXZEXpRMkpIrpmeP5JRN0,5951 +transformers/models/pop2piano/feature_extraction_pop2piano.py,sha256=DQb7Y7mxkvYfwDbZQ-CQYzdOQ9mX17D-lhcsMMW4538,19974 +transformers/models/pop2piano/modeling_pop2piano.py,sha256=jg4y0buKJWSS-8x9jjEyvfPTSfwGpDxdY_oVqP8LeBg,63188 +transformers/models/pop2piano/processing_pop2piano.py,sha256=Fdvmle3D5Clhgx6RMjXE2RknTvcNahWWIUo8PltF50c,5399 +transformers/models/pop2piano/tokenization_pop2piano.py,sha256=ntxNcv0GFLzDpy6eHDCqDsjD8GXKiQUxmgXZiE3iIoE,32803 +transformers/models/prompt_depth_anything/__init__.py,sha256=KjyIVKAGtL4B0RRW4s5WyyFNmvimW_Cv36LkiyuPbGA,1333 +transformers/models/prompt_depth_anything/__pycache__/__init__.cpython-310.pyc,, +transformers/models/prompt_depth_anything/__pycache__/configuration_prompt_depth_anything.cpython-310.pyc,, +transformers/models/prompt_depth_anything/__pycache__/image_processing_prompt_depth_anything.cpython-310.pyc,, +transformers/models/prompt_depth_anything/__pycache__/image_processing_prompt_depth_anything_fast.cpython-310.pyc,, +transformers/models/prompt_depth_anything/__pycache__/modeling_prompt_depth_anything.cpython-310.pyc,, +transformers/models/prompt_depth_anything/__pycache__/modular_prompt_depth_anything.cpython-310.pyc,, +transformers/models/prompt_depth_anything/configuration_prompt_depth_anything.py,sha256=vL-HwgUR7moy5eBRTH0t1qPDduSQ40J9F6i9rpNZG-Y,9062 +transformers/models/prompt_depth_anything/image_processing_prompt_depth_anything.py,sha256=HdE7-txaofl5a9NIhsoH76oSCF2wLJ7Pay5_a9VN15k,24748 +transformers/models/prompt_depth_anything/image_processing_prompt_depth_anything_fast.py,sha256=uCI3WpEHXNBv_rdY2XOTKU48neu7ZFNUwj8TX1CJ4JU,14136 +transformers/models/prompt_depth_anything/modeling_prompt_depth_anything.py,sha256=kpI2MyI32F-vI3I412QykOXfNIJHBaqpVJ13uubaaOg,20407 +transformers/models/prompt_depth_anything/modular_prompt_depth_anything.py,sha256=wP11VynfmVInYHvH4GeJDd1ELl7C7nj8evmivgntkDQ,13755 +transformers/models/prophetnet/__init__.py,sha256=TYI21JDlj449kTgKAOtUBpuxVv5L_I70CDjofSZ627M,1044 +transformers/models/prophetnet/__pycache__/__init__.cpython-310.pyc,, +transformers/models/prophetnet/__pycache__/configuration_prophetnet.cpython-310.pyc,, +transformers/models/prophetnet/__pycache__/modeling_prophetnet.cpython-310.pyc,, +transformers/models/prophetnet/__pycache__/tokenization_prophetnet.cpython-310.pyc,, +transformers/models/prophetnet/configuration_prophetnet.py,sha256=XPcB7itQbCqMzONUd3-4Ag6wtBHC4f3-jWb6OUTyxoQ,8893 +transformers/models/prophetnet/modeling_prophetnet.py,sha256=uwcgn6o4uepCjsGgEbEm28zkzbQvcvD4bBv-fk8QvGo,97193 +transformers/models/prophetnet/tokenization_prophetnet.py,sha256=JsP4EwckyDeORtcAsVlrNlfLXo_YriRbiZwLcKEzFDI,20154 +transformers/models/pvt/__init__.py,sha256=-4ajQRrz2cTp2czAd6D23yxShatfUpHzZrHyyLRsku0,1072 +transformers/models/pvt/__pycache__/__init__.cpython-310.pyc,, +transformers/models/pvt/__pycache__/configuration_pvt.cpython-310.pyc,, +transformers/models/pvt/__pycache__/image_processing_pvt.cpython-310.pyc,, +transformers/models/pvt/__pycache__/image_processing_pvt_fast.cpython-310.pyc,, +transformers/models/pvt/__pycache__/modeling_pvt.cpython-310.pyc,, +transformers/models/pvt/configuration_pvt.py,sha256=NivJRKXgMQ-F4SOqf7Z3nFNWxJKdsV6iqJ2YdVvrtj0,6983 +transformers/models/pvt/image_processing_pvt.py,sha256=-A6Q9_jrqBhiVIi3Mh3bNJXOxXLzOXhI_qtzVqL5zVE,13882 +transformers/models/pvt/image_processing_pvt_fast.py,sha256=C2hhtB4aUqbLdVawDaeubuef9fSkC-oNT0c4WJK8Ja0,1341 +transformers/models/pvt/modeling_pvt.py,sha256=ir6AztE-05jFjPlrJIhkCBObsxpz7OJ-s92Y2ymBfaw,24686 +transformers/models/pvt_v2/__init__.py,sha256=LkmqeLd7cZGKTFX_2d9_jU0sj_bDlML042kr_vMJTLw,993 +transformers/models/pvt_v2/__pycache__/__init__.cpython-310.pyc,, +transformers/models/pvt_v2/__pycache__/configuration_pvt_v2.cpython-310.pyc,, +transformers/models/pvt_v2/__pycache__/modeling_pvt_v2.cpython-310.pyc,, +transformers/models/pvt_v2/configuration_pvt_v2.py,sha256=7LMMRQUgb_xYvWFkGtLxA6k_a10cBFUtSx8vejJup38,7978 +transformers/models/pvt_v2/modeling_pvt_v2.py,sha256=bTon7gNl2FolGIG5X_N6CK18vldIHUFd3Sw72CBO44s,25365 +transformers/models/qwen2/__init__.py,sha256=e49oEzErXujE0UVl_q_agf5XHzHES4vV2kLwmqdk2kg,1095 +transformers/models/qwen2/__pycache__/__init__.cpython-310.pyc,, +transformers/models/qwen2/__pycache__/configuration_qwen2.cpython-310.pyc,, +transformers/models/qwen2/__pycache__/modeling_qwen2.cpython-310.pyc,, +transformers/models/qwen2/__pycache__/modular_qwen2.cpython-310.pyc,, +transformers/models/qwen2/__pycache__/tokenization_qwen2.cpython-310.pyc,, +transformers/models/qwen2/__pycache__/tokenization_qwen2_fast.cpython-310.pyc,, +transformers/models/qwen2/configuration_qwen2.py,sha256=K50KA_7u9zSuRR7uOBrRXe78AqtLi5V9h4A_tYlOm9M,11400 +transformers/models/qwen2/modeling_qwen2.py,sha256=pZ-gZSQic2H7QBuvTRdxJKJ67BRrwB7JMSNamrurF8s,21621 +transformers/models/qwen2/modular_qwen2.py,sha256=btP3seJzGwxkz7flduaXI8yGElide3Y_o2K_gAdjRlM,9498 +transformers/models/qwen2/tokenization_qwen2.py,sha256=I_BWl_yvJv5eMoq69STwEFEKK59LouLtydygpAFaCaI,13935 +transformers/models/qwen2/tokenization_qwen2_fast.py,sha256=ECWjuGUmKDvYakR_D-LZkdCXdbMtP9zCM8nkR7BhEEk,5210 +transformers/models/qwen2_5_omni/__init__.py,sha256=YEDAlOoWmhkZ4L6lxmlVqVhe5A0P6aVSJNSziEFSN4E,1071 +transformers/models/qwen2_5_omni/__pycache__/__init__.cpython-310.pyc,, +transformers/models/qwen2_5_omni/__pycache__/configuration_qwen2_5_omni.cpython-310.pyc,, +transformers/models/qwen2_5_omni/__pycache__/modeling_qwen2_5_omni.cpython-310.pyc,, +transformers/models/qwen2_5_omni/__pycache__/modular_qwen2_5_omni.cpython-310.pyc,, +transformers/models/qwen2_5_omni/__pycache__/processing_qwen2_5_omni.cpython-310.pyc,, +transformers/models/qwen2_5_omni/configuration_qwen2_5_omni.py,sha256=h4nJZjnS_Jed3OqGzEVH56tEvkx0JsrK4I36_hkMDsY,52838 +transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py,sha256=gwhVB40MCxWaRwQfiUKUn9Gm79OcYhJ8E4fMO4QFj6M,177393 +transformers/models/qwen2_5_omni/modular_qwen2_5_omni.py,sha256=jhG7Cdm3bRkHBOG2pz2gERVj_DN41MJ5z9ShOXEbf1s,191129 +transformers/models/qwen2_5_omni/processing_qwen2_5_omni.py,sha256=CEBbeuYqjcQSqMl1cq2dFi0LldzJ1IlS25c3g_XilFg,17110 +transformers/models/qwen2_5_vl/__init__.py,sha256=8-dsgLIeeE3n90n6F0XOu-tBZ-80Wotz89pjZi5GqjQ,1065 +transformers/models/qwen2_5_vl/__pycache__/__init__.cpython-310.pyc,, +transformers/models/qwen2_5_vl/__pycache__/configuration_qwen2_5_vl.cpython-310.pyc,, +transformers/models/qwen2_5_vl/__pycache__/modeling_qwen2_5_vl.cpython-310.pyc,, +transformers/models/qwen2_5_vl/__pycache__/modular_qwen2_5_vl.cpython-310.pyc,, +transformers/models/qwen2_5_vl/__pycache__/processing_qwen2_5_vl.cpython-310.pyc,, +transformers/models/qwen2_5_vl/configuration_qwen2_5_vl.py,sha256=ckFVe5PFCn6BM5PpPvL0V3OvLq-sn1f1beCYaS6pFQA,18562 +transformers/models/qwen2_5_vl/modeling_qwen2_5_vl.py,sha256=9QUVIzABRfZt4IB2XAa9gIA1DBVpLAltLDjnP-nQMJk,82355 +transformers/models/qwen2_5_vl/modular_qwen2_5_vl.py,sha256=8T5rkMDA9BKurCAWBm5l57ktOWxBWYgM3QSRSWmkDog,49601 +transformers/models/qwen2_5_vl/processing_qwen2_5_vl.py,sha256=aogQe4UyDKnuEVRzFTDbWEugSKEq_x66sve9x3BiGE0,14907 +transformers/models/qwen2_audio/__init__.py,sha256=KaUmP3FK3GdeWvbunzyp1QjBki0USS4E80NlvhaJ3D8,1045 +transformers/models/qwen2_audio/__pycache__/__init__.cpython-310.pyc,, +transformers/models/qwen2_audio/__pycache__/configuration_qwen2_audio.cpython-310.pyc,, +transformers/models/qwen2_audio/__pycache__/modeling_qwen2_audio.cpython-310.pyc,, +transformers/models/qwen2_audio/__pycache__/processing_qwen2_audio.cpython-310.pyc,, +transformers/models/qwen2_audio/configuration_qwen2_audio.py,sha256=U37sA7O8GvbrlFOwXgBSvqu28Kz2uKJORqjthqH8UnE,8673 +transformers/models/qwen2_audio/modeling_qwen2_audio.py,sha256=-gMWHKbcAT5rILYmNVypl9kkWEiKOVYKRY6waW6poUQ,41729 +transformers/models/qwen2_audio/processing_qwen2_audio.py,sha256=4Q38fvhIEKQLIE435h7c9bGlCAi3d5qh3CU5OTMlwas,11312 +transformers/models/qwen2_moe/__init__.py,sha256=TZM20WtUr1UyV-hDDgq5B-qFT4aUulMpjWwSUNdUs2w,999 +transformers/models/qwen2_moe/__pycache__/__init__.cpython-310.pyc,, +transformers/models/qwen2_moe/__pycache__/configuration_qwen2_moe.cpython-310.pyc,, +transformers/models/qwen2_moe/__pycache__/modeling_qwen2_moe.cpython-310.pyc,, +transformers/models/qwen2_moe/configuration_qwen2_moe.py,sha256=3BBfpz3Pu3DuaCuTtWaFdY_JK5QrLVWrW-Ri-Ky205I,13228 +transformers/models/qwen2_moe/modeling_qwen2_moe.py,sha256=LGeqEeHF9qDHi0qCanRAqV5W1FbQgauvXvcqsvYetrg,54846 +transformers/models/qwen2_vl/__init__.py,sha256=MtNDD6sEQws-WTLwPxUL5UNd-UyDPrDh8yWzIAsRp-U,1131 +transformers/models/qwen2_vl/__pycache__/__init__.cpython-310.pyc,, +transformers/models/qwen2_vl/__pycache__/configuration_qwen2_vl.cpython-310.pyc,, +transformers/models/qwen2_vl/__pycache__/image_processing_qwen2_vl.cpython-310.pyc,, +transformers/models/qwen2_vl/__pycache__/image_processing_qwen2_vl_fast.cpython-310.pyc,, +transformers/models/qwen2_vl/__pycache__/modeling_qwen2_vl.cpython-310.pyc,, +transformers/models/qwen2_vl/__pycache__/processing_qwen2_vl.cpython-310.pyc,, +transformers/models/qwen2_vl/__pycache__/video_processing_qwen2_vl.cpython-310.pyc,, +transformers/models/qwen2_vl/configuration_qwen2_vl.py,sha256=BoXLC18Nb_w5zLRduzbGyfIaBZ3tqKRuNUUroeC4qrA,17192 +transformers/models/qwen2_vl/image_processing_qwen2_vl.py,sha256=eCCg_MoQfnVgXgjZt3QoXKKwMW-Fe8AiXHeXlHBez08,26381 +transformers/models/qwen2_vl/image_processing_qwen2_vl_fast.py,sha256=Cb-psX33w_DGFZvDQAjuUPIdJHLNW65-XCG6HKE6Qjw,12723 +transformers/models/qwen2_vl/modeling_qwen2_vl.py,sha256=8y_bho4BRBTzvKL8yOcWX8nkm1fpRptPOvmiQ2QK4Ps,74168 +transformers/models/qwen2_vl/processing_qwen2_vl.py,sha256=hjoTvQrQDX1ADMe7q0RnSF47kdMoGbYBvMRX35HSeOU,12801 +transformers/models/qwen2_vl/video_processing_qwen2_vl.py,sha256=MwNHWyxwShfI0CVu3jx54_8J-kNXW_kMfeQbcpWHhXk,13813 +transformers/models/qwen3/__init__.py,sha256=5JU8uO9x0AmJ-YjY36MxtbMKT_B38dLJkrnAwLyjcTY,1014 +transformers/models/qwen3/__pycache__/__init__.cpython-310.pyc,, +transformers/models/qwen3/__pycache__/configuration_qwen3.cpython-310.pyc,, +transformers/models/qwen3/__pycache__/modeling_qwen3.cpython-310.pyc,, +transformers/models/qwen3/__pycache__/modular_qwen3.cpython-310.pyc,, +transformers/models/qwen3/configuration_qwen3.py,sha256=J4Y-lxj9vImfLQ5WdiHk09NtjcUAwdVLSdukJC0I0r0,11810 +transformers/models/qwen3/modeling_qwen3.py,sha256=S5XDcf0m1AxpCD2rNqwer9jPgrQVoLuCcnUJfFrSMFs,23067 +transformers/models/qwen3/modular_qwen3.py,sha256=WA_tIiC8UOyrxynwkbPQl-a8zRTd6bPbVkD5jK9irVs,6199 +transformers/models/qwen3_moe/__init__.py,sha256=q5WfIniJecmOju3Lhy277H3Puu7viwc9vUhUWen3UZY,999 +transformers/models/qwen3_moe/__pycache__/__init__.cpython-310.pyc,, +transformers/models/qwen3_moe/__pycache__/configuration_qwen3_moe.cpython-310.pyc,, +transformers/models/qwen3_moe/__pycache__/modeling_qwen3_moe.cpython-310.pyc,, +transformers/models/qwen3_moe/__pycache__/modular_qwen3_moe.cpython-310.pyc,, +transformers/models/qwen3_moe/configuration_qwen3_moe.py,sha256=DQzCSiwo1SfPrEUr_wJV14N8qM7iVAIuhGDIt7BZPHw,12862 +transformers/models/qwen3_moe/modeling_qwen3_moe.py,sha256=PdL5fCHyD_huokWs9uzdj81rVaLKyCtcXehs3wJEfv8,32144 +transformers/models/qwen3_moe/modular_qwen3_moe.py,sha256=tSjWubuVGbJdWoYbvrTBV2Wh2agahUdIDXC0FiTmiqY,12091 +transformers/models/qwen3_next/__init__.py,sha256=PuPvF5xcEfBxUKjqiZaWCiHeDeKuTmNdfuI6wvb-cbI,1001 +transformers/models/qwen3_next/__pycache__/__init__.cpython-310.pyc,, +transformers/models/qwen3_next/__pycache__/configuration_qwen3_next.cpython-310.pyc,, +transformers/models/qwen3_next/__pycache__/modeling_qwen3_next.cpython-310.pyc,, +transformers/models/qwen3_next/__pycache__/modular_qwen3_next.cpython-310.pyc,, +transformers/models/qwen3_next/configuration_qwen3_next.py,sha256=yZ0mSSnmJ2A9HkBPdrAsmh832ORtrlwkK5qRfd5VxHE,14521 +transformers/models/qwen3_next/modeling_qwen3_next.py,sha256=zo3TMIlee1iadz46oVdPP2sXSa0FLQtV78lKDchQLdQ,56301 +transformers/models/qwen3_next/modular_qwen3_next.py,sha256=_xmmzBYuNRihzloeRRzrB4fbWzhE1RlkbReB3NFX2lo,36540 +transformers/models/qwen3_omni_moe/__init__.py,sha256=6xE3okskjamaUt4t3k8qJeJWbTPvLH7MfEjmtKtCC3I,1077 +transformers/models/qwen3_omni_moe/__pycache__/__init__.cpython-310.pyc,, +transformers/models/qwen3_omni_moe/__pycache__/configuration_qwen3_omni_moe.cpython-310.pyc,, +transformers/models/qwen3_omni_moe/__pycache__/modeling_qwen3_omni_moe.cpython-310.pyc,, +transformers/models/qwen3_omni_moe/__pycache__/modular_qwen3_omni_moe.cpython-310.pyc,, +transformers/models/qwen3_omni_moe/__pycache__/processing_qwen3_omni_moe.cpython-310.pyc,, +transformers/models/qwen3_omni_moe/configuration_qwen3_omni_moe.py,sha256=d5v0uBZCVEjV06L_pXko0ce3wQ4tZrCTcfzq7mK8v4k,64262 +transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py,sha256=gJ6utNQMsOWZZahbX4XdwH6at7bNroSXLHEfjNrewpY,182410 +transformers/models/qwen3_omni_moe/modular_qwen3_omni_moe.py,sha256=0-7EiaVhM_dX6C3WEoTSA3-ZxE4q6Vw1Su2TEFjF92Y,118937 +transformers/models/qwen3_omni_moe/processing_qwen3_omni_moe.py,sha256=mnbS3YQij9_lIAgI_kbR-9eIRFCUS17h8_6KiwPK2D8,17321 +transformers/models/qwen3_vl/__init__.py,sha256=abVaeHwwKgL-3gVI3c5PSZfroZlU4TxEKXweDd75BXQ,1104 +transformers/models/qwen3_vl/__pycache__/__init__.cpython-310.pyc,, +transformers/models/qwen3_vl/__pycache__/configuration_qwen3_vl.cpython-310.pyc,, +transformers/models/qwen3_vl/__pycache__/modeling_qwen3_vl.cpython-310.pyc,, +transformers/models/qwen3_vl/__pycache__/modular_qwen3_vl.cpython-310.pyc,, +transformers/models/qwen3_vl/__pycache__/processing_qwen3_vl.cpython-310.pyc,, +transformers/models/qwen3_vl/__pycache__/video_processing_qwen3_vl.cpython-310.pyc,, +transformers/models/qwen3_vl/configuration_qwen3_vl.py,sha256=F3_QpNwbCDB8CMpyzya419wCirarWXW_ZQ_BSrgTKoM,14827 +transformers/models/qwen3_vl/modeling_qwen3_vl.py,sha256=3WPtOxJCMnNbPcob-ij51rDT9xgq_Ldd3o8-cksrIto,70877 +transformers/models/qwen3_vl/modular_qwen3_vl.py,sha256=Enk-yjv5VJ_XBPjywbX4yPyZexxuI1i-cRqDEXn0f_Q,68832 +transformers/models/qwen3_vl/processing_qwen3_vl.py,sha256=79jWSq9giq0f-z5tUD1qmeUifQB9-Vwdn6kF2ZjNpKk,17149 +transformers/models/qwen3_vl/video_processing_qwen3_vl.py,sha256=pJqD_EXNm6o-ORpor3l0PHDUe4bX1sgaJi_aQQT4nbc,11561 +transformers/models/qwen3_vl_moe/__init__.py,sha256=kZX59YLK-ZPItl-fKkUko_3uNM_QthuwE-rfzurn9iY,1028 +transformers/models/qwen3_vl_moe/__pycache__/__init__.cpython-310.pyc,, +transformers/models/qwen3_vl_moe/__pycache__/configuration_qwen3_vl_moe.cpython-310.pyc,, +transformers/models/qwen3_vl_moe/__pycache__/modeling_qwen3_vl_moe.cpython-310.pyc,, +transformers/models/qwen3_vl_moe/__pycache__/modular_qwen3_vl_moe.cpython-310.pyc,, +transformers/models/qwen3_vl_moe/configuration_qwen3_vl_moe.py,sha256=q6GXqyZ9B3tt-qmXd8zCIP13IOrv52l2bOMfsnAGkDI,17361 +transformers/models/qwen3_vl_moe/modeling_qwen3_vl_moe.py,sha256=Xt7cal2LYIrdIMTWrFhDk7xAn1MVidOTEUnrvWkzo4Q,84553 +transformers/models/qwen3_vl_moe/modular_qwen3_vl_moe.py,sha256=Lflr0PnyDE7zlLlZloo0vd1EhJN-nX7-5h477tOLU-U,26298 +transformers/models/rag/__init__.py,sha256=89sLlT4QJ96h0U-X6FmTdfSNJ8NjDjTpqyI1yK0L1Cw,1091 +transformers/models/rag/__pycache__/__init__.cpython-310.pyc,, +transformers/models/rag/__pycache__/configuration_rag.cpython-310.pyc,, +transformers/models/rag/__pycache__/modeling_rag.cpython-310.pyc,, +transformers/models/rag/__pycache__/modeling_tf_rag.cpython-310.pyc,, +transformers/models/rag/__pycache__/retrieval_rag.cpython-310.pyc,, +transformers/models/rag/__pycache__/tokenization_rag.cpython-310.pyc,, +transformers/models/rag/configuration_rag.py,sha256=dFbQO0qhT-mKYoTEmZAXlpwHSHaE4CVWNGcY7D7_yGo,8523 +transformers/models/rag/modeling_rag.py,sha256=48nUcFNh8KzGbU0r62SWaPDXwrZZbThO6nHTrfgdcE8,89183 +transformers/models/rag/modeling_tf_rag.py,sha256=bVwrivZEwtaAeuegzXIPoCC6sWcYuzYB4LGIiUaDLkQ,89318 +transformers/models/rag/retrieval_rag.py,sha256=oGsrPV81UHw2m6wIXVC7WcW8SD_lGl40L4rI5wLTwKs,30069 +transformers/models/rag/tokenization_rag.py,sha256=5UVTej-039v54SV8nC9StpNMSFMIxPCqo0srnrVsnKA,4610 +transformers/models/recurrent_gemma/__init__.py,sha256=i86Cydx-eAdwsVMjNc0yG9hGxe_amyfAdvF5Eg-UCGM,1011 +transformers/models/recurrent_gemma/__pycache__/__init__.cpython-310.pyc,, +transformers/models/recurrent_gemma/__pycache__/configuration_recurrent_gemma.cpython-310.pyc,, +transformers/models/recurrent_gemma/__pycache__/modeling_recurrent_gemma.cpython-310.pyc,, +transformers/models/recurrent_gemma/configuration_recurrent_gemma.py,sha256=w0mD1rnokEkBuvDNCW0mMJlO0DsF0TuG2JyJSmdqGmI,7750 +transformers/models/recurrent_gemma/modeling_recurrent_gemma.py,sha256=YY4RJaHlVmMv7KABCRyx7hyrE5_qcfHrHo2_uZ25PWM,35964 +transformers/models/reformer/__init__.py,sha256=zjiMjHIRPssQ8pVa4fQ0zMCCn0ee_mtJt6wc9J23QYQ,1084 +transformers/models/reformer/__pycache__/__init__.cpython-310.pyc,, +transformers/models/reformer/__pycache__/configuration_reformer.cpython-310.pyc,, +transformers/models/reformer/__pycache__/modeling_reformer.cpython-310.pyc,, +transformers/models/reformer/__pycache__/tokenization_reformer.cpython-310.pyc,, +transformers/models/reformer/__pycache__/tokenization_reformer_fast.cpython-310.pyc,, +transformers/models/reformer/configuration_reformer.py,sha256=MnTplogKNnkWOIGQHLRx5qmrZOBqIqXfeyLzZPy89IA,13196 +transformers/models/reformer/modeling_reformer.py,sha256=rfqhDMNL0zBOsampdV4TGTWlA08-5yNyuN8uCwrT7FU,118180 +transformers/models/reformer/tokenization_reformer.py,sha256=B5EhgmnvgvW8NiLWDq198Mh7IqUmnDYVUKoh0ECgbD4,6823 +transformers/models/reformer/tokenization_reformer_fast.py,sha256=Ow1TJe2MIatlbk0fYAfAZySEfPfWUpaAahzJvDrnAMQ,4137 +transformers/models/regnet/__init__.py,sha256=X_FU3wnZJ5KkCmRi4EyHk6ZUm_f0--YyyTS8lrknS9Y,1071 +transformers/models/regnet/__pycache__/__init__.cpython-310.pyc,, +transformers/models/regnet/__pycache__/configuration_regnet.cpython-310.pyc,, +transformers/models/regnet/__pycache__/modeling_flax_regnet.cpython-310.pyc,, +transformers/models/regnet/__pycache__/modeling_regnet.cpython-310.pyc,, +transformers/models/regnet/__pycache__/modeling_tf_regnet.cpython-310.pyc,, +transformers/models/regnet/configuration_regnet.py,sha256=TgYggQiYssFjcXjzLIe5ZDVrMxP4qQl1ZpmvZhLi2Ig,3974 +transformers/models/regnet/modeling_flax_regnet.py,sha256=ov6SXyXtkFXwNSC9quWte1vMl6AZkeJ49hlqp0l171k,28519 +transformers/models/regnet/modeling_regnet.py,sha256=9z0akvcr2eApFWLfTs8ZuLoMfLi_XgbjU0YGnULudHY,14166 +transformers/models/regnet/modeling_tf_regnet.py,sha256=Rzy-36Qzqu1wRp_qYZAfEj-5sZycNEgWQE210EBGmD8,24394 +transformers/models/rembert/__init__.py,sha256=Gif9TX1kvmD5iVWqsViSjxKYIDhR3FiBfp_QfA7U7i4,1119 +transformers/models/rembert/__pycache__/__init__.cpython-310.pyc,, +transformers/models/rembert/__pycache__/configuration_rembert.cpython-310.pyc,, +transformers/models/rembert/__pycache__/modeling_rembert.cpython-310.pyc,, +transformers/models/rembert/__pycache__/modeling_tf_rembert.cpython-310.pyc,, +transformers/models/rembert/__pycache__/tokenization_rembert.cpython-310.pyc,, +transformers/models/rembert/__pycache__/tokenization_rembert_fast.cpython-310.pyc,, +transformers/models/rembert/configuration_rembert.py,sha256=wSBV6VLEvcKMvP2PZw6KgaqelYzyIWhK_NZDV8kzX_8,7300 +transformers/models/rembert/modeling_rembert.py,sha256=jdb2SvVe4ZrUIV8Cspq0u_hoCjrAals-MGiFd0kKbNI,58413 +transformers/models/rembert/modeling_tf_rembert.py,sha256=ChyRVbTldGrTuWayyNLjm91mS4lOK25Q4SAuNTF5Fzo,77771 +transformers/models/rembert/tokenization_rembert.py,sha256=K_x4GpkaWMCipug1ojjPMKyiPMk-JwJSXBfXiLYIWm0,9566 +transformers/models/rembert/tokenization_rembert_fast.py,sha256=7T60RZ34azXx0zfaxE8Qh-4IJOYx7M-j59QDQO5BDNE,8747 +transformers/models/resnet/__init__.py,sha256=NCgMoczDbEI_XDWkWNWKIKGPYeohOC95f0o2X-Vh2vA,1071 +transformers/models/resnet/__pycache__/__init__.cpython-310.pyc,, +transformers/models/resnet/__pycache__/configuration_resnet.cpython-310.pyc,, +transformers/models/resnet/__pycache__/modeling_flax_resnet.cpython-310.pyc,, +transformers/models/resnet/__pycache__/modeling_resnet.cpython-310.pyc,, +transformers/models/resnet/__pycache__/modeling_tf_resnet.cpython-310.pyc,, +transformers/models/resnet/configuration_resnet.py,sha256=RUWWvz_KwilBJVOlaY1cK0CN078VPXPwzlOs2jZmd6I,6076 +transformers/models/resnet/modeling_flax_resnet.py,sha256=2r5isBIaKQIcGeDKWFtwbsgatGZDTXu0rpEKVbeT5xE,24708 +transformers/models/resnet/modeling_resnet.py,sha256=VhLrEx4CHIk-d-sj_eR_s1g5vbZcRo-oYYILNdxF01s,16120 +transformers/models/resnet/modeling_tf_resnet.py,sha256=FS0VNZqUMq7sXABV-GE3stcUpYd2bVUGVNh2xWLJdro,23774 +transformers/models/roberta/__init__.py,sha256=p1qYu_9qpmxsxMfXuoxK-VrmRQMEshwiM8Ekoij2J1M,1160 +transformers/models/roberta/__pycache__/__init__.cpython-310.pyc,, +transformers/models/roberta/__pycache__/configuration_roberta.cpython-310.pyc,, +transformers/models/roberta/__pycache__/modeling_flax_roberta.cpython-310.pyc,, +transformers/models/roberta/__pycache__/modeling_roberta.cpython-310.pyc,, +transformers/models/roberta/__pycache__/modeling_tf_roberta.cpython-310.pyc,, +transformers/models/roberta/__pycache__/tokenization_roberta.cpython-310.pyc,, +transformers/models/roberta/__pycache__/tokenization_roberta_fast.cpython-310.pyc,, +transformers/models/roberta/configuration_roberta.py,sha256=BYTjf1lo0Mk9xYqZjNHsZSlxPG7zJPcFl8ttr6LK8Ew,7336 +transformers/models/roberta/modeling_flax_roberta.py,sha256=hW7TxugQammDOpLCTZW3X3TjcJuy81AIdDztOcxzs-A,57284 +transformers/models/roberta/modeling_roberta.py,sha256=_NGbErJ3PkPieam0RUYCEbBNxW8OZzBEpAOTES2DN54,70968 +transformers/models/roberta/modeling_tf_roberta.py,sha256=5wdoYO0aaDfd5u6iwEYjSLuhp3Mti8jODh9OdXWRQt0,79951 +transformers/models/roberta/tokenization_roberta.py,sha256=FtKax5F5Cg4uJR7aWs62l9Tp0uDcVLW2dZKfrYfarrg,16469 +transformers/models/roberta/tokenization_roberta_fast.py,sha256=JYe2lmZugU3J7PEKn_SegaFURSAPLUejM6ckH_SqWmY,10978 +transformers/models/roberta_prelayernorm/__init__.py,sha256=QsVJJaoujnLHyCgwSsz53MV88vI183tTGJNXHDCHCAc,1127 +transformers/models/roberta_prelayernorm/__pycache__/__init__.cpython-310.pyc,, +transformers/models/roberta_prelayernorm/__pycache__/configuration_roberta_prelayernorm.cpython-310.pyc,, +transformers/models/roberta_prelayernorm/__pycache__/modeling_flax_roberta_prelayernorm.cpython-310.pyc,, +transformers/models/roberta_prelayernorm/__pycache__/modeling_roberta_prelayernorm.cpython-310.pyc,, +transformers/models/roberta_prelayernorm/__pycache__/modeling_tf_roberta_prelayernorm.cpython-310.pyc,, +transformers/models/roberta_prelayernorm/configuration_roberta_prelayernorm.py,sha256=YAxqjJmTFys2-TCyo4-B8Y1mm-kF2ExOqmxiSw5i4C4,7908 +transformers/models/roberta_prelayernorm/modeling_flax_roberta_prelayernorm.py,sha256=fQzWW2x-4ffASPs5V3shK4ctvdvmBlKrqmBeP6mUsEM,60941 +transformers/models/roberta_prelayernorm/modeling_roberta_prelayernorm.py,sha256=jaVRe7lS_yui9XS7XELphAxyqGybV_OLqBz0G-pp240,66826 +transformers/models/roberta_prelayernorm/modeling_tf_roberta_prelayernorm.py,sha256=Cv6jETaFoVnYC4rbko5lk3KL11Q7CuWMqaKJlCufNqs,83224 +transformers/models/roc_bert/__init__.py,sha256=4CveMGU-dY3nV4E6x-Xpb1jicRniwrPuSOrY8-SHIUI,1038 +transformers/models/roc_bert/__pycache__/__init__.cpython-310.pyc,, +transformers/models/roc_bert/__pycache__/configuration_roc_bert.cpython-310.pyc,, +transformers/models/roc_bert/__pycache__/modeling_roc_bert.cpython-310.pyc,, +transformers/models/roc_bert/__pycache__/tokenization_roc_bert.cpython-310.pyc,, +transformers/models/roc_bert/configuration_roc_bert.py,sha256=3w3t43X0ZkziGeftmlFg8yozWj57Pn5kynhbxXUkNMk,8544 +transformers/models/roc_bert/modeling_roc_bert.py,sha256=wasuviDKG6vG0R4uz52xgELoSHqjPdgCyn_ZsIV65rs,89010 +transformers/models/roc_bert/tokenization_roc_bert.py,sha256=Zo8YLFlTCOtUMFXU-et41Ktw_S61n9XRHn7DulIJ4tQ,49487 +transformers/models/roformer/__init__.py,sha256=v1CIjowYMq6aN-V9gyl-RWlMi_uQQxopuvEv76geFqk,1166 +transformers/models/roformer/__pycache__/__init__.cpython-310.pyc,, +transformers/models/roformer/__pycache__/configuration_roformer.cpython-310.pyc,, +transformers/models/roformer/__pycache__/modeling_flax_roformer.cpython-310.pyc,, +transformers/models/roformer/__pycache__/modeling_roformer.cpython-310.pyc,, +transformers/models/roformer/__pycache__/modeling_tf_roformer.cpython-310.pyc,, +transformers/models/roformer/__pycache__/tokenization_roformer.cpython-310.pyc,, +transformers/models/roformer/__pycache__/tokenization_roformer_fast.cpython-310.pyc,, +transformers/models/roformer/__pycache__/tokenization_utils.cpython-310.pyc,, +transformers/models/roformer/configuration_roformer.py,sha256=22jMpd4-nBlP7kJAlZADxFmr76zor7BRBd8orUW23go,6865 +transformers/models/roformer/modeling_flax_roformer.py,sha256=RwabkHxAdW4jApBUbJwjXESKCg-xcez9uNBAzya_xP4,39383 +transformers/models/roformer/modeling_roformer.py,sha256=lF0SdhZ8nkxqF19ph1Iy5xodfZ5lgFmlBBznY2HkXK8,65061 +transformers/models/roformer/modeling_tf_roformer.py,sha256=wevLVlaGrv6P6sP8zY3Mpg9fUsZRqb-PLRdOAT_OpWo,66049 +transformers/models/roformer/tokenization_roformer.py,sha256=Dlj00LiDLK0PSbGRlTOVpTXhYFj9yBvMqFqaEiNQSwk,20858 +transformers/models/roformer/tokenization_roformer_fast.py,sha256=BGhYYclZeX8qFSf0XOvATd9gH8rqlIqW4QCQq-umMXY,5584 +transformers/models/roformer/tokenization_utils.py,sha256=v_Qvq0uBuHpE43oIM64g9kTZcy8BD9oHhOR_ketIyIg,2625 +transformers/models/rt_detr/__init__.py,sha256=c9Y3NeKQwBP46tyFF99kjqTngoIWhLMq7XvzEJOfLaY,1181 +transformers/models/rt_detr/__pycache__/__init__.cpython-310.pyc,, +transformers/models/rt_detr/__pycache__/configuration_rt_detr.cpython-310.pyc,, +transformers/models/rt_detr/__pycache__/configuration_rt_detr_resnet.cpython-310.pyc,, +transformers/models/rt_detr/__pycache__/image_processing_rt_detr.cpython-310.pyc,, +transformers/models/rt_detr/__pycache__/image_processing_rt_detr_fast.cpython-310.pyc,, +transformers/models/rt_detr/__pycache__/modeling_rt_detr.cpython-310.pyc,, +transformers/models/rt_detr/__pycache__/modeling_rt_detr_resnet.cpython-310.pyc,, +transformers/models/rt_detr/__pycache__/modular_rt_detr.cpython-310.pyc,, +transformers/models/rt_detr/configuration_rt_detr.py,sha256=Khno06NPBiP_2Nq7_uy569OoiR6sb7vdxJ1jMVOtkCA,18295 +transformers/models/rt_detr/configuration_rt_detr_resnet.py,sha256=kBbmglFZkq0cqLsz1VZwTXVLHQnjnLjtFbkfMMbVOmM,5557 +transformers/models/rt_detr/image_processing_rt_detr.py,sha256=ayBseDPRJZX4PweZrnvR_ZIXPzo9XOdPwiZLAPGLGLA,51701 +transformers/models/rt_detr/image_processing_rt_detr_fast.py,sha256=hTOTc06ZliEDV9bkuB4iik-rBrj2f_6UvIpiT7NbxqE,24944 +transformers/models/rt_detr/modeling_rt_detr.py,sha256=W7rxYPOAwKzIAU1b1g0FLIW992bowryp1a4HOzYamnw,95382 +transformers/models/rt_detr/modeling_rt_detr_resnet.py,sha256=xlET8ddRbxBzLz2uH4ks_9wuqNPbpj-uanOd0gOp9Dg,15149 +transformers/models/rt_detr/modular_rt_detr.py,sha256=U5As4Jc341eUEmVdaRFGkeY6udhMM3PzGiseIqEbzyc,14885 +transformers/models/rt_detr_v2/__init__.py,sha256=7RL5U-hsGt3HQZ5SuWn8iZY_L166EYswBvaQXFRkzRc,1003 +transformers/models/rt_detr_v2/__pycache__/__init__.cpython-310.pyc,, +transformers/models/rt_detr_v2/__pycache__/configuration_rt_detr_v2.cpython-310.pyc,, +transformers/models/rt_detr_v2/__pycache__/modeling_rt_detr_v2.cpython-310.pyc,, +transformers/models/rt_detr_v2/__pycache__/modular_rt_detr_v2.cpython-310.pyc,, +transformers/models/rt_detr_v2/configuration_rt_detr_v2.py,sha256=IjGQgzggWMu4uGoPEn8DHMc00lGJCdTcu2fvZ6NamQs,19837 +transformers/models/rt_detr_v2/modeling_rt_detr_v2.py,sha256=mYzHhnFEJzXvKYhNty5N5ZuS2wKluehRD7PR-ocUkT4,96324 +transformers/models/rt_detr_v2/modular_rt_detr_v2.py,sha256=oFEBxGHsltolRP9fSFLRb_4j2-N22fXAbtwPP8SL8jw,29745 +transformers/models/rwkv/__init__.py,sha256=HAiwEvW1j_xuHj_PbmN25srY9RtA1gLmN_0RWvAyG78,989 +transformers/models/rwkv/__pycache__/__init__.cpython-310.pyc,, +transformers/models/rwkv/__pycache__/configuration_rwkv.cpython-310.pyc,, +transformers/models/rwkv/__pycache__/modeling_rwkv.cpython-310.pyc,, +transformers/models/rwkv/configuration_rwkv.py,sha256=0hwiEhaLNCekxOiYD_D-e95ftq7_aazx9ImRtf0ydWc,5204 +transformers/models/rwkv/modeling_rwkv.py,sha256=EkHzVtu8p87JcT-rymah94GGnpl_vdWpK0-XGTlt47w,33588 +transformers/models/sam/__init__.py,sha256=ilUO6W284DgX2BijkzdGXaw-OZsSrEo-qjZqiidfOEY,1141 +transformers/models/sam/__pycache__/__init__.cpython-310.pyc,, +transformers/models/sam/__pycache__/configuration_sam.cpython-310.pyc,, +transformers/models/sam/__pycache__/image_processing_sam.cpython-310.pyc,, +transformers/models/sam/__pycache__/image_processing_sam_fast.cpython-310.pyc,, +transformers/models/sam/__pycache__/modeling_sam.cpython-310.pyc,, +transformers/models/sam/__pycache__/modeling_tf_sam.cpython-310.pyc,, +transformers/models/sam/__pycache__/processing_sam.cpython-310.pyc,, +transformers/models/sam/configuration_sam.py,sha256=q6C10OyYdHicWRfuaudnl_5K9I3LH8nPQj_1wXPGegw,14716 +transformers/models/sam/image_processing_sam.py,sha256=jJZT4t9zIvLgPYpXh1Eh2I19Zkw_ABMKrYZYhJI3EU4,67970 +transformers/models/sam/image_processing_sam_fast.py,sha256=ZTlVrL-tTxZuJnxRQQ2pCVPt_exhLx4zpQuvfBMTEM0,31316 +transformers/models/sam/modeling_sam.py,sha256=eOkCQhH64lnMzgtYbRLMI3OlVgjrIn8iOBgKtkaZ0Fg,61715 +transformers/models/sam/modeling_tf_sam.py,sha256=oUYzLUHdtOgEcoS6wzkV9MDmU12UwXwTGOiAQiV-2WA,77733 +transformers/models/sam/processing_sam.py,sha256=3Cn9YnVdfmCi-HSvMubnW9vHNfOKMnzhTwQO7Fui6nk,12118 +transformers/models/sam2/__init__.py,sha256=H7LrRCnUmUZ9fj5C_p_Mp8xNB5Zdtoo1S__LcYcs_i4,1070 +transformers/models/sam2/__pycache__/__init__.cpython-310.pyc,, +transformers/models/sam2/__pycache__/configuration_sam2.cpython-310.pyc,, +transformers/models/sam2/__pycache__/image_processing_sam2_fast.cpython-310.pyc,, +transformers/models/sam2/__pycache__/modeling_sam2.cpython-310.pyc,, +transformers/models/sam2/__pycache__/modular_sam2.cpython-310.pyc,, +transformers/models/sam2/__pycache__/processing_sam2.cpython-310.pyc,, +transformers/models/sam2/configuration_sam2.py,sha256=VqEXGJqFzfy8PhpwGn4U9O67ZwSN2fpnb3HHwZ4FWgY,20600 +transformers/models/sam2/image_processing_sam2_fast.py,sha256=7UzCnCfUF5XUfpYDziwCY32o5ONpG-noTwM92WiYuFk,30796 +transformers/models/sam2/modeling_sam2.py,sha256=OMzHf0MWkCIkriTr0xLqDJENQ5VM-qH7oKOG6SC--54,72876 +transformers/models/sam2/modular_sam2.py,sha256=Kp__1RCHtCWaSw21K-YmgZqa9wASirgNz3j3EXUwiwk,64617 +transformers/models/sam2/processing_sam2.py,sha256=viGjbI1aZKD7tWHAWaVKTZ0xiyigctODUPJ1ESRcnVI,23039 +transformers/models/sam2_video/__init__.py,sha256=WFP70wbKsoPQuuR0Aq6sMpFZ9m2cQJwNgdCpngg4C1o,1089 +transformers/models/sam2_video/__pycache__/__init__.cpython-310.pyc,, +transformers/models/sam2_video/__pycache__/configuration_sam2_video.cpython-310.pyc,, +transformers/models/sam2_video/__pycache__/modeling_sam2_video.cpython-310.pyc,, +transformers/models/sam2_video/__pycache__/modular_sam2_video.cpython-310.pyc,, +transformers/models/sam2_video/__pycache__/processing_sam2_video.cpython-310.pyc,, +transformers/models/sam2_video/__pycache__/video_processing_sam2_video.cpython-310.pyc,, +transformers/models/sam2_video/configuration_sam2_video.py,sha256=u5wSunYToJaU9nC7dVigFo0dDkiBf8KpjWo76K9HFzo,20482 +transformers/models/sam2_video/modeling_sam2_video.py,sha256=2FroEz3fIEAHKKMvLj5Tw9fFAr4GWXAghcuPZkgLbwM,125463 +transformers/models/sam2_video/modular_sam2_video.py,sha256=MdDAnVjIz_JLwNzeAoeR166HUI9lngsAbzg8juCyREU,117324 +transformers/models/sam2_video/processing_sam2_video.py,sha256=3qlms1YII2vownAjpjVhwV7IuiMS7ikYScCFzZk-HeA,38301 +transformers/models/sam2_video/video_processing_sam2_video.py,sha256=p1CaA_NGuAePgso2n0hKQuoizYNxvX6zafSlz65J7dg,4899 +transformers/models/sam_hq/__init__.py,sha256=DtfMcRDroMaiZ9FKrgymx4rCyGuP5r1dxr-wzjS0T0Q,1029 +transformers/models/sam_hq/__pycache__/__init__.cpython-310.pyc,, +transformers/models/sam_hq/__pycache__/configuration_sam_hq.cpython-310.pyc,, +transformers/models/sam_hq/__pycache__/modeling_sam_hq.cpython-310.pyc,, +transformers/models/sam_hq/__pycache__/modular_sam_hq.cpython-310.pyc,, +transformers/models/sam_hq/__pycache__/processing_samhq.cpython-310.pyc,, +transformers/models/sam_hq/configuration_sam_hq.py,sha256=U3nPcw9lh2M6MdBMe7rK_xniKVPVoRKzgqvPgU-7kzo,14840 +transformers/models/sam_hq/modeling_sam_hq.py,sha256=GHvDMfx8P4YJlbCU2HtZHzkwNWacEbq1hlSvD9cPkDA,69298 +transformers/models/sam_hq/modular_sam_hq.py,sha256=6NxL8hQd7wigyRqr5Z2Ci7f_G8Wnv-_xIdty-les2m4,31609 +transformers/models/sam_hq/processing_samhq.py,sha256=5audIn1A3v9gU6zM90o8oLF5YM_PA3QWR-3aFReFcFA,12020 +transformers/models/seamless_m4t/__init__.py,sha256=Y5c_W1E83fh8ToTMqF4NcReXzKZiTDv3A4ePoNUxXDg,1194 +transformers/models/seamless_m4t/__pycache__/__init__.cpython-310.pyc,, +transformers/models/seamless_m4t/__pycache__/configuration_seamless_m4t.cpython-310.pyc,, +transformers/models/seamless_m4t/__pycache__/feature_extraction_seamless_m4t.cpython-310.pyc,, +transformers/models/seamless_m4t/__pycache__/modeling_seamless_m4t.cpython-310.pyc,, +transformers/models/seamless_m4t/__pycache__/processing_seamless_m4t.cpython-310.pyc,, +transformers/models/seamless_m4t/__pycache__/tokenization_seamless_m4t.cpython-310.pyc,, +transformers/models/seamless_m4t/__pycache__/tokenization_seamless_m4t_fast.cpython-310.pyc,, +transformers/models/seamless_m4t/configuration_seamless_m4t.py,sha256=zvCh7r-KOILwOlujAaJLtv1-Z7B8XgZEfxqYuBMjGK0,23521 +transformers/models/seamless_m4t/feature_extraction_seamless_m4t.py,sha256=VeMODyxbmdHC7O2gb_VOzXO8_cz7gktCWEYIVPmscWQ,13628 +transformers/models/seamless_m4t/modeling_seamless_m4t.py,sha256=gc96yE1P9dMRaKxfgUuYdIfFxz0tnUudRjDTHn1laO0,187012 +transformers/models/seamless_m4t/processing_seamless_m4t.py,sha256=ZoZ_rJ0G2UNhLDQ4INAjnmB1BZWHtEBsLjGJxjIvACg,5039 +transformers/models/seamless_m4t/tokenization_seamless_m4t.py,sha256=vRb1fQgr6HzLT5rnhE7dDqAuC5_yT5DCIftiBSZIIak,26076 +transformers/models/seamless_m4t/tokenization_seamless_m4t_fast.py,sha256=NC5GbGQnDiLf9NB6-XQ4DqJjLFQWJ7_0yJXoDthY-z0,19774 +transformers/models/seamless_m4t_v2/__init__.py,sha256=mMY04PBMrOwTIQLq01RHqZjssvrSYl3UDhP5Y5vFifs,1011 +transformers/models/seamless_m4t_v2/__pycache__/__init__.cpython-310.pyc,, +transformers/models/seamless_m4t_v2/__pycache__/configuration_seamless_m4t_v2.cpython-310.pyc,, +transformers/models/seamless_m4t_v2/__pycache__/modeling_seamless_m4t_v2.cpython-310.pyc,, +transformers/models/seamless_m4t_v2/configuration_seamless_m4t_v2.py,sha256=ihF9DjqhoOojebAUTijxbQuLNs0nEqJBi9umyR-gHgA,24388 +transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py,sha256=gcA91JUtgk5WTM-Tt8FJXiaLZLUyKnbQ2Y7cokbEcRk,206172 +transformers/models/seed_oss/__init__.py,sha256=ukqpfG-W3jFJvA9UiL5bI_2jl_CTZFynUL0Tq9WD63M,1025 +transformers/models/seed_oss/__pycache__/__init__.cpython-310.pyc,, +transformers/models/seed_oss/__pycache__/configuration_seed_oss.cpython-310.pyc,, +transformers/models/seed_oss/__pycache__/modeling_seed_oss.cpython-310.pyc,, +transformers/models/seed_oss/__pycache__/modular_seed_oss.cpython-310.pyc,, +transformers/models/seed_oss/configuration_seed_oss.py,sha256=V_XjuaOrTU7hyAMvrsAQg-Vvmm3exGr-IX9uPgELdH0,12107 +transformers/models/seed_oss/modeling_seed_oss.py,sha256=1HRueKix0pbNLxdZjm_ascQSH8yWMYMERekBnWQYxPc,22009 +transformers/models/seed_oss/modular_seed_oss.py,sha256=kaPESWCrk1VEjMfsy6BoZRDu_JOVs5WwkRZh4gkPwMA,7688 +transformers/models/segformer/__init__.py,sha256=KusPvx7i3IW86Z3RjiVjo3oNu-SsqwmkifgegRkSzKs,1185 +transformers/models/segformer/__pycache__/__init__.cpython-310.pyc,, +transformers/models/segformer/__pycache__/configuration_segformer.cpython-310.pyc,, +transformers/models/segformer/__pycache__/feature_extraction_segformer.cpython-310.pyc,, +transformers/models/segformer/__pycache__/image_processing_segformer.cpython-310.pyc,, +transformers/models/segformer/__pycache__/image_processing_segformer_fast.cpython-310.pyc,, +transformers/models/segformer/__pycache__/modeling_segformer.cpython-310.pyc,, +transformers/models/segformer/__pycache__/modeling_tf_segformer.cpython-310.pyc,, +transformers/models/segformer/__pycache__/modular_segformer.cpython-310.pyc,, +transformers/models/segformer/configuration_segformer.py,sha256=CyvERUX7QyWRo0mG7jwst-3jIqzOyD6YQ2ZdCkoTY_g,7429 +transformers/models/segformer/feature_extraction_segformer.py,sha256=7JHygTUT0pw36WCxl14kgaPvxqNBPFf9AOUuxQKHhlg,1324 +transformers/models/segformer/image_processing_segformer.py,sha256=4zstqJfk235643AT0ewDya4hhI9z5f99reO0-Kj1L_k,22252 +transformers/models/segformer/image_processing_segformer_fast.py,sha256=szsb6m7-mdAJeYYTGqJYHVNU4HR80vCNj9lr1Rs3VKE,10074 +transformers/models/segformer/modeling_segformer.py,sha256=r54Pc20Bl-tPOWCrU85ZaKUipKCCXwMAC-k1TE85Xxw,31598 +transformers/models/segformer/modeling_tf_segformer.py,sha256=99M87FnHfxDikZXn-2PmCnGiPEcTW4kxQpWC1tTaQw8,43687 +transformers/models/segformer/modular_segformer.py,sha256=82GCRkfnIsSv1faNznK8-w4TySJ3p4ofIaIGVE7MCGw,5827 +transformers/models/seggpt/__init__.py,sha256=RzV8DKCX1lOWGqXv2BlE1R7T4QuEcdYAVy_csccLvEw,1036 +transformers/models/seggpt/__pycache__/__init__.cpython-310.pyc,, +transformers/models/seggpt/__pycache__/configuration_seggpt.cpython-310.pyc,, +transformers/models/seggpt/__pycache__/image_processing_seggpt.cpython-310.pyc,, +transformers/models/seggpt/__pycache__/modeling_seggpt.cpython-310.pyc,, +transformers/models/seggpt/configuration_seggpt.py,sha256=VeHoocblt-EIRF-FO8JkrVGUcBPKbXPWAJMlXRllz44,6492 +transformers/models/seggpt/image_processing_seggpt.py,sha256=2hctN6Au2N4H8-2Kv7w0GIsh8Am6d3O5z4i7yp5HySE,31505 +transformers/models/seggpt/modeling_seggpt.py,sha256=eQgzzo7KzBk9Z7SPAl9U0IUAPnz_6WN_aPfZwjDYyJE,44650 +transformers/models/sew/__init__.py,sha256=POCF36ZRa_dr7oQhkDU2X17bsZuLoWI5V8DSihqr_vU,987 +transformers/models/sew/__pycache__/__init__.cpython-310.pyc,, +transformers/models/sew/__pycache__/configuration_sew.cpython-310.pyc,, +transformers/models/sew/__pycache__/feature_extraction_sew.cpython-310.pyc,, +transformers/models/sew/__pycache__/modeling_sew.cpython-310.pyc,, +transformers/models/sew/__pycache__/modular_sew.cpython-310.pyc,, +transformers/models/sew/configuration_sew.py,sha256=lJIjv2Ktr3PexNd9E8Q2cb3ewzh4W10eCk5M4d-JOyc,14231 +transformers/models/sew/feature_extraction_sew.py,sha256=szQVJwMsEe-9xZxeHiUFb5E-JFHc6gfTQNqwPp_kLiU,1883 +transformers/models/sew/modeling_sew.py,sha256=kYPlJjQM-hfUr9UCgsz1Rk8xlIuItUKvulvo93CA5es,47441 +transformers/models/sew/modular_sew.py,sha256=umXuB4_mJgHOy_4O4wsHUyocemK9WcQVTVOmQvPCdgc,18883 +transformers/models/sew_d/__init__.py,sha256=zE9sw10e_a1d-8-Jsb75z5frCjkFGD0dZMHAXiNgGwk,991 +transformers/models/sew_d/__pycache__/__init__.cpython-310.pyc,, +transformers/models/sew_d/__pycache__/configuration_sew_d.cpython-310.pyc,, +transformers/models/sew_d/__pycache__/modeling_sew_d.cpython-310.pyc,, +transformers/models/sew_d/configuration_sew_d.py,sha256=UXLYoDAIix9cWhSQVuavz4LgbQ2lvCxO5vE_bGsZei0,16191 +transformers/models/sew_d/modeling_sew_d.py,sha256=p2CuIOUUolce5x29v7yRqujC5p6a8QF5qQCOe6XJivg,69121 +transformers/models/shieldgemma2/__init__.py,sha256=B7eqFJSWi0p49QNvKqUGR8NPyFjQuMdBANevIjTsSxw,1048 +transformers/models/shieldgemma2/__pycache__/__init__.cpython-310.pyc,, +transformers/models/shieldgemma2/__pycache__/configuration_shieldgemma2.cpython-310.pyc,, +transformers/models/shieldgemma2/__pycache__/modeling_shieldgemma2.cpython-310.pyc,, +transformers/models/shieldgemma2/__pycache__/processing_shieldgemma2.cpython-310.pyc,, +transformers/models/shieldgemma2/configuration_shieldgemma2.py,sha256=Cj4MM47fvnQVGqzEXeidaqrkSmz4-i11mYvz6yj4dvU,4805 +transformers/models/shieldgemma2/modeling_shieldgemma2.py,sha256=gI8F9mRgE3zPjdUcRD4kTpOvNvCgEM7Er3y8Y3i_POE,6039 +transformers/models/shieldgemma2/processing_shieldgemma2.py,sha256=vP_TLeEuh5MYgxGqc2P3Z9Z4CXuPJQd34QX7xkMYkvc,8380 +transformers/models/siglip/__init__.py,sha256=CnNqbSQ25tKLz0MGJVmhSXjVyASRDu7v5yjTHWYZ6M4,1160 +transformers/models/siglip/__pycache__/__init__.cpython-310.pyc,, +transformers/models/siglip/__pycache__/configuration_siglip.cpython-310.pyc,, +transformers/models/siglip/__pycache__/image_processing_siglip.cpython-310.pyc,, +transformers/models/siglip/__pycache__/image_processing_siglip_fast.cpython-310.pyc,, +transformers/models/siglip/__pycache__/modeling_siglip.cpython-310.pyc,, +transformers/models/siglip/__pycache__/processing_siglip.cpython-310.pyc,, +transformers/models/siglip/__pycache__/tokenization_siglip.cpython-310.pyc,, +transformers/models/siglip/configuration_siglip.py,sha256=3GVhImzaW3WCFyQ3IfC-ZM3ZA2qmvA_BEjmZyNOQyfk,11697 +transformers/models/siglip/image_processing_siglip.py,sha256=9obAmCFLGUqI-5cOZl_YbNyeMi001rA1asw25qH2sT4,12084 +transformers/models/siglip/image_processing_siglip_fast.py,sha256=3dwic9zjpzgxbCnQC84lUvcDOSnWIlEZrCUJItmi474,1257 +transformers/models/siglip/modeling_siglip.py,sha256=YIdFZLn9H7142ao3SLOttQbPS1cPHr1R383jLgulHQ0,42077 +transformers/models/siglip/processing_siglip.py,sha256=Oit8g6wlMxBCp9fh6qvSuNZCQcQxZBlsoW6a77HjzC4,1594 +transformers/models/siglip/tokenization_siglip.py,sha256=QXJ1RdlwC6ESO0z3thY-tzXY5JL0VEsMBsWi-OgA4Vg,16047 +transformers/models/siglip2/__init__.py,sha256=dvfEVdLNJzWjugwTPGNp1gfxA6x4ytFLgGtV4Zfhoh4,1126 +transformers/models/siglip2/__pycache__/__init__.cpython-310.pyc,, +transformers/models/siglip2/__pycache__/configuration_siglip2.cpython-310.pyc,, +transformers/models/siglip2/__pycache__/image_processing_siglip2.cpython-310.pyc,, +transformers/models/siglip2/__pycache__/image_processing_siglip2_fast.cpython-310.pyc,, +transformers/models/siglip2/__pycache__/modeling_siglip2.cpython-310.pyc,, +transformers/models/siglip2/__pycache__/modular_siglip2.cpython-310.pyc,, +transformers/models/siglip2/__pycache__/processing_siglip2.cpython-310.pyc,, +transformers/models/siglip2/configuration_siglip2.py,sha256=zs0zqZ9Tog9iwLK6yEN6peJErYCHN5N0iBB11Lp0FpA,12819 +transformers/models/siglip2/image_processing_siglip2.py,sha256=CgxErsXcPSf9OVsc-tXUr85w1l9Qm37gqc_zeo8CgFg,16118 +transformers/models/siglip2/image_processing_siglip2_fast.py,sha256=VexDWmZAXYBB6Pl8rX4mo9pfGdpXbl9PgLi8-lERUek,6233 +transformers/models/siglip2/modeling_siglip2.py,sha256=kEHDyQQaqxXbArs_op_e8rgaUbm0wWmLzLzi7G-jiM4,48351 +transformers/models/siglip2/modular_siglip2.py,sha256=vtCU0qpFidhEXkTPMjutIv29DkrTBy4s-OjAGPBXxG0,25104 +transformers/models/siglip2/processing_siglip2.py,sha256=9ogRb_M32f_6UxB_6GZqf2a0oN_h9zY3c96GWBLiYDY,2178 +transformers/models/smollm3/__init__.py,sha256=BZA2MiDpGmv2swg1yO14tkgi_SZ0yVg8ndr-PJwY-fI,1000 +transformers/models/smollm3/__pycache__/__init__.cpython-310.pyc,, +transformers/models/smollm3/__pycache__/configuration_smollm3.cpython-310.pyc,, +transformers/models/smollm3/__pycache__/modeling_smollm3.cpython-310.pyc,, +transformers/models/smollm3/__pycache__/modular_smollm3.cpython-310.pyc,, +transformers/models/smollm3/configuration_smollm3.py,sha256=T-xosij-x2fdyPjNTED46vN0w8RL84wM8WGDgsdzHN8,13374 +transformers/models/smollm3/modeling_smollm3.py,sha256=BoFsQYaadeZtx4RomHx19kNJRQxEyYC3hqILIgQVluw,22491 +transformers/models/smollm3/modular_smollm3.py,sha256=uab9U7hYXzDjuRWHLaUrgR4L9M7x3lcqrdgxgVmYEUg,16418 +transformers/models/smolvlm/__init__.py,sha256=fE-znTLrbxNe5qkHVgI4xmwFz-paFymZuxTAd2GKkOo,1126 +transformers/models/smolvlm/__pycache__/__init__.cpython-310.pyc,, +transformers/models/smolvlm/__pycache__/configuration_smolvlm.cpython-310.pyc,, +transformers/models/smolvlm/__pycache__/image_processing_smolvlm.cpython-310.pyc,, +transformers/models/smolvlm/__pycache__/image_processing_smolvlm_fast.cpython-310.pyc,, +transformers/models/smolvlm/__pycache__/modeling_smolvlm.cpython-310.pyc,, +transformers/models/smolvlm/__pycache__/modular_smolvlm.cpython-310.pyc,, +transformers/models/smolvlm/__pycache__/processing_smolvlm.cpython-310.pyc,, +transformers/models/smolvlm/__pycache__/video_processing_smolvlm.cpython-310.pyc,, +transformers/models/smolvlm/configuration_smolvlm.py,sha256=4XHkP6aHHeBOGOoLNn87AuAp5csfYpWo8QKW8TrauYI,9359 +transformers/models/smolvlm/image_processing_smolvlm.py,sha256=SLYyIc-WYrgw-g_-sADEJmhzPhAFww3RbWVq_P6NHsc,44554 +transformers/models/smolvlm/image_processing_smolvlm_fast.py,sha256=q-r6uelXrWE4LAxIWH4YdSAiq66RtAFyc5HMd2WoO48,23780 +transformers/models/smolvlm/modeling_smolvlm.py,sha256=LqZ0Hnhh1Tx1Gpxmlgljv_gdO2ZQ3w6pnKXKnjo_kPs,41990 +transformers/models/smolvlm/modular_smolvlm.py,sha256=kRdro6czM8tqsHyiXz8NjIY8yni4ng8bh-78XfIHYC0,19040 +transformers/models/smolvlm/processing_smolvlm.py,sha256=LEtjQgbvX76FlfrqkHIN12MTJ-o_gXWr00MG-lQb-rs,20291 +transformers/models/smolvlm/video_processing_smolvlm.py,sha256=TzjLnFdGMR6Umz-rR3yVgsL8aTBp-n5yPxVrnqfdsgw,14874 +transformers/models/speech_encoder_decoder/__init__.py,sha256=0MwevN904dCSAb0dvznhDH--q-m3-MzdCtx0B-T5hpk,1081 +transformers/models/speech_encoder_decoder/__pycache__/__init__.cpython-310.pyc,, +transformers/models/speech_encoder_decoder/__pycache__/configuration_speech_encoder_decoder.cpython-310.pyc,, +transformers/models/speech_encoder_decoder/__pycache__/modeling_flax_speech_encoder_decoder.cpython-310.pyc,, +transformers/models/speech_encoder_decoder/__pycache__/modeling_speech_encoder_decoder.cpython-310.pyc,, +transformers/models/speech_encoder_decoder/configuration_speech_encoder_decoder.py,sha256=2FBAuqwi4KNkbb7chAliDYZ46vYJiIjEwqtSh1oFSKY,4693 +transformers/models/speech_encoder_decoder/modeling_flax_speech_encoder_decoder.py,sha256=KCyHnYvQdlpFChAzDCgDs2UfY546A0i01U8e1YYGT0Q,44860 +transformers/models/speech_encoder_decoder/modeling_speech_encoder_decoder.py,sha256=IA54yPvoAUeirx9dPHtoo-LUaWKPER6aVHMBp7BFqP0,25575 +transformers/models/speech_to_text/__init__.py,sha256=qZzt5u1rbSsOjPVmX40R4b4pkL1mxOQZ66q8GPDKao8,1200 +transformers/models/speech_to_text/__pycache__/__init__.cpython-310.pyc,, +transformers/models/speech_to_text/__pycache__/configuration_speech_to_text.cpython-310.pyc,, +transformers/models/speech_to_text/__pycache__/feature_extraction_speech_to_text.cpython-310.pyc,, +transformers/models/speech_to_text/__pycache__/modeling_speech_to_text.cpython-310.pyc,, +transformers/models/speech_to_text/__pycache__/modeling_tf_speech_to_text.cpython-310.pyc,, +transformers/models/speech_to_text/__pycache__/processing_speech_to_text.cpython-310.pyc,, +transformers/models/speech_to_text/__pycache__/tokenization_speech_to_text.cpython-310.pyc,, +transformers/models/speech_to_text/configuration_speech_to_text.py,sha256=YazgmnHYt_lbYaRQNt2dEYAqgpAfYln36hQl89WPLF4,9825 +transformers/models/speech_to_text/feature_extraction_speech_to_text.py,sha256=r6vxaMiZM7KBxghUnd_WnDJ4brms95HimGR0bkzvglw,13955 +transformers/models/speech_to_text/modeling_speech_to_text.py,sha256=dcolyIrurG9SojhUohBDO45OHi-C_kI2x4TRW0mvABY,61717 +transformers/models/speech_to_text/modeling_tf_speech_to_text.py,sha256=-qOZso75ib0DJDvIGE4NcnQdP3Q97uALIiUqlRd5-qc,74289 +transformers/models/speech_to_text/processing_speech_to_text.py,sha256=jg7WkcQYWW00ndyN3PUo98EfswLlNNUc0izl1Iphy5E,4240 +transformers/models/speech_to_text/tokenization_speech_to_text.py,sha256=4VRmhzHQZvrplhvYdQFMN8v9xAWmz0UFW4TY9pI7ygw,11501 +transformers/models/speecht5/__init__.py,sha256=DploRLnZX4ZO40Z7BstCZ7aNWGuZE06tIeMo0GTyR60,1124 +transformers/models/speecht5/__pycache__/__init__.cpython-310.pyc,, +transformers/models/speecht5/__pycache__/configuration_speecht5.cpython-310.pyc,, +transformers/models/speecht5/__pycache__/feature_extraction_speecht5.cpython-310.pyc,, +transformers/models/speecht5/__pycache__/modeling_speecht5.cpython-310.pyc,, +transformers/models/speecht5/__pycache__/number_normalizer.cpython-310.pyc,, +transformers/models/speecht5/__pycache__/processing_speecht5.cpython-310.pyc,, +transformers/models/speecht5/__pycache__/tokenization_speecht5.cpython-310.pyc,, +transformers/models/speecht5/configuration_speecht5.py,sha256=q6TwW_M__spcgD9NOObNlcOZt8_xvL6V5Qm1yQZ1T1I,23466 +transformers/models/speecht5/feature_extraction_speecht5.py,sha256=MqnjfL1S_-VCnJhEEWgfv9kAYp2_nlO9MZ9OtsESJX0,17853 +transformers/models/speecht5/modeling_speecht5.py,sha256=Vd5tEqXzZ8SjTDLV7RJ6jiZXy2JnxMG2QHVPkFxkNyI,147725 +transformers/models/speecht5/number_normalizer.py,sha256=cxnEUdHSISW5eAo15cLuVkZa65zMFuMFaJ8zAOQCsAA,7019 +transformers/models/speecht5/processing_speecht5.py,sha256=PvI7tFsx_a_39n1TME0uDQSqQS3J9neLLFPwbrn40C0,6990 +transformers/models/speecht5/tokenization_speecht5.py,sha256=UfqBVrMUHCRRY_-kVvcU3RJnEfdAlq40ooE0UqV40ps,9009 +transformers/models/splinter/__init__.py,sha256=N3tdgJIqZRPK0g3pfLE3p3-HkGJMRf-GQ189anQ51to,1084 +transformers/models/splinter/__pycache__/__init__.cpython-310.pyc,, +transformers/models/splinter/__pycache__/configuration_splinter.cpython-310.pyc,, +transformers/models/splinter/__pycache__/modeling_splinter.cpython-310.pyc,, +transformers/models/splinter/__pycache__/tokenization_splinter.cpython-310.pyc,, +transformers/models/splinter/__pycache__/tokenization_splinter_fast.cpython-310.pyc,, +transformers/models/splinter/configuration_splinter.py,sha256=ZajZPX6f9K7gBqp2PbOtmJg-_fAU8h72tKdTNjyQV0M,5625 +transformers/models/splinter/modeling_splinter.py,sha256=TdgEoZC-qk2GXnaLhX_PWTY15CK0KGvrJhvtGF4_Ce0,37981 +transformers/models/splinter/tokenization_splinter.py,sha256=ba400uZlqtB6kjdMI3oMgBWs_p-px81zAQItZQx-l6c,20948 +transformers/models/splinter/tokenization_splinter_fast.py,sha256=AG6k691a2HJqtIAiEyn07WuSc4JgqU1HTkfEGC8Tt2c,8590 +transformers/models/squeezebert/__init__.py,sha256=_kzQtfoJetCK99e_FICGZl5DN8S2VVcOUFioGyN0sLI,1096 +transformers/models/squeezebert/__pycache__/__init__.cpython-310.pyc,, +transformers/models/squeezebert/__pycache__/configuration_squeezebert.cpython-310.pyc,, +transformers/models/squeezebert/__pycache__/modeling_squeezebert.cpython-310.pyc,, +transformers/models/squeezebert/__pycache__/tokenization_squeezebert.cpython-310.pyc,, +transformers/models/squeezebert/__pycache__/tokenization_squeezebert_fast.cpython-310.pyc,, +transformers/models/squeezebert/configuration_squeezebert.py,sha256=9I4mUuqEwKAIrezRjjto3HBfJ-aiWBTkQcIZWuJFFGM,7312 +transformers/models/squeezebert/modeling_squeezebert.py,sha256=XNcULy9rowxidymjHb8D3OWWVFaTsC9rHLPmJQsd5rQ,38738 +transformers/models/squeezebert/tokenization_squeezebert.py,sha256=4ZbPoFCjrt-d2zdbZ9s23IHOsN5iw9VpG11W4sJWCJM,20092 +transformers/models/squeezebert/tokenization_squeezebert_fast.py,sha256=CtqOSIMAYhS66yYjbWxTDpbbxNvAllTkP_lJroEyvfQ,6724 +transformers/models/stablelm/__init__.py,sha256=aVgWTcwBuuiGJDp8H_ZU6BvhYqjmNEqCukU7jEfwd_I,997 +transformers/models/stablelm/__pycache__/__init__.cpython-310.pyc,, +transformers/models/stablelm/__pycache__/configuration_stablelm.cpython-310.pyc,, +transformers/models/stablelm/__pycache__/modeling_stablelm.cpython-310.pyc,, +transformers/models/stablelm/configuration_stablelm.py,sha256=GqKL53dgijlmwQMgLsuw4jB6gm1stU4SaCETjqumKVs,10843 +transformers/models/stablelm/modeling_stablelm.py,sha256=DmRces0LIF0s84vdEPmdpaKCSajxP_nKfhEt88Hfsh0,45059 +transformers/models/starcoder2/__init__.py,sha256=fZ8HHZCGjxRfVgROe7zuoi9ADIAa4SeqxGHkvKUQiQM,1001 +transformers/models/starcoder2/__pycache__/__init__.cpython-310.pyc,, +transformers/models/starcoder2/__pycache__/configuration_starcoder2.cpython-310.pyc,, +transformers/models/starcoder2/__pycache__/modeling_starcoder2.cpython-310.pyc,, +transformers/models/starcoder2/__pycache__/modular_starcoder2.cpython-310.pyc,, +transformers/models/starcoder2/configuration_starcoder2.py,sha256=o7FQ_LonUW6vTd8nNQuM44S_-0ypa21kwluLvrYZ3_k,10898 +transformers/models/starcoder2/modeling_starcoder2.py,sha256=bFBfPK5y0sjF23tnWkmVkdwpcViyMTzpvph_CrxjXrI,21537 +transformers/models/starcoder2/modular_starcoder2.py,sha256=vgdQ04BgCPTHEYbcme0EjQk1IGZ7E8GgTSPjf75DRIA,9875 +transformers/models/superglue/__init__.py,sha256=Sg_nfSbBltkVhp40pVc04SthUCnXMX3kWHH_qC_YL4Y,1045 +transformers/models/superglue/__pycache__/__init__.cpython-310.pyc,, +transformers/models/superglue/__pycache__/configuration_superglue.cpython-310.pyc,, +transformers/models/superglue/__pycache__/image_processing_superglue.cpython-310.pyc,, +transformers/models/superglue/__pycache__/modeling_superglue.cpython-310.pyc,, +transformers/models/superglue/configuration_superglue.py,sha256=WD-orzD73GN0s_3On6qcv0jRS7PwC1yjgNBPNnXpOzc,5473 +transformers/models/superglue/image_processing_superglue.py,sha256=eKPx9qButG26SGKLQ5zaQQKjxQmM2ZDXiQ0b7_51D38,21954 +transformers/models/superglue/modeling_superglue.py,sha256=bBVf-RB3Vp2YO5dnlTfeLCBLcGkI7jCUSx5nad4jTIA,36118 +transformers/models/superpoint/__init__.py,sha256=6fQQ-p4220IUaIQCZseKItiHWVV7KOiA5mXoTdJSJmI,1100 +transformers/models/superpoint/__pycache__/__init__.cpython-310.pyc,, +transformers/models/superpoint/__pycache__/configuration_superpoint.cpython-310.pyc,, +transformers/models/superpoint/__pycache__/image_processing_superpoint.cpython-310.pyc,, +transformers/models/superpoint/__pycache__/image_processing_superpoint_fast.cpython-310.pyc,, +transformers/models/superpoint/__pycache__/modeling_superpoint.cpython-310.pyc,, +transformers/models/superpoint/configuration_superpoint.py,sha256=wWW7CLDM2VW-f41M_hLvq4N3j1gt_4QmsaNHifKLd_I,4048 +transformers/models/superpoint/image_processing_superpoint.py,sha256=5eUYxWamNm6Jm_mEhfJQYs2yxFH5AKgaM6XheXLXvBE,16414 +transformers/models/superpoint/image_processing_superpoint_fast.py,sha256=LxdFQ7JrXE1nAcB93KJqTkJayTZ4MuQnAwJqIHXUZ5Y,6837 +transformers/models/superpoint/modeling_superpoint.py,sha256=iqN6g4a2Yt8I-tantOd66ajRukiCzl1PcLFUIMDv71I,20071 +transformers/models/swiftformer/__init__.py,sha256=cW3-9efPxdjZV1KziM8j1S8e8wH3wJQhWqMXlULhG6c,1046 +transformers/models/swiftformer/__pycache__/__init__.cpython-310.pyc,, +transformers/models/swiftformer/__pycache__/configuration_swiftformer.cpython-310.pyc,, +transformers/models/swiftformer/__pycache__/modeling_swiftformer.cpython-310.pyc,, +transformers/models/swiftformer/__pycache__/modeling_tf_swiftformer.cpython-310.pyc,, +transformers/models/swiftformer/configuration_swiftformer.py,sha256=zc6uduEgdxwc_ApNrsADFqGSKC1qlH-kceHSuUWHQCI,5867 +transformers/models/swiftformer/modeling_swiftformer.py,sha256=p3RkkRJsjzLOC835594Q94T2tAv-91nG4V8cc8nk4v4,19526 +transformers/models/swiftformer/modeling_tf_swiftformer.py,sha256=BtStZyRloUcoWu3km_TLihPzMPiXA5QT88WQthuMS8Q,34959 +transformers/models/swin/__init__.py,sha256=7pcdahUG9WcEkEDRoUcMVxdonKglhOpXaQLo8xI6KTg,1025 +transformers/models/swin/__pycache__/__init__.cpython-310.pyc,, +transformers/models/swin/__pycache__/configuration_swin.cpython-310.pyc,, +transformers/models/swin/__pycache__/modeling_swin.cpython-310.pyc,, +transformers/models/swin/__pycache__/modeling_tf_swin.cpython-310.pyc,, +transformers/models/swin/configuration_swin.py,sha256=hcksE44MGT9_rWYNXvhyl94jqU00rQY3XXTDPzTlvmo,7958 +transformers/models/swin/modeling_swin.py,sha256=iwOA2YKG5e9jnxJUP_BdBObjRslIvDpCi7XxOetVnFg,54742 +transformers/models/swin/modeling_tf_swin.py,sha256=1ql5W5rY6oxRDd24dj-RGsWy-onKGQbeN1JZ3KaKdj4,70829 +transformers/models/swin2sr/__init__.py,sha256=PLCBXwTQF37hLur2ROcYXUiNropQ6u5Ig_HgK29MOu8,1088 +transformers/models/swin2sr/__pycache__/__init__.cpython-310.pyc,, +transformers/models/swin2sr/__pycache__/configuration_swin2sr.cpython-310.pyc,, +transformers/models/swin2sr/__pycache__/image_processing_swin2sr.cpython-310.pyc,, +transformers/models/swin2sr/__pycache__/image_processing_swin2sr_fast.cpython-310.pyc,, +transformers/models/swin2sr/__pycache__/modeling_swin2sr.cpython-310.pyc,, +transformers/models/swin2sr/configuration_swin2sr.py,sha256=6ZRVIyo6z1oQvPm13QvkrWcKpf1qjMf0QqwmdHMdvto,6841 +transformers/models/swin2sr/image_processing_swin2sr.py,sha256=h3J27aTqsI7mmVpttQOFYQt0pyYHk68MQhOZyFs53fc,9838 +transformers/models/swin2sr/image_processing_swin2sr_fast.py,sha256=o8qCErIx9f7RXomvEPCH9yUYqIEbUpprFaBCUdcDfCY,4699 +transformers/models/swin2sr/modeling_swin2sr.py,sha256=JCTeuihUJgaE-VddIkKaS5uKqFJ2PwDQf_ILEkt27xU,46884 +transformers/models/swinv2/__init__.py,sha256=njM902tlEQ82mYRN9ZTMOiXpJn1NHnxKbm_LCvn2I-M,993 +transformers/models/swinv2/__pycache__/__init__.cpython-310.pyc,, +transformers/models/swinv2/__pycache__/configuration_swinv2.cpython-310.pyc,, +transformers/models/swinv2/__pycache__/modeling_swinv2.cpython-310.pyc,, +transformers/models/swinv2/configuration_swinv2.py,sha256=m2yjnprZXcqtF4dlw2JAv8MWjBBm6khztGzCUAp4rHw,7547 +transformers/models/swinv2/modeling_swinv2.py,sha256=FynHY4dYJa4H1D-M4wQ37rZkYuPe0ITfSFEhSZjb0fE,58956 +transformers/models/switch_transformers/__init__.py,sha256=Iw38A9kfIT5mJ0G00YE-TVN-M_b1DBHYQqb0pEyTZMY,1019 +transformers/models/switch_transformers/__pycache__/__init__.cpython-310.pyc,, +transformers/models/switch_transformers/__pycache__/configuration_switch_transformers.cpython-310.pyc,, +transformers/models/switch_transformers/__pycache__/modeling_switch_transformers.cpython-310.pyc,, +transformers/models/switch_transformers/configuration_switch_transformers.py,sha256=hqXjdBHj-oqNPBPzwH-e5-dKYDPw2lfWgc3oDegHHVE,9054 +transformers/models/switch_transformers/modeling_switch_transformers.py,sha256=WstSfVCgfkvOOl3sTbTwxHbLSgHo6wUhnyZgcDShKoM,84654 +transformers/models/t5/__init__.py,sha256=hCQO8nkKAJqFgMOwC7nxhyDYOUA9fcDT0pDb7DAHt5Y,1130 +transformers/models/t5/__pycache__/__init__.cpython-310.pyc,, +transformers/models/t5/__pycache__/configuration_t5.cpython-310.pyc,, +transformers/models/t5/__pycache__/modeling_flax_t5.cpython-310.pyc,, +transformers/models/t5/__pycache__/modeling_t5.cpython-310.pyc,, +transformers/models/t5/__pycache__/modeling_tf_t5.cpython-310.pyc,, +transformers/models/t5/__pycache__/tokenization_t5.cpython-310.pyc,, +transformers/models/t5/__pycache__/tokenization_t5_fast.cpython-310.pyc,, +transformers/models/t5/configuration_t5.py,sha256=1fXcdM1_SwAjVwAo2pyiWoxXuoZ6meJaqI6btUPH-bU,7381 +transformers/models/t5/modeling_flax_t5.py,sha256=l-uYt9Ze0OemY-eF2BVoCmYomkQeJieRMuozgr7pqk8,74353 +transformers/models/t5/modeling_t5.py,sha256=7hoEP1wDxoSiu7AhPqOz-L4nKgOriEvcpXwx5zFee34,109941 +transformers/models/t5/modeling_tf_t5.py,sha256=lW4_eVKZY317xGPnXt1L-q0fAp44wSXiRb85vOJEjY8,76956 +transformers/models/t5/tokenization_t5.py,sha256=BZJ_dt1beGBH1qWSpa99UHv-hJ3C_jo1zFHKc07yBhA,19952 +transformers/models/t5/tokenization_t5_fast.py,sha256=E1E_dH9RXXh7ei1c1u9Q_518o-n5x0mrhMJlHvlqLb8,10048 +transformers/models/t5gemma/__init__.py,sha256=2QjFw4aK-Ui2JuImfxWN8oeMkMwokEzurG8wPvKv98Y,1005 +transformers/models/t5gemma/__pycache__/__init__.cpython-310.pyc,, +transformers/models/t5gemma/__pycache__/configuration_t5gemma.cpython-310.pyc,, +transformers/models/t5gemma/__pycache__/modeling_t5gemma.cpython-310.pyc,, +transformers/models/t5gemma/__pycache__/modular_t5gemma.cpython-310.pyc,, +transformers/models/t5gemma/configuration_t5gemma.py,sha256=ZJBaR9MKuXG8bs6iKd1iBZTt36OYzgB_pDr4mLcybvo,16241 +transformers/models/t5gemma/modeling_t5gemma.py,sha256=dXtuSbCmEVLgFlCDz2wBcgsz3vDoSlly3A6kh1LsqYM,60720 +transformers/models/t5gemma/modular_t5gemma.py,sha256=bSWw9Ta3q6Aj9iqPTA95fhDwFVUsu1Fb9V_3Ba2k0xA,52346 +transformers/models/table_transformer/__init__.py,sha256=VT-KM0_6LZ6fdOAglbfA8zEhCQuYa6He10Div7WEcD8,1015 +transformers/models/table_transformer/__pycache__/__init__.cpython-310.pyc,, +transformers/models/table_transformer/__pycache__/configuration_table_transformer.cpython-310.pyc,, +transformers/models/table_transformer/__pycache__/modeling_table_transformer.cpython-310.pyc,, +transformers/models/table_transformer/configuration_table_transformer.py,sha256=sXV9fFcqNqz9K7zYPCFZyDXfjr42GhotJ7th5UCdH54,13613 +transformers/models/table_transformer/modeling_table_transformer.py,sha256=RYS0x53pWkPkh8OiSfhBLTe2ioplGetkvQu-RG8Vj1A,61338 +transformers/models/tapas/__init__.py,sha256=DQTmog2nYukVsXxARy8v35SitI0Iv4ZLCGl7zUlLDuI,1066 +transformers/models/tapas/__pycache__/__init__.cpython-310.pyc,, +transformers/models/tapas/__pycache__/configuration_tapas.cpython-310.pyc,, +transformers/models/tapas/__pycache__/modeling_tapas.cpython-310.pyc,, +transformers/models/tapas/__pycache__/modeling_tf_tapas.cpython-310.pyc,, +transformers/models/tapas/__pycache__/tokenization_tapas.cpython-310.pyc,, +transformers/models/tapas/configuration_tapas.py,sha256=i1_a_AArLjS8SkWu0Du8TC7JZBfvMUSku2QteSdfnC4,12293 +transformers/models/tapas/modeling_tapas.py,sha256=6-CTY0FbAgSAl5-_r2AgvFNw_3KeGRa8H7uTjYC6Kwk,108838 +transformers/models/tapas/modeling_tf_tapas.py,sha256=HpG3CLwp21ZKZ39Kew6FakiaWuCuv0ZFXmFdMs2WFlw,112267 +transformers/models/tapas/tokenization_tapas.py,sha256=tN5PcvOE_GT9NOYggB4GYI0kRl3mj_gyqUHDQ0bjGXE,118445 +transformers/models/textnet/__init__.py,sha256=nqXafUk5z5F_61jrGF9gK_sI66uj7kq5sUYrit9bsno,1088 +transformers/models/textnet/__pycache__/__init__.cpython-310.pyc,, +transformers/models/textnet/__pycache__/configuration_textnet.cpython-310.pyc,, +transformers/models/textnet/__pycache__/image_processing_textnet.cpython-310.pyc,, +transformers/models/textnet/__pycache__/image_processing_textnet_fast.cpython-310.pyc,, +transformers/models/textnet/__pycache__/modeling_textnet.cpython-310.pyc,, +transformers/models/textnet/configuration_textnet.py,sha256=ZGtG42UxM2RbWr7pSN1IUIBo74aK8Vq79Gg2-vfFWp4,6212 +transformers/models/textnet/image_processing_textnet.py,sha256=H_Lp_-3oe-_P8dzHEa_BkPn7Gp8mrbiic87Ld4XYkkw,17731 +transformers/models/textnet/image_processing_textnet_fast.py,sha256=OU_nnaC0e9tbMc3r5NYDc_k26PpcR1SUfS7h63Yn4mc,5736 +transformers/models/textnet/modeling_textnet.py,sha256=oy3NC67XYjrbPr8iujuO6fLYdrn6REIZncOkYP1fvEY,15517 +transformers/models/time_series_transformer/__init__.py,sha256=3A_3Wog-6NDwCoBIMtkzJv9slc_wXpzDzsOo-xBQ8hE,1027 +transformers/models/time_series_transformer/__pycache__/__init__.cpython-310.pyc,, +transformers/models/time_series_transformer/__pycache__/configuration_time_series_transformer.cpython-310.pyc,, +transformers/models/time_series_transformer/__pycache__/modeling_time_series_transformer.cpython-310.pyc,, +transformers/models/time_series_transformer/configuration_time_series_transformer.py,sha256=jNs-oZ17yVDy4g-shNyOLoA9pupIt9ZlBbX5BXRLyYo,11695 +transformers/models/time_series_transformer/modeling_time_series_transformer.py,sha256=sqb8fls8_cJ-h2dkfeWrkqCPGgCiCs8FeV-rRn-Npi0,95480 +transformers/models/timesfm/__init__.py,sha256=gcfLgRAbwZThFP98fst9wsoTMB0fkR28tzWYoQIs5qU,995 +transformers/models/timesfm/__pycache__/__init__.cpython-310.pyc,, +transformers/models/timesfm/__pycache__/configuration_timesfm.cpython-310.pyc,, +transformers/models/timesfm/__pycache__/modeling_timesfm.cpython-310.pyc,, +transformers/models/timesfm/__pycache__/modular_timesfm.cpython-310.pyc,, +transformers/models/timesfm/configuration_timesfm.py,sha256=OBKxwrNeeak-YgKtKL4zTgs705E9to4FCbD7wX0J1Gs,5715 +transformers/models/timesfm/modeling_timesfm.py,sha256=oW_6yao7FOzfvlXxGVAsdK2AZlfX7H1f0R77yUDR-oQ,34502 +transformers/models/timesfm/modular_timesfm.py,sha256=RE1ypm8pygCjjZQ2lUfEfwqiY3v8wYdWHJrEsFIkdeo,32164 +transformers/models/timesformer/__init__.py,sha256=4ODuyNRrYkbgpSbMHJX8XmpJdekHlu__zWey-plUSgI,1003 +transformers/models/timesformer/__pycache__/__init__.cpython-310.pyc,, +transformers/models/timesformer/__pycache__/configuration_timesformer.cpython-310.pyc,, +transformers/models/timesformer/__pycache__/modeling_timesformer.cpython-310.pyc,, +transformers/models/timesformer/configuration_timesformer.py,sha256=GilCKil_40B_hqjh0-02CWrBupbwEfHhOZ3b5bUpTPI,5568 +transformers/models/timesformer/modeling_timesformer.py,sha256=C05CUfZFsKM4ckKg8PSJTBUEk8KDo7fFUgqa1HjngGM,32808 +transformers/models/timm_backbone/__init__.py,sha256=s0GlTaJ43Yt9ZdzG9-qjJNlp0Ol4vjN-14S6N7gXLsA,1007 +transformers/models/timm_backbone/__pycache__/__init__.cpython-310.pyc,, +transformers/models/timm_backbone/__pycache__/configuration_timm_backbone.cpython-310.pyc,, +transformers/models/timm_backbone/__pycache__/modeling_timm_backbone.cpython-310.pyc,, +transformers/models/timm_backbone/configuration_timm_backbone.py,sha256=CMRsZX3ZQiI1bzBrza3Eqgjy8XEid8dPfJZVuhtLTn8,3186 +transformers/models/timm_backbone/modeling_timm_backbone.py,sha256=8k2tlfAtgX2FguLvxtXc_15jCjbnq4lXKq_BalsgxT8,6635 +transformers/models/timm_wrapper/__init__.py,sha256=U19BCtZcAQdmBto5bqG6u69W5rnUBtIyP11EcRh_0Tk,1054 +transformers/models/timm_wrapper/__pycache__/__init__.cpython-310.pyc,, +transformers/models/timm_wrapper/__pycache__/configuration_timm_wrapper.cpython-310.pyc,, +transformers/models/timm_wrapper/__pycache__/image_processing_timm_wrapper.cpython-310.pyc,, +transformers/models/timm_wrapper/__pycache__/modeling_timm_wrapper.cpython-310.pyc,, +transformers/models/timm_wrapper/configuration_timm_wrapper.py,sha256=uvp6s_QCjKBXSO461YIEJugvQ6Wbo9BkZ-peFc8nt7s,5509 +transformers/models/timm_wrapper/image_processing_timm_wrapper.py,sha256=hV9q0IaHBS-hl0FwNUwam3uEXWf4sC7YrQTGjMLMR8k,5348 +transformers/models/timm_wrapper/modeling_timm_wrapper.py,sha256=7pxeqAIhm73Zj1bgt64hO7YwGXxfXeBOwX14PnKqcBQ,16677 +transformers/models/trocr/__init__.py,sha256=Hllbq_42XbGRZyXsGOzYHcb33MOA5_yfijMRKEXJ4n4,1027 +transformers/models/trocr/__pycache__/__init__.cpython-310.pyc,, +transformers/models/trocr/__pycache__/configuration_trocr.cpython-310.pyc,, +transformers/models/trocr/__pycache__/modeling_trocr.cpython-310.pyc,, +transformers/models/trocr/__pycache__/processing_trocr.cpython-310.pyc,, +transformers/models/trocr/configuration_trocr.py,sha256=mm8gO1FagOM7OpQ9S7TZ9UrNc7or081ymZz-q3uss3s,6558 +transformers/models/trocr/modeling_trocr.py,sha256=0fAS9zHFFwwVFHbGbKpiqalER5MSNRaHLavOGOXWOsA,39336 +transformers/models/trocr/processing_trocr.py,sha256=ts4bW7BoYIqffiXK4Iin6W1i-5h8AsHbIGBx6SaLBWE,5738 +transformers/models/tvp/__init__.py,sha256=zY4KwnUt4Q8f_afJGLIxUIfZf8RIyOOCbv9tnAJk1ic,1106 +transformers/models/tvp/__pycache__/__init__.cpython-310.pyc,, +transformers/models/tvp/__pycache__/configuration_tvp.cpython-310.pyc,, +transformers/models/tvp/__pycache__/image_processing_tvp.cpython-310.pyc,, +transformers/models/tvp/__pycache__/image_processing_tvp_fast.cpython-310.pyc,, +transformers/models/tvp/__pycache__/modeling_tvp.cpython-310.pyc,, +transformers/models/tvp/__pycache__/processing_tvp.cpython-310.pyc,, +transformers/models/tvp/configuration_tvp.py,sha256=DpgrPqYGfjA6OSNkh5UsdkLw8RWFF6qh90Zrz6U9pn4,10147 +transformers/models/tvp/image_processing_tvp.py,sha256=LRQ9EvVO1MemVGbQqtzLC3zUksA__g-xXZXUHLV_Fh0,22750 +transformers/models/tvp/image_processing_tvp_fast.py,sha256=XIrD2hGP59xpTfkCAqCJnCUrbWkDw_kJTkFwMOKuWkM,8477 +transformers/models/tvp/modeling_tvp.py,sha256=LxF_XsdNsgP-YmJaa_iUCww7RLbN4gwBoX1_dA0VvHY,40032 +transformers/models/tvp/processing_tvp.py,sha256=e1h71Tq5NDHBeea7uS3Kc61m-PisGoYvgss4Q-Tgjdo,2648 +transformers/models/udop/__init__.py,sha256=CqFpHruzC__VtxEcVz31QxxMpBI1mjO77-Lj0RqW4Eo,1103 +transformers/models/udop/__pycache__/__init__.cpython-310.pyc,, +transformers/models/udop/__pycache__/configuration_udop.cpython-310.pyc,, +transformers/models/udop/__pycache__/modeling_udop.cpython-310.pyc,, +transformers/models/udop/__pycache__/processing_udop.cpython-310.pyc,, +transformers/models/udop/__pycache__/tokenization_udop.cpython-310.pyc,, +transformers/models/udop/__pycache__/tokenization_udop_fast.cpython-310.pyc,, +transformers/models/udop/configuration_udop.py,sha256=xzaHEk_1LtY4AqHr10qL2Vt7Yi-CRgCO98Ni_OvRPgg,7675 +transformers/models/udop/modeling_udop.py,sha256=SkHCGohwJ1dpt7-JIeRSzncKsouh3__yWtbYnc-Ktnw,92185 +transformers/models/udop/processing_udop.py,sha256=Huz5GGRLuRhY6S9P9yxzowgz8JC3LozZkoyZUBfRjIY,8642 +transformers/models/udop/tokenization_udop.py,sha256=8wBBqyD99Y_tcP8q_LHZiIITj26kKdMRtLAeaIH91EU,71827 +transformers/models/udop/tokenization_udop_fast.py,sha256=cvfqL2DiAyd2_d5BL14U6XQScBvM8JoGizTM3tLSik0,49663 +transformers/models/umt5/__init__.py,sha256=FKt6Ap3AvOCIKoeOM-5qY84lNEML9IujaDaYROINJMs,989 +transformers/models/umt5/__pycache__/__init__.cpython-310.pyc,, +transformers/models/umt5/__pycache__/configuration_umt5.cpython-310.pyc,, +transformers/models/umt5/__pycache__/modeling_umt5.cpython-310.pyc,, +transformers/models/umt5/configuration_umt5.py,sha256=W60fZhT2upRLbNTauRSs1-K0HSB5aCV4m79TFSXO1VI,7749 +transformers/models/umt5/modeling_umt5.py,sha256=m86drqG6CRNml3lD60ZRP0KbCehBReCvzfgfYepB2Fs,90935 +transformers/models/unispeech/__init__.py,sha256=AXJMExDoYYI71OKNXhAt7lyqcFIvcLHEQ1Fsm171m5w,999 +transformers/models/unispeech/__pycache__/__init__.cpython-310.pyc,, +transformers/models/unispeech/__pycache__/configuration_unispeech.cpython-310.pyc,, +transformers/models/unispeech/__pycache__/modeling_unispeech.cpython-310.pyc,, +transformers/models/unispeech/__pycache__/modular_unispeech.cpython-310.pyc,, +transformers/models/unispeech/configuration_unispeech.py,sha256=THcTvZNOVsDyoVkiDZ5kKGu5hmNu0qM2lal-P-WPDos,17510 +transformers/models/unispeech/modeling_unispeech.py,sha256=8pZQ3HXzcXXzgp8HpjkzniWKKfERCmGHDtQpjIi7hOU,64373 +transformers/models/unispeech/modular_unispeech.py,sha256=A7tDao9K2QPRdy7WpLGKJLWmYFxpp9f4eqAzkCFvtdE,18207 +transformers/models/unispeech_sat/__init__.py,sha256=P9lCzMg01s4Gj_Pb8t1l36MRAeoOcxUa4d7dbQSe9N4,1007 +transformers/models/unispeech_sat/__pycache__/__init__.cpython-310.pyc,, +transformers/models/unispeech_sat/__pycache__/configuration_unispeech_sat.cpython-310.pyc,, +transformers/models/unispeech_sat/__pycache__/modeling_unispeech_sat.cpython-310.pyc,, +transformers/models/unispeech_sat/__pycache__/modular_unispeech_sat.cpython-310.pyc,, +transformers/models/unispeech_sat/configuration_unispeech_sat.py,sha256=3CduPVTYRqVQWaZbD_oA3wsCl_7v95Fn4RuWpPi6VhQ,18855 +transformers/models/unispeech_sat/modeling_unispeech_sat.py,sha256=Ri6oR_eW82UilW8mZ0UMIFSx6OPK2KV-Z9izxQaA3I0,78446 +transformers/models/unispeech_sat/modular_unispeech_sat.py,sha256=UsFpwELhczFJTXGNoHClgGFzP-ZFWBFVQ5HQR6S5KQY,18606 +transformers/models/univnet/__init__.py,sha256=hfHyxyKGEfd58p1fUSA3IxK2q6JkVatkGceVaoKuODk,1041 +transformers/models/univnet/__pycache__/__init__.cpython-310.pyc,, +transformers/models/univnet/__pycache__/configuration_univnet.cpython-310.pyc,, +transformers/models/univnet/__pycache__/feature_extraction_univnet.cpython-310.pyc,, +transformers/models/univnet/__pycache__/modeling_univnet.cpython-310.pyc,, +transformers/models/univnet/configuration_univnet.py,sha256=dwE48PdXxA4_3tbux06b7HAsdUK9c5-capcOdDeAr9c,6758 +transformers/models/univnet/feature_extraction_univnet.py,sha256=9iNfhNCBNRWaY7odFlzXzMLzauhSzgFGdr20sQ4xPWw,22880 +transformers/models/univnet/modeling_univnet.py,sha256=cngw_Vo6uRk_-mG6Fv95xaXDGpxVVEarC7ewQDr2Wqw,25749 +transformers/models/upernet/__init__.py,sha256=Wq3u7yXJul5PLmjalxKgx451sa_WuSXbEM45bZsRv3E,995 +transformers/models/upernet/__pycache__/__init__.cpython-310.pyc,, +transformers/models/upernet/__pycache__/configuration_upernet.cpython-310.pyc,, +transformers/models/upernet/__pycache__/modeling_upernet.cpython-310.pyc,, +transformers/models/upernet/configuration_upernet.py,sha256=ih_8sDO-OzHJOCqUDhtiBOtRanCrLfhx3c6OBZryILI,6859 +transformers/models/upernet/modeling_upernet.py,sha256=vWF4TKPs6t8AxHBVOGsw2BaHRyXnithQ3RFs-iNRHUM,14577 +transformers/models/vaultgemma/__init__.py,sha256=NxMaPmECIwYDSIgI9BuyVwsLmZEwagfSCY2Wy0YAiOQ,1017 +transformers/models/vaultgemma/__pycache__/__init__.cpython-310.pyc,, +transformers/models/vaultgemma/__pycache__/configuration_vaultgemma.cpython-310.pyc,, +transformers/models/vaultgemma/__pycache__/modeling_vaultgemma.cpython-310.pyc,, +transformers/models/vaultgemma/__pycache__/modular_vaultgemma.cpython-310.pyc,, +transformers/models/vaultgemma/configuration_vaultgemma.py,sha256=8PN4wzNi91UmX25nO7IiCXBKqHhGOTa7RBnOZ_VNf8M,9672 +transformers/models/vaultgemma/modeling_vaultgemma.py,sha256=z2r03_vGcAoEbnfspNduvDs2lnqXpW2SAVfOx0tCLHw,24855 +transformers/models/vaultgemma/modular_vaultgemma.py,sha256=_VKyFOSmR1sASCQBBxotRccrOUBqqaXAq0q1svDfj5Q,2802 +transformers/models/video_llava/__init__.py,sha256=bsLGp1WBBO_AvNVRxzOn5k7OYQIbX9SqFhESd24FImc,1093 +transformers/models/video_llava/__pycache__/__init__.cpython-310.pyc,, +transformers/models/video_llava/__pycache__/configuration_video_llava.cpython-310.pyc,, +transformers/models/video_llava/__pycache__/image_processing_video_llava.cpython-310.pyc,, +transformers/models/video_llava/__pycache__/modeling_video_llava.cpython-310.pyc,, +transformers/models/video_llava/__pycache__/processing_video_llava.cpython-310.pyc,, +transformers/models/video_llava/__pycache__/video_processing_video_llava.cpython-310.pyc,, +transformers/models/video_llava/configuration_video_llava.py,sha256=zetmD2cvfHzFEiU8PJn1qWWVPwMgT08YMR3q-DTPukk,6448 +transformers/models/video_llava/image_processing_video_llava.py,sha256=1pqD3NxiK0Y5Eb5JcuExB6t_3ca5wDGNh6TQ-R1V0h8,19160 +transformers/models/video_llava/modeling_video_llava.py,sha256=XJ0nmB_o6gd0-J5U4Cxb1SiaHYxlOhvixRgzeDRt9ak,33549 +transformers/models/video_llava/processing_video_llava.py,sha256=1iOpeBgUC0Lr5Yq8d9g0ytne_13Gg2CR2CWu9CelfxE,10786 +transformers/models/video_llava/video_processing_video_llava.py,sha256=fE7ZIouajWIxNfpJAjpTUqkRQwICpPwzkaVBUutcn2Q,1678 +transformers/models/videomae/__init__.py,sha256=IYw3qXj1-PDmBAp---YaZyqdBsIjdMZQI37xT_-9SgY,1089 +transformers/models/videomae/__pycache__/__init__.cpython-310.pyc,, +transformers/models/videomae/__pycache__/configuration_videomae.cpython-310.pyc,, +transformers/models/videomae/__pycache__/feature_extraction_videomae.cpython-310.pyc,, +transformers/models/videomae/__pycache__/image_processing_videomae.cpython-310.pyc,, +transformers/models/videomae/__pycache__/modeling_videomae.cpython-310.pyc,, +transformers/models/videomae/configuration_videomae.py,sha256=O0BwqYZnc9Q5Kpemmel6rOxeDBSj7KKCxgpHfMVCVGE,6600 +transformers/models/videomae/feature_extraction_videomae.py,sha256=YfjgYL2im5-5OtnL_U9Z72Fxm58jNAIQWkUlszLJEtY,1316 +transformers/models/videomae/image_processing_videomae.py,sha256=JEvCBnW-u36BnclEMi6PC9pyVf_MabxE3y8nHR3-E-E,16791 +transformers/models/videomae/modeling_videomae.py,sha256=6FL19ketIRuIcrBzGXlSKxsGYz4oJkTlaoaU5kjtW48,38363 +transformers/models/vilt/__init__.py,sha256=efaZSTGsk3QhZmBrc6F29q55LkC_1Vb8fNC0MY4881Q,1154 +transformers/models/vilt/__pycache__/__init__.cpython-310.pyc,, +transformers/models/vilt/__pycache__/configuration_vilt.cpython-310.pyc,, +transformers/models/vilt/__pycache__/feature_extraction_vilt.cpython-310.pyc,, +transformers/models/vilt/__pycache__/image_processing_vilt.cpython-310.pyc,, +transformers/models/vilt/__pycache__/image_processing_vilt_fast.cpython-310.pyc,, +transformers/models/vilt/__pycache__/modeling_vilt.cpython-310.pyc,, +transformers/models/vilt/__pycache__/processing_vilt.cpython-310.pyc,, +transformers/models/vilt/configuration_vilt.py,sha256=B7lnWQV7QC5CeliGPQF5TP5Ci-s35bv7_LX4UvOVNUs,6817 +transformers/models/vilt/feature_extraction_vilt.py,sha256=OYz67RYXTxX9oQpJ9b-lSzCduexmgugUpkiPHSfcs9s,1284 +transformers/models/vilt/image_processing_vilt.py,sha256=MWYvUw6fi9XIJOI2FJ379a8wFAto1hO7HTa-L3Y0hgc,23304 +transformers/models/vilt/image_processing_vilt_fast.py,sha256=w2f2VPmSVCCcLFiPMKIrjraVnYN7T4pdxCeFFxVpabI,9457 +transformers/models/vilt/modeling_vilt.py,sha256=jG91LCGy1FEUnZnh42EBSI6Y4oHKkhLV_vFzE8SWnPg,57560 +transformers/models/vilt/processing_vilt.py,sha256=N8C1XiqnMb7a5SbMDiDlIqdrm31K-XjAEQn1jCGc0Vk,3371 +transformers/models/vipllava/__init__.py,sha256=HJ5mZUNdt_bmaC9l-GycD7mVT2r1oN15prmnlBtz6oA,997 +transformers/models/vipllava/__pycache__/__init__.cpython-310.pyc,, +transformers/models/vipllava/__pycache__/configuration_vipllava.cpython-310.pyc,, +transformers/models/vipllava/__pycache__/modeling_vipllava.cpython-310.pyc,, +transformers/models/vipllava/__pycache__/modular_vipllava.cpython-310.pyc,, +transformers/models/vipllava/configuration_vipllava.py,sha256=BUvvdV2CgiEp5h-pWbuEUi7t8bnkl6haqljNtf3en6c,5049 +transformers/models/vipllava/modeling_vipllava.py,sha256=e54zVMrTPBuour9sgr5DfwNriKkfDGtWVAP1pZ2Uj9A,20614 +transformers/models/vipllava/modular_vipllava.py,sha256=1K_TeonOFDO_UZR_6MBHOJyGW5V8Vx6pNWg3u1pqv8Y,12339 +transformers/models/vision_encoder_decoder/__init__.py,sha256=xK5xKVeIOZSN1d9Y2nDa3NYkLdGidbwgQ6Es8JhzKzA,1135 +transformers/models/vision_encoder_decoder/__pycache__/__init__.cpython-310.pyc,, +transformers/models/vision_encoder_decoder/__pycache__/configuration_vision_encoder_decoder.cpython-310.pyc,, +transformers/models/vision_encoder_decoder/__pycache__/modeling_flax_vision_encoder_decoder.cpython-310.pyc,, +transformers/models/vision_encoder_decoder/__pycache__/modeling_tf_vision_encoder_decoder.cpython-310.pyc,, +transformers/models/vision_encoder_decoder/__pycache__/modeling_vision_encoder_decoder.cpython-310.pyc,, +transformers/models/vision_encoder_decoder/configuration_vision_encoder_decoder.py,sha256=6uLyTC16qnr7xboS9yTb1C6OvVWu2snFata6p85Crcs,8475 +transformers/models/vision_encoder_decoder/modeling_flax_vision_encoder_decoder.py,sha256=K_vwvC2W7Sz_j4gh3DbnplwdIH3zRNA5Tlk9v-qbxBw,41615 +transformers/models/vision_encoder_decoder/modeling_tf_vision_encoder_decoder.py,sha256=t7zHO-hBGMm-wlMQQN7x-nCBqUclSXP93U--Iun8iG8,36115 +transformers/models/vision_encoder_decoder/modeling_vision_encoder_decoder.py,sha256=L3UvMzl75fC-koHjos9bmnmq7i1_Qk7cl0IF19Xc4so,29373 +transformers/models/vision_text_dual_encoder/__init__.py,sha256=LRXs5oXk4_8AaHuIVaj1IgBO4X1vwP-ehQC1T1xEiAI,1198 +transformers/models/vision_text_dual_encoder/__pycache__/__init__.cpython-310.pyc,, +transformers/models/vision_text_dual_encoder/__pycache__/configuration_vision_text_dual_encoder.cpython-310.pyc,, +transformers/models/vision_text_dual_encoder/__pycache__/modeling_flax_vision_text_dual_encoder.cpython-310.pyc,, +transformers/models/vision_text_dual_encoder/__pycache__/modeling_tf_vision_text_dual_encoder.cpython-310.pyc,, +transformers/models/vision_text_dual_encoder/__pycache__/modeling_vision_text_dual_encoder.cpython-310.pyc,, +transformers/models/vision_text_dual_encoder/__pycache__/processing_vision_text_dual_encoder.cpython-310.pyc,, +transformers/models/vision_text_dual_encoder/configuration_vision_text_dual_encoder.py,sha256=Zqb3nGZWG-J3a2FPUY4ocbDYWiLVeZOiFua-MXTDUfQ,5023 +transformers/models/vision_text_dual_encoder/modeling_flax_vision_text_dual_encoder.py,sha256=ejVh6jvNJhfxXc70KAyy0UZxj_xWpcrly7sbUclBi54,26399 +transformers/models/vision_text_dual_encoder/modeling_tf_vision_text_dual_encoder.py,sha256=NnCOaAYtjQ4yUv90Am7cHnxKU9VgDDnXGQqnJSsgEs4,28626 +transformers/models/vision_text_dual_encoder/modeling_vision_text_dual_encoder.py,sha256=1kiv0PqgdNXflKJDA5fxpfbYRQu1ewfCS1OG8bFFqhA,17987 +transformers/models/vision_text_dual_encoder/processing_vision_text_dual_encoder.py,sha256=T7I9V7xJoBWFtXYu9QgFE5NgImm2gfuu2ymKbUozGXA,2854 +transformers/models/visual_bert/__init__.py,sha256=zZFHfkE7OUMZUwYvB7v4ZIBXVUW9Mboqoa1QdTQURWM,1003 +transformers/models/visual_bert/__pycache__/__init__.cpython-310.pyc,, +transformers/models/visual_bert/__pycache__/configuration_visual_bert.cpython-310.pyc,, +transformers/models/visual_bert/__pycache__/modeling_visual_bert.cpython-310.pyc,, +transformers/models/visual_bert/configuration_visual_bert.py,sha256=4U17YnlSjbOpzsAPdGH_EfvBjv7jppbHWlmLBrchGM4,6767 +transformers/models/visual_bert/modeling_visual_bert.py,sha256=5CvusWewEyuj_U-RXAzI_76POb8eQ5VP7-XMfdXZ-vk,70212 +transformers/models/vit/__init__.py,sha256=uTQRjeWgJLHyXfc7yVOEyv7wnr42Jhy-8p9k5UUbxAM,1186 +transformers/models/vit/__pycache__/__init__.cpython-310.pyc,, +transformers/models/vit/__pycache__/configuration_vit.cpython-310.pyc,, +transformers/models/vit/__pycache__/feature_extraction_vit.cpython-310.pyc,, +transformers/models/vit/__pycache__/image_processing_vit.cpython-310.pyc,, +transformers/models/vit/__pycache__/image_processing_vit_fast.cpython-310.pyc,, +transformers/models/vit/__pycache__/modeling_flax_vit.cpython-310.pyc,, +transformers/models/vit/__pycache__/modeling_tf_vit.cpython-310.pyc,, +transformers/models/vit/__pycache__/modeling_vit.cpython-310.pyc,, +transformers/models/vit/configuration_vit.py,sha256=qzjqndsRc6Pyd8YiTFvAbe-OIIJyRSPOdUFKVSJB2Fg,6290 +transformers/models/vit/feature_extraction_vit.py,sha256=v5PPSon24ldH0wC-42BQTxGakc-ow2aUh-Egq5D9hJw,1276 +transformers/models/vit/image_processing_vit.py,sha256=8U9XOAgxjOwLt9HeJtwhpqGNvDA4hM2ZiIQMjhKrHg4,14449 +transformers/models/vit/image_processing_vit_fast.py,sha256=yrkXCSNPpRXfBiQhsgLao-dFOALdBrWa4dDOwZvGiwQ,1237 +transformers/models/vit/modeling_flax_vit.py,sha256=95SBab3CAIoD3bwgWfN6Y7v44fR6EHNJVDuPqi-FOX8,25503 +transformers/models/vit/modeling_tf_vit.py,sha256=r__S8GF7AS7xbOpnVp_JOdE4ByH1H1WBnv1CZdGLTmE,37321 +transformers/models/vit/modeling_vit.py,sha256=Bp4JWMEOgGVRouHSQhzSbmv_IffGWuufDzwNveGojKU,28910 +transformers/models/vit_mae/__init__.py,sha256=C8NcxWwzXlNMeMOA9DNHfDYvRF9biIuUduuwhoaTTD8,1034 +transformers/models/vit_mae/__pycache__/__init__.cpython-310.pyc,, +transformers/models/vit_mae/__pycache__/configuration_vit_mae.cpython-310.pyc,, +transformers/models/vit_mae/__pycache__/modeling_tf_vit_mae.cpython-310.pyc,, +transformers/models/vit_mae/__pycache__/modeling_vit_mae.cpython-310.pyc,, +transformers/models/vit_mae/configuration_vit_mae.py,sha256=3nnWDAbp6WLfOHLO3taJUNEuGRlk3oAa0qaLEEJgjHQ,6372 +transformers/models/vit_mae/modeling_tf_vit_mae.py,sha256=GKXpysqOcon8KW-3KRQoG9mvLBb5b8mIk2Ix6VQyYhE,58009 +transformers/models/vit_mae/modeling_vit_mae.py,sha256=PSW194r_6IgNb6uFUf4ojqGSqnbc6hhh5DUiTBc0ZHk,40948 +transformers/models/vit_msn/__init__.py,sha256=Y1g56VRSNr-PxS-g4Cp2IlRR5M9CiaFGlhAQXwszGHo,995 +transformers/models/vit_msn/__pycache__/__init__.cpython-310.pyc,, +transformers/models/vit_msn/__pycache__/configuration_vit_msn.cpython-310.pyc,, +transformers/models/vit_msn/__pycache__/modeling_vit_msn.cpython-310.pyc,, +transformers/models/vit_msn/configuration_vit_msn.py,sha256=HeU0UloranISU9zLiPsK0CyooMacqogTNmwE4xp2N-o,4864 +transformers/models/vit_msn/modeling_vit_msn.py,sha256=qz3Z3PJOzoEsgZvR8hHkW31yX9iMLE8vsnj5jWhCK_w,24236 +transformers/models/vitdet/__init__.py,sha256=13LNGZwvKK3tBrQWVs43rQbxbgqvxLfnM0uMqomHqhM,993 +transformers/models/vitdet/__pycache__/__init__.cpython-310.pyc,, +transformers/models/vitdet/__pycache__/configuration_vitdet.cpython-310.pyc,, +transformers/models/vitdet/__pycache__/modeling_vitdet.cpython-310.pyc,, +transformers/models/vitdet/configuration_vitdet.py,sha256=CM18kVFmgjDEp7leQPG0L60VKNmBebmxYvEGZN4Kvlg,7541 +transformers/models/vitdet/modeling_vitdet.py,sha256=CqmO4bK5mRE-wNA6DhoYv6-ms0b4Xqhqo47-W7VS-XY,32365 +transformers/models/vitmatte/__init__.py,sha256=al6dWrth9LhRLjmVZrxSi0SRcMMUH_UNpMmR5nwflSc,1092 +transformers/models/vitmatte/__pycache__/__init__.cpython-310.pyc,, +transformers/models/vitmatte/__pycache__/configuration_vitmatte.cpython-310.pyc,, +transformers/models/vitmatte/__pycache__/image_processing_vitmatte.cpython-310.pyc,, +transformers/models/vitmatte/__pycache__/image_processing_vitmatte_fast.cpython-310.pyc,, +transformers/models/vitmatte/__pycache__/modeling_vitmatte.cpython-310.pyc,, +transformers/models/vitmatte/configuration_vitmatte.py,sha256=QRQbE4An9rWLaj4L1UgDo9JipXKVPyPPahJiMKXyQBQ,6498 +transformers/models/vitmatte/image_processing_vitmatte.py,sha256=5SxTOzvoLuVuB0qZlpJQM9ueeBm9mFTYXXsFDiq_hTo,14172 +transformers/models/vitmatte/image_processing_vitmatte_fast.py,sha256=hTo238U2zVVh-2IWVP5cYsJK6vXH1LaNyhHQmvWsRD4,6828 +transformers/models/vitmatte/modeling_vitmatte.py,sha256=Xw_A4MvjsM34PDy5XxkZ26mbYm7WP8wiYhbVc4O6k0Y,10618 +transformers/models/vitpose/__init__.py,sha256=VA7aRcVMgFJH46i6HurkXJS0Z38BotU3H3o3e2wgyXU,1039 +transformers/models/vitpose/__pycache__/__init__.cpython-310.pyc,, +transformers/models/vitpose/__pycache__/configuration_vitpose.cpython-310.pyc,, +transformers/models/vitpose/__pycache__/image_processing_vitpose.cpython-310.pyc,, +transformers/models/vitpose/__pycache__/modeling_vitpose.cpython-310.pyc,, +transformers/models/vitpose/configuration_vitpose.py,sha256=Ij3xe1cFLDOuIJYUTh-SP2UPKSf9pHwXlLwKRDtcqdc,6015 +transformers/models/vitpose/image_processing_vitpose.py,sha256=hsHxTJOi9q3CV76VvGwGTMVtEjeAyDdCpc1vZj1OlMw,29606 +transformers/models/vitpose/modeling_vitpose.py,sha256=AtYwmW5WassxYj1nYjfs71IPoalS6L0WUWLmpOJ_q6k,11683 +transformers/models/vitpose_backbone/__init__.py,sha256=W5IjP47Ykg5KRs8S9ztAbtfQ__n6sbJUZG4UDIGdGmA,577 +transformers/models/vitpose_backbone/__pycache__/__init__.cpython-310.pyc,, +transformers/models/vitpose_backbone/__pycache__/configuration_vitpose_backbone.cpython-310.pyc,, +transformers/models/vitpose_backbone/__pycache__/modeling_vitpose_backbone.cpython-310.pyc,, +transformers/models/vitpose_backbone/configuration_vitpose_backbone.py,sha256=k17SrNK_1I7cE43C3Cu2ZU5V5VnWQA7RsmOSSzXCEME,6651 +transformers/models/vitpose_backbone/modeling_vitpose_backbone.py,sha256=i8KBSXswCAUFuPLjYDVhq0uOy0Y7jXMWILOsK6OP-hU,19298 +transformers/models/vits/__init__.py,sha256=7baZcqGvFlYQxAl721XtMptMZKkzvBOa2ttyOhqhUtk,1026 +transformers/models/vits/__pycache__/__init__.cpython-310.pyc,, +transformers/models/vits/__pycache__/configuration_vits.cpython-310.pyc,, +transformers/models/vits/__pycache__/modeling_vits.cpython-310.pyc,, +transformers/models/vits/__pycache__/tokenization_vits.cpython-310.pyc,, +transformers/models/vits/configuration_vits.py,sha256=OT42q2ihf2Q9r9qm7JJM4gJlOqQSZyVH8Jk3Qsbcji0,13892 +transformers/models/vits/modeling_vits.py,sha256=E-hWgCI2LT1Y-EkF44ixlPCzzT88cbp7t5ZgYv-_tBM,61936 +transformers/models/vits/tokenization_vits.py,sha256=hMWf72PabgSlH-UJjN4-ddrNQGb8n5e7d5mSXuGTK9U,9369 +transformers/models/vivit/__init__.py,sha256=LT2FipIBdB69s9UY4viyuB5q2e0v3bCwtQMiOEOj2xg,1033 +transformers/models/vivit/__pycache__/__init__.cpython-310.pyc,, +transformers/models/vivit/__pycache__/configuration_vivit.cpython-310.pyc,, +transformers/models/vivit/__pycache__/image_processing_vivit.cpython-310.pyc,, +transformers/models/vivit/__pycache__/modeling_vivit.cpython-310.pyc,, +transformers/models/vivit/configuration_vivit.py,sha256=TVsjmzoXac2Xh0zcHS8fy0RmFivbol3WsO7kj-gKZik,5142 +transformers/models/vivit/image_processing_vivit.py,sha256=i4-HurrJ_6igx1IpIRE1WhKgCsupxw5z6o0sCKvVxa0,19265 +transformers/models/vivit/modeling_vivit.py,sha256=x46lNFWgTiYiFALbOg4tAtl0hYPdApCWzo8cMwchTKg,28598 +transformers/models/vjepa2/__init__.py,sha256=uG8tvHYoCxXAMjQuCfsT56YCg0l8_2e6H5Nm7L7Ygm0,1056 +transformers/models/vjepa2/__pycache__/__init__.cpython-310.pyc,, +transformers/models/vjepa2/__pycache__/configuration_vjepa2.cpython-310.pyc,, +transformers/models/vjepa2/__pycache__/modeling_vjepa2.cpython-310.pyc,, +transformers/models/vjepa2/__pycache__/video_processing_vjepa2.cpython-310.pyc,, +transformers/models/vjepa2/configuration_vjepa2.py,sha256=mpPeIpTffMjlfOJ5m0mM_wj16znJAKUabh3S1EGvcoM,7055 +transformers/models/vjepa2/modeling_vjepa2.py,sha256=IE0u06fWlVrLMUg8w7d-VXHRrviU28yuAW7U_QHz8xI,48804 +transformers/models/vjepa2/video_processing_vjepa2.py,sha256=_I9Z3HJE5Bx__XtvlWv1jxBAK3vXvtHA9it15fkJEJI,1928 +transformers/models/voxtral/__init__.py,sha256=hARPigCbvhSlR0iKCDkHcUnsXtoCgXnLFSgZnw5HQus,1053 +transformers/models/voxtral/__pycache__/__init__.cpython-310.pyc,, +transformers/models/voxtral/__pycache__/configuration_voxtral.cpython-310.pyc,, +transformers/models/voxtral/__pycache__/modeling_voxtral.cpython-310.pyc,, +transformers/models/voxtral/__pycache__/modular_voxtral.cpython-310.pyc,, +transformers/models/voxtral/__pycache__/processing_voxtral.cpython-310.pyc,, +transformers/models/voxtral/configuration_voxtral.py,sha256=y_8_udDNsK5Zsy6JAkbIJ7QhMYCDLwHNwp1QhQcYmDs,8474 +transformers/models/voxtral/modeling_voxtral.py,sha256=ef1vCJlFeQKYGnOCvpYFtLIVWC9PJLHgCir5OyE7zpY,23536 +transformers/models/voxtral/modular_voxtral.py,sha256=HAcMFkJD4HPfQp3hBqrftMDCBIkcKQdqypw_YVy2REQ,12050 +transformers/models/voxtral/processing_voxtral.py,sha256=MM-wkQejwvANTtNhDBxMYjPNjL7nlMh_-9yq-J09MCA,19847 +transformers/models/wav2vec2/__init__.py,sha256=5nXyY4dA0h9iNUQZrGAUXtjOnU6KbVq2B1gRzEGEUNI,1206 +transformers/models/wav2vec2/__pycache__/__init__.cpython-310.pyc,, +transformers/models/wav2vec2/__pycache__/configuration_wav2vec2.cpython-310.pyc,, +transformers/models/wav2vec2/__pycache__/feature_extraction_wav2vec2.cpython-310.pyc,, +transformers/models/wav2vec2/__pycache__/modeling_flax_wav2vec2.cpython-310.pyc,, +transformers/models/wav2vec2/__pycache__/modeling_tf_wav2vec2.cpython-310.pyc,, +transformers/models/wav2vec2/__pycache__/modeling_wav2vec2.cpython-310.pyc,, +transformers/models/wav2vec2/__pycache__/processing_wav2vec2.cpython-310.pyc,, +transformers/models/wav2vec2/__pycache__/tokenization_wav2vec2.cpython-310.pyc,, +transformers/models/wav2vec2/configuration_wav2vec2.py,sha256=A4XGuSVpZUfWvd-ZJPkcGhISsBSNtSgUCNU2gN0mZos,20100 +transformers/models/wav2vec2/feature_extraction_wav2vec2.py,sha256=OTlRDKVJjkM2J93nN-PRW8xWetFO6Q7TsoRHLvew2pA,11609 +transformers/models/wav2vec2/modeling_flax_wav2vec2.py,sha256=kfZkGa6MYfKJpYvg1jDkMhEaB2ak9LIEvAOYRa_7H4s,57356 +transformers/models/wav2vec2/modeling_tf_wav2vec2.py,sha256=Q2x2AIfXMKL-c_pJpAYJNf_ZpOAXUYzcazcAbpqn2Xg,78572 +transformers/models/wav2vec2/modeling_wav2vec2.py,sha256=HBnRT5nGI8caqKBYI1l4oGqK9N77Xh9UMh96a3mE5XI,100972 +transformers/models/wav2vec2/processing_wav2vec2.py,sha256=KdHgpfu5Fv8ja2KRmoqr1urQ3mVe7mLqLf8kBswsgIA,8208 +transformers/models/wav2vec2/tokenization_wav2vec2.py,sha256=xaEOdRxousCdBFo4_snzcolYYFEype-apHZsIhhWxLc,38782 +transformers/models/wav2vec2_bert/__init__.py,sha256=DL010VL3ZV3lAugPH-BOTNSgIedotOEaoy8iHo0sC1Q,1051 +transformers/models/wav2vec2_bert/__pycache__/__init__.cpython-310.pyc,, +transformers/models/wav2vec2_bert/__pycache__/configuration_wav2vec2_bert.cpython-310.pyc,, +transformers/models/wav2vec2_bert/__pycache__/modeling_wav2vec2_bert.cpython-310.pyc,, +transformers/models/wav2vec2_bert/__pycache__/modular_wav2vec2_bert.cpython-310.pyc,, +transformers/models/wav2vec2_bert/__pycache__/processing_wav2vec2_bert.cpython-310.pyc,, +transformers/models/wav2vec2_bert/configuration_wav2vec2_bert.py,sha256=XpsUE-kvk4hTixrK5sbClT8A5j46A3XwzBcwWDs5E7g,18142 +transformers/models/wav2vec2_bert/modeling_wav2vec2_bert.py,sha256=hrYFh1l6hB_GdKF7D_ah1yL2Lw7xu-VmXGu-LF0XK0o,66073 +transformers/models/wav2vec2_bert/modular_wav2vec2_bert.py,sha256=nVQeAVL8MLzlX2axaBt4UThy2zHHGVprWAYW9LpjeK8,44929 +transformers/models/wav2vec2_bert/processing_wav2vec2_bert.py,sha256=3lt98gf2ZxejI17pvYNkish_634Qukb99-zQ7cOWqBU,7544 +transformers/models/wav2vec2_conformer/__init__.py,sha256=JBpapW8VF3yck4Bk29xKyUiQZqB_CXLSYtYxXGXAu2Q,1017 +transformers/models/wav2vec2_conformer/__pycache__/__init__.cpython-310.pyc,, +transformers/models/wav2vec2_conformer/__pycache__/configuration_wav2vec2_conformer.cpython-310.pyc,, +transformers/models/wav2vec2_conformer/__pycache__/modeling_wav2vec2_conformer.cpython-310.pyc,, +transformers/models/wav2vec2_conformer/__pycache__/modular_wav2vec2_conformer.cpython-310.pyc,, +transformers/models/wav2vec2_conformer/configuration_wav2vec2_conformer.py,sha256=gBeb_cZC5XCDOmg1llPUQ0ELDS-1u0_eGZRrA98tLxM,20938 +transformers/models/wav2vec2_conformer/modeling_wav2vec2_conformer.py,sha256=eR0Zh5AUECUBvjdg8KPX7PnXM1Mz9mKvjmnaJ_ASWho,85397 +transformers/models/wav2vec2_conformer/modular_wav2vec2_conformer.py,sha256=k94FX7pPHNr8RXy6_aeUnP9aRc1ksCJ4KdC8jj-zybI,30730 +transformers/models/wav2vec2_phoneme/__init__.py,sha256=LV4FKcFYNt0GuJvfsUOwTYVFRVfuzUuclKRybFyN9lk,967 +transformers/models/wav2vec2_phoneme/__pycache__/__init__.cpython-310.pyc,, +transformers/models/wav2vec2_phoneme/__pycache__/tokenization_wav2vec2_phoneme.cpython-310.pyc,, +transformers/models/wav2vec2_phoneme/tokenization_wav2vec2_phoneme.py,sha256=DdFdFOAOhnhy5Iq6U-eno8m-bgLbGC-2xiHauNhszd4,23217 +transformers/models/wav2vec2_with_lm/__init__.py,sha256=yZKHsma85j7AMLB8g8uNXL5D_E5Gc3Vqe-D-V2W15oY,965 +transformers/models/wav2vec2_with_lm/__pycache__/__init__.cpython-310.pyc,, +transformers/models/wav2vec2_with_lm/__pycache__/processing_wav2vec2_with_lm.cpython-310.pyc,, +transformers/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.py,sha256=cxCksE0dl-HONpCWGgzV_gfr-SHiDMhuZaoPB-LTl5Q,30031 +transformers/models/wavlm/__init__.py,sha256=wYnYuOpw2e95lauqDbD7u3OC-Pez8yoRsrgExSh_WJQ,991 +transformers/models/wavlm/__pycache__/__init__.cpython-310.pyc,, +transformers/models/wavlm/__pycache__/configuration_wavlm.cpython-310.pyc,, +transformers/models/wavlm/__pycache__/modeling_wavlm.cpython-310.pyc,, +transformers/models/wavlm/__pycache__/modular_wavlm.cpython-310.pyc,, +transformers/models/wavlm/configuration_wavlm.py,sha256=HrK0dtsxcVB-k3yO2px6RS-TW1lonvx_x8uRkz7iJqQ,18588 +transformers/models/wavlm/modeling_wavlm.py,sha256=LYduqQ4d8uBJFJoki0fJ-KtJbb9ale5dqSIu1Dm2LN8,72561 +transformers/models/wavlm/modular_wavlm.py,sha256=hUsN1PF4AhTRvrwa9gI3KcLoJKdJcNU4j-JPE4e6VnA,23183 +transformers/models/whisper/__init__.py,sha256=qT70wGFDyOsAGuyaHe9if7kn8fxK2shCe6rovr3onw4,1244 +transformers/models/whisper/__pycache__/__init__.cpython-310.pyc,, +transformers/models/whisper/__pycache__/configuration_whisper.cpython-310.pyc,, +transformers/models/whisper/__pycache__/english_normalizer.cpython-310.pyc,, +transformers/models/whisper/__pycache__/feature_extraction_whisper.cpython-310.pyc,, +transformers/models/whisper/__pycache__/generation_whisper.cpython-310.pyc,, +transformers/models/whisper/__pycache__/modeling_flax_whisper.cpython-310.pyc,, +transformers/models/whisper/__pycache__/modeling_tf_whisper.cpython-310.pyc,, +transformers/models/whisper/__pycache__/modeling_whisper.cpython-310.pyc,, +transformers/models/whisper/__pycache__/processing_whisper.cpython-310.pyc,, +transformers/models/whisper/__pycache__/tokenization_whisper.cpython-310.pyc,, +transformers/models/whisper/__pycache__/tokenization_whisper_fast.cpython-310.pyc,, +transformers/models/whisper/configuration_whisper.py,sha256=CZgcgXbDdSSxvAwvJ0BmsVuhJLFOVgeGKnKn83yz978,17102 +transformers/models/whisper/english_normalizer.py,sha256=GmqBtyvGnsz2HXoksWAVu2wxJJJUclq-CSdH40jP51g,22857 +transformers/models/whisper/feature_extraction_whisper.py,sha256=wgnmafrg6l3pLhhG2HkOPW1mzij0zUBxeJwu7IjISmY,16732 +transformers/models/whisper/generation_whisper.py,sha256=9svDWZvMi5tRlLg8F8XR3eVo049vZBnKomGM857HOUk,110511 +transformers/models/whisper/modeling_flax_whisper.py,sha256=Sdt-z5ZQXvD6I501rsCdPHmX5UuVtz1nWCmpt8ub5YY,74027 +transformers/models/whisper/modeling_tf_whisper.py,sha256=AkTDnM5YLd2hN3yjUnB9ILQ5IOW44DCpCvXnTRvT42I,84663 +transformers/models/whisper/modeling_whisper.py,sha256=hRx48api-E7Q0KTf3tR4oFyY9D0mcytW_qLUrMeXKLg,73607 +transformers/models/whisper/processing_whisper.py,sha256=HqD-DDmkNIbHgDLFgky6hYu8WeuOv0kV6nFkDNBE4yg,3341 +transformers/models/whisper/tokenization_whisper.py,sha256=JxHC6ryKd8kjOLXOIjKf37jdEf48Y1McdrWcmotRLHc,58409 +transformers/models/whisper/tokenization_whisper_fast.py,sha256=Q6HdLOFUejR-aEIJZo0SkCkIQCtFL7eSSyvSEJWbaJ0,30284 +transformers/models/x_clip/__init__.py,sha256=ufjh6w7SNuNAUjAHp_MK3yRcrHm22-SfhZ0ZfbiXhGw,1030 +transformers/models/x_clip/__pycache__/__init__.cpython-310.pyc,, +transformers/models/x_clip/__pycache__/configuration_x_clip.cpython-310.pyc,, +transformers/models/x_clip/__pycache__/modeling_x_clip.cpython-310.pyc,, +transformers/models/x_clip/__pycache__/processing_x_clip.cpython-310.pyc,, +transformers/models/x_clip/configuration_x_clip.py,sha256=_KPmQFusZP23e1Kh31SxJiR9qaaGm_dt1SsDS7DKUGs,18232 +transformers/models/x_clip/modeling_x_clip.py,sha256=xvrQ5FummEpKtwQ60sE6tDHk9FkL1W_8z15fzlcE2aM,63671 +transformers/models/x_clip/processing_x_clip.py,sha256=LpeVPYVnsiO_ZSPyOxbTaRT4OToiWjVXU0ygaoqVtbs,2735 +transformers/models/xcodec/__init__.py,sha256=X16pTVB3loZ9OMnqHAaxInF1X5EOhxlmHjyxEvoqSWE,993 +transformers/models/xcodec/__pycache__/__init__.cpython-310.pyc,, +transformers/models/xcodec/__pycache__/configuration_xcodec.cpython-310.pyc,, +transformers/models/xcodec/__pycache__/modeling_xcodec.cpython-310.pyc,, +transformers/models/xcodec/configuration_xcodec.py,sha256=8V_u-p5JvxnpvH1ajT0GF5kb5Yh_FPrP9tydEusfHqQ,7932 +transformers/models/xcodec/modeling_xcodec.py,sha256=cVD7a8daBZLnu1ZO--mbGkVwc0zEyollfxeAkJTr9js,24209 +transformers/models/xglm/__init__.py,sha256=ZU7tQBmBXzr8wh9MJNDZ5uIrsCRQP8tuNrpGDd2W3OI,1142 +transformers/models/xglm/__pycache__/__init__.cpython-310.pyc,, +transformers/models/xglm/__pycache__/configuration_xglm.cpython-310.pyc,, +transformers/models/xglm/__pycache__/modeling_flax_xglm.cpython-310.pyc,, +transformers/models/xglm/__pycache__/modeling_tf_xglm.cpython-310.pyc,, +transformers/models/xglm/__pycache__/modeling_xglm.cpython-310.pyc,, +transformers/models/xglm/__pycache__/tokenization_xglm.cpython-310.pyc,, +transformers/models/xglm/__pycache__/tokenization_xglm_fast.cpython-310.pyc,, +transformers/models/xglm/configuration_xglm.py,sha256=m0sfPYf0qKl0pT9sOd3ssoQv13yt5IWRnUn11aGDa1Q,5881 +transformers/models/xglm/modeling_flax_xglm.py,sha256=BLW965ik0iRDR9fGbbw82SyuDxNs__9qKdQxZLPq7XI,33217 +transformers/models/xglm/modeling_tf_xglm.py,sha256=CHMd92nY-UsHA-lPDKOKdrPXHKUFWh3_7CDEGvmzy3E,45026 +transformers/models/xglm/modeling_xglm.py,sha256=wB6TSPD3hSbzyjnetdpqV3_5b92eH8QvWLRhWJYMeus,32780 +transformers/models/xglm/tokenization_xglm.py,sha256=lzdJEYP3S8w-HLa5nX7BAllqXQWnmr49kQsSYl3Cxe4,12576 +transformers/models/xglm/tokenization_xglm_fast.py,sha256=4G278mqxvBG0onsXTichXPRki94OiZJZ3Ioy4t6TfKQ,7470 +transformers/models/xlm/__init__.py,sha256=QevE83gMJ5h41H7EKxRAUN-kmE0zgOsyGj6QzWcpjmk,1058 +transformers/models/xlm/__pycache__/__init__.cpython-310.pyc,, +transformers/models/xlm/__pycache__/configuration_xlm.cpython-310.pyc,, +transformers/models/xlm/__pycache__/modeling_tf_xlm.cpython-310.pyc,, +transformers/models/xlm/__pycache__/modeling_xlm.cpython-310.pyc,, +transformers/models/xlm/__pycache__/tokenization_xlm.cpython-310.pyc,, +transformers/models/xlm/configuration_xlm.py,sha256=k216zyLI3r20HXsFfesj0QQiF-4oCxjUM3ONCxJZtzY,11062 +transformers/models/xlm/modeling_tf_xlm.py,sha256=kEPNqT6vET9FaGDUoo8-wfmCkmFIMnfU3XVPUyAVN8E,56527 +transformers/models/xlm/modeling_xlm.py,sha256=QXsgSyEFfftnS67zzrGriYKbnn1Ld32m75NMZ6tBy74,75495 +transformers/models/xlm/tokenization_xlm.py,sha256=UH0gOdFyLyiXC6_suxt9R9rWYwZjgFOhwnq6w3Rnq88,23408 +transformers/models/xlm_roberta/__init__.py,sha256=dhjej7PBi8UrfXRkTxh9CWXnw8wuLZHPT9FYFfCkIHg,1184 +transformers/models/xlm_roberta/__pycache__/__init__.cpython-310.pyc,, +transformers/models/xlm_roberta/__pycache__/configuration_xlm_roberta.cpython-310.pyc,, +transformers/models/xlm_roberta/__pycache__/modeling_flax_xlm_roberta.cpython-310.pyc,, +transformers/models/xlm_roberta/__pycache__/modeling_tf_xlm_roberta.cpython-310.pyc,, +transformers/models/xlm_roberta/__pycache__/modeling_xlm_roberta.cpython-310.pyc,, +transformers/models/xlm_roberta/__pycache__/tokenization_xlm_roberta.cpython-310.pyc,, +transformers/models/xlm_roberta/__pycache__/tokenization_xlm_roberta_fast.cpython-310.pyc,, +transformers/models/xlm_roberta/configuration_xlm_roberta.py,sha256=A_vz0mpN0KhV6dbuOO8FR5qFCXXYeSASknBS_kVLXPM,7596 +transformers/models/xlm_roberta/modeling_flax_xlm_roberta.py,sha256=ndYuXyoj_I5xVW2TWB5SrXt_D3hlqShvbOY-tW0eOkM,58777 +transformers/models/xlm_roberta/modeling_tf_xlm_roberta.py,sha256=pFUXeNncEmL8gNGKg3Mwkh6B-db2yKXgnf5ZvrlN-Go,81896 +transformers/models/xlm_roberta/modeling_xlm_roberta.py,sha256=lZTqyS04ctJbjuUp1k4cHdYTRVF0f1IFFHknIxJXjiU,71904 +transformers/models/xlm_roberta/tokenization_xlm_roberta.py,sha256=GYqlEjrwdzxZ1xdDuCpJRAKEZAIPuBdGWetCD7eXpzw,12804 +transformers/models/xlm_roberta/tokenization_xlm_roberta_fast.py,sha256=ojIIHjd2wELfeiFylqMYN0iYMeEaAtimZFOHVAFYkkM,7808 +transformers/models/xlm_roberta_xl/__init__.py,sha256=V0fXTKk2hQmf5dKogCJ0HSiRBxVX-rs7c414ZoZIh28,1009 +transformers/models/xlm_roberta_xl/__pycache__/__init__.cpython-310.pyc,, +transformers/models/xlm_roberta_xl/__pycache__/configuration_xlm_roberta_xl.cpython-310.pyc,, +transformers/models/xlm_roberta_xl/__pycache__/modeling_xlm_roberta_xl.cpython-310.pyc,, +transformers/models/xlm_roberta_xl/configuration_xlm_roberta_xl.py,sha256=f8cw938xnzVrNMZA9C6A0wIQm_mmtUr6EMQAgamN9Sw,7348 +transformers/models/xlm_roberta_xl/modeling_xlm_roberta_xl.py,sha256=H-bkQ_D7sfsq5vGRAW25vN54rqHTgfhWdRt1uRirMe0,67346 +transformers/models/xlnet/__init__.py,sha256=t-UvrFyorGF7VMuATzjrB_cUqKsM-8O9KqxiWjtJqhs,1109 +transformers/models/xlnet/__pycache__/__init__.cpython-310.pyc,, +transformers/models/xlnet/__pycache__/configuration_xlnet.cpython-310.pyc,, +transformers/models/xlnet/__pycache__/modeling_tf_xlnet.cpython-310.pyc,, +transformers/models/xlnet/__pycache__/modeling_xlnet.cpython-310.pyc,, +transformers/models/xlnet/__pycache__/tokenization_xlnet.cpython-310.pyc,, +transformers/models/xlnet/__pycache__/tokenization_xlnet_fast.cpython-310.pyc,, +transformers/models/xlnet/configuration_xlnet.py,sha256=U_WpCoqALv86cbvTXgTVnJwOfl3nzcGTgZJd_9SDhvY,10953 +transformers/models/xlnet/modeling_tf_xlnet.py,sha256=FjkGozmhkH6qIPhQO15VCkDJMWOVj2QD7aCR3Nb12wQ,77744 +transformers/models/xlnet/modeling_xlnet.py,sha256=jOOCwlzqD4b-JU6G0RSUqPF6QFrpfOanNjB3EItFW2w,107152 +transformers/models/xlnet/tokenization_xlnet.py,sha256=8GVn73lPjtz6PljvlLuwvuNCElWfbLHfHtdYaI8XrS8,15800 +transformers/models/xlnet/tokenization_xlnet_fast.py,sha256=ZfWE9TWuq8NC7Q3Z2y-plAofp0o9PtQEu08U4M7Qx6s,9247 +transformers/models/xlstm/__init__.py,sha256=-Vfj7bUcDAD3TguoDgKW0zpzZ8KtOmnUNwSkvL6Df8k,1047 +transformers/models/xlstm/__pycache__/__init__.cpython-310.pyc,, +transformers/models/xlstm/__pycache__/configuration_xlstm.cpython-310.pyc,, +transformers/models/xlstm/__pycache__/modeling_xlstm.cpython-310.pyc,, +transformers/models/xlstm/configuration_xlstm.py,sha256=6jEctcitQnoEpOb-ruRiq0OMmq1mSJkdbc3yMTeHMdY,12847 +transformers/models/xlstm/modeling_xlstm.py,sha256=yDYbYgohmUYC-TDm1ipDiasj5r7rqVbLck7nF9NZauM,66379 +transformers/models/xmod/__init__.py,sha256=WLxIbzC8oCEkMrerWHTy7GLopz0mqocSaacdcyb_BhQ,989 +transformers/models/xmod/__pycache__/__init__.cpython-310.pyc,, +transformers/models/xmod/__pycache__/configuration_xmod.cpython-310.pyc,, +transformers/models/xmod/__pycache__/modeling_xmod.cpython-310.pyc,, +transformers/models/xmod/configuration_xmod.py,sha256=W5bQLbTh3EhMd-Lvseyl28uQhkVVCdPSdhcRXJO7hcg,9180 +transformers/models/xmod/modeling_xmod.py,sha256=gNf0LKpksSuW2QSDQtzD0QBcuScF-qZkdZJ-5IO2LyE,68646 +transformers/models/yolos/__init__.py,sha256=UlbQDtMQJaGRcin-iz6NOEFWT8otanBndRuw4VrWUiQ,1124 +transformers/models/yolos/__pycache__/__init__.cpython-310.pyc,, +transformers/models/yolos/__pycache__/configuration_yolos.cpython-310.pyc,, +transformers/models/yolos/__pycache__/feature_extraction_yolos.cpython-310.pyc,, +transformers/models/yolos/__pycache__/image_processing_yolos.cpython-310.pyc,, +transformers/models/yolos/__pycache__/image_processing_yolos_fast.cpython-310.pyc,, +transformers/models/yolos/__pycache__/modeling_yolos.cpython-310.pyc,, +transformers/models/yolos/__pycache__/modular_yolos.cpython-310.pyc,, +transformers/models/yolos/configuration_yolos.py,sha256=3MosWcNOUgTJ1pTBkCQT852fsnIDHomISTyCShOKo2k,7627 +transformers/models/yolos/feature_extraction_yolos.py,sha256=5wVaZnDzK3ROFChjwHYMHGv1aPmtq1IOqmt100yImtE,1594 +transformers/models/yolos/image_processing_yolos.py,sha256=I_gQH5v6KCmM-o0DFVhcKThLxiSdcsmzC5XXCmmNhWA,67993 +transformers/models/yolos/image_processing_yolos_fast.py,sha256=Y-qfpXBEbSl2Pj75A4MUhG2Pqom6JKuUoShK2KmCb40,36609 +transformers/models/yolos/modeling_yolos.py,sha256=I23SChE6JPVUZZXuifPFd1HcfdiwSSrOfOTsNvnLYiM,30708 +transformers/models/yolos/modular_yolos.py,sha256=ec81AdiV3BwrEkb8tQZU_c9O9nntLj0YZ9TntYEEsTY,8239 +transformers/models/yoso/__init__.py,sha256=sCXsXYZuOQLFkZMexRb8qY7EJCftR54G_eO7qIUvdss,989 +transformers/models/yoso/__pycache__/__init__.cpython-310.pyc,, +transformers/models/yoso/__pycache__/configuration_yoso.cpython-310.pyc,, +transformers/models/yoso/__pycache__/modeling_yoso.cpython-310.pyc,, +transformers/models/yoso/configuration_yoso.py,sha256=6PQqt0OjHQBTNnnhDE761sdwlq9_tqG48UJ-pBV3rBM,6715 +transformers/models/yoso/modeling_yoso.py,sha256=GlEYsQNJm2Uj3j3dOPCR7GsDTNIu49nmqi6AJoCHdeI,49723 +transformers/models/zamba/__init__.py,sha256=iqZnf8BQ49TLcB4mYwIfuJeF4aGvYhOBRiGI6_74ZFk,991 +transformers/models/zamba/__pycache__/__init__.cpython-310.pyc,, +transformers/models/zamba/__pycache__/configuration_zamba.cpython-310.pyc,, +transformers/models/zamba/__pycache__/modeling_zamba.cpython-310.pyc,, +transformers/models/zamba/configuration_zamba.py,sha256=0sHrNCBHaMWoTLegdBSl2WFQBQtyMj4qb_XNO5cUM64,11292 +transformers/models/zamba/modeling_zamba.py,sha256=DeYNv2grFHL9aAMCBWiUaueynTAX1Wnt8NFX-uTKFHk,63188 +transformers/models/zamba2/__init__.py,sha256=3FgH8KelorllnKF6ncpKGREwZXt6YwsQ7NPS8W6jcmQ,993 +transformers/models/zamba2/__pycache__/__init__.cpython-310.pyc,, +transformers/models/zamba2/__pycache__/configuration_zamba2.cpython-310.pyc,, +transformers/models/zamba2/__pycache__/modeling_zamba2.cpython-310.pyc,, +transformers/models/zamba2/__pycache__/modular_zamba2.cpython-310.pyc,, +transformers/models/zamba2/configuration_zamba2.py,sha256=DNZAQNnBwPacTJy1yp7Dd8y9aW7HL3zFwa0xam1Fop8,12734 +transformers/models/zamba2/modeling_zamba2.py,sha256=rIilQ50ayrzmATdDqexIsBSDIODHFfGyQLtPY8r-Wr8,85124 +transformers/models/zamba2/modular_zamba2.py,sha256=4DXLXOTbqQR92R_PEeTZ8lRIAlzp26UXE3zhfPOjgfs,56003 +transformers/models/zoedepth/__init__.py,sha256=BUGUeWtpJJRRdQGT1dIOi-B5v89Ae8eTTxbEmVqiu0k,1092 +transformers/models/zoedepth/__pycache__/__init__.cpython-310.pyc,, +transformers/models/zoedepth/__pycache__/configuration_zoedepth.cpython-310.pyc,, +transformers/models/zoedepth/__pycache__/image_processing_zoedepth.cpython-310.pyc,, +transformers/models/zoedepth/__pycache__/image_processing_zoedepth_fast.cpython-310.pyc,, +transformers/models/zoedepth/__pycache__/modeling_zoedepth.cpython-310.pyc,, +transformers/models/zoedepth/configuration_zoedepth.py,sha256=gRQ2uRqmhfagYNHU3FkWJ4PPirYIe9Ve7GJ7ENW17mk,12972 +transformers/models/zoedepth/image_processing_zoedepth.py,sha256=GJNTg1Zvx7zTxLGvlcN1iGlhhfa5-WsZlJHoGVRZfG8,28203 +transformers/models/zoedepth/image_processing_zoedepth_fast.py,sha256=UxGdJjbLQ_yH7evC7Z4ldZt2I8dXPEk30YT4C32vXh4,13322 +transformers/models/zoedepth/modeling_zoedepth.py,sha256=_SGP87VHSdW3uPkG2fqna52q_h_c5FnKO7kz1UsVxSg,54555 +transformers/onnx/__init__.py,sha256=wALLY4TPOK2iPrFcfZf_WiEmTRAU6dAWHElxGdexr58,1548 +transformers/onnx/__main__.py,sha256=JZ9ZmeRsnDitwTMWb-dFT8W9AEmMoMKLQ3SvbyCkY0w,9497 +transformers/onnx/__pycache__/__init__.cpython-310.pyc,, +transformers/onnx/__pycache__/__main__.cpython-310.pyc,, +transformers/onnx/__pycache__/config.cpython-310.pyc,, +transformers/onnx/__pycache__/convert.cpython-310.pyc,, +transformers/onnx/__pycache__/features.cpython-310.pyc,, +transformers/onnx/__pycache__/utils.cpython-310.pyc,, +transformers/onnx/config.py,sha256=BAsRXnhp8q28Axi0NNpJELcXxId4eqm5Yyd_cWh9cgc,32627 +transformers/onnx/convert.py,sha256=1Skizwf9hyB2CQtNNwjwtuJT9EshegWQNcvPdJp4SNg,19418 +transformers/onnx/features.py,sha256=zRhGiYgzMMfvdh7UvCO9j_y0L9cbVbTSL88cItk_PBg,28276 +transformers/onnx/utils.py,sha256=39Uw_GkFBsTb6ZvMIHRTnI289aQDhc6hwfEapaBGE-o,3625 +transformers/optimization.py,sha256=QbCP-ynCaRYmsiXtOJppTMjmFICBghSjXyFbXDkWe_s,39971 +transformers/optimization_tf.py,sha256=JYL8tVbLyB3puGJ0b2i1gGaidCHSxm8_jYmm7z-ZJ-4,16718 +transformers/pipelines/__init__.py,sha256=uewHAiQR2oMlXCvaF-qXvX2sArzOvxHdcQ_3OgEyym4,85062 +transformers/pipelines/__pycache__/__init__.cpython-310.pyc,, +transformers/pipelines/__pycache__/audio_classification.cpython-310.pyc,, +transformers/pipelines/__pycache__/audio_utils.cpython-310.pyc,, +transformers/pipelines/__pycache__/automatic_speech_recognition.cpython-310.pyc,, +transformers/pipelines/__pycache__/base.cpython-310.pyc,, +transformers/pipelines/__pycache__/depth_estimation.cpython-310.pyc,, +transformers/pipelines/__pycache__/document_question_answering.cpython-310.pyc,, +transformers/pipelines/__pycache__/feature_extraction.cpython-310.pyc,, +transformers/pipelines/__pycache__/fill_mask.cpython-310.pyc,, +transformers/pipelines/__pycache__/image_classification.cpython-310.pyc,, +transformers/pipelines/__pycache__/image_feature_extraction.cpython-310.pyc,, +transformers/pipelines/__pycache__/image_segmentation.cpython-310.pyc,, +transformers/pipelines/__pycache__/image_text_to_text.cpython-310.pyc,, +transformers/pipelines/__pycache__/image_to_image.cpython-310.pyc,, +transformers/pipelines/__pycache__/image_to_text.cpython-310.pyc,, +transformers/pipelines/__pycache__/keypoint_matching.cpython-310.pyc,, +transformers/pipelines/__pycache__/mask_generation.cpython-310.pyc,, +transformers/pipelines/__pycache__/object_detection.cpython-310.pyc,, +transformers/pipelines/__pycache__/pt_utils.cpython-310.pyc,, +transformers/pipelines/__pycache__/question_answering.cpython-310.pyc,, +transformers/pipelines/__pycache__/table_question_answering.cpython-310.pyc,, +transformers/pipelines/__pycache__/text2text_generation.cpython-310.pyc,, +transformers/pipelines/__pycache__/text_classification.cpython-310.pyc,, +transformers/pipelines/__pycache__/text_generation.cpython-310.pyc,, +transformers/pipelines/__pycache__/text_to_audio.cpython-310.pyc,, +transformers/pipelines/__pycache__/token_classification.cpython-310.pyc,, +transformers/pipelines/__pycache__/video_classification.cpython-310.pyc,, +transformers/pipelines/__pycache__/visual_question_answering.cpython-310.pyc,, +transformers/pipelines/__pycache__/zero_shot_audio_classification.cpython-310.pyc,, +transformers/pipelines/__pycache__/zero_shot_classification.cpython-310.pyc,, +transformers/pipelines/__pycache__/zero_shot_image_classification.cpython-310.pyc,, +transformers/pipelines/__pycache__/zero_shot_object_detection.cpython-310.pyc,, +transformers/pipelines/audio_classification.py,sha256=9U6AmVAPfPInduBbdued0nXZpMdj2nWTgV3S0m6golo,11188 +transformers/pipelines/audio_utils.py,sha256=HLzdBFNQOfDyJJbvfMYXZTXlWcjTPLyWaPO6fUulQkk,12271 +transformers/pipelines/automatic_speech_recognition.py,sha256=3BVb2RoO5qinhMT1nCTW1PhANIrC3U0MPNy7Gy9g0ZY,33915 +transformers/pipelines/base.py,sha256=pTwHOzFrYIkMDXEblnKj5sPufhfvXaFixcoibJdPLzA,69144 +transformers/pipelines/depth_estimation.py,sha256=ARwIxnh4S-gn9OgOfJpfNgKpdCD0hQIZg1B925OpPt8,6170 +transformers/pipelines/document_question_answering.py,sha256=eJ1AMIGk-f2xwR9DJOwP_XPKgMjr2kpH_nCz9jlMWyc,25786 +transformers/pipelines/feature_extraction.py,sha256=x6ZmfVcoT9TNWaPyM5S-zep_cCgTsFBFxe7B8QdrVTs,3564 +transformers/pipelines/fill_mask.py,sha256=KR5SmztnwW2C_abrrsz4R58i-Ju61yQGGTVjNCn76Z8,12061 +transformers/pipelines/image_classification.py,sha256=LrAvZRwEC6Cqk9jlST1fD51VO67w6Hjm7q_gMdoxa7k,10232 +transformers/pipelines/image_feature_extraction.py,sha256=24ib-fmsdbN2ZX7PxJvAI3OX1z2x80X8A2IcSF6ynJI,4963 +transformers/pipelines/image_segmentation.py,sha256=BcswPSyXzbC_3IW6EYws10dwJxpBPS9JcrlbevBRD10,9976 +transformers/pipelines/image_text_to_text.py,sha256=Bfyy-UvXa2PgucQSQAOMDCzy1uoZqK_lG4RFy5lFMOs,24086 +transformers/pipelines/image_to_image.py,sha256=-4I7xiTDXcxptt8i4reI_n6rm1t-7QWwndm4MpJDD-0,5387 +transformers/pipelines/image_to_text.py,sha256=rn8nvu1PbKwzXYoA8QhPehP4kk8c5Z8urZnS0JzNTRU,10317 +transformers/pipelines/keypoint_matching.py,sha256=bjA8sqNFwR8OQX5oCYc8S5v6wWOhy9cD8u04kV8LNcg,7212 +transformers/pipelines/mask_generation.py,sha256=atgPYQq8Pzhd1BF-O7lbGHZ2X-9oAIKYmJ9XkevBd90,15513 +transformers/pipelines/object_detection.py,sha256=fLCAtvjdL_atexroUzkC9pfurffxQtblOSW5WMgkaoo,8642 +transformers/pipelines/pt_utils.py,sha256=DtNVgO1ud1n0bYMwJclMvnIJqtoNs9aedcXuCvJL_SM,12816 +transformers/pipelines/question_answering.py,sha256=iUXKuYPemRszay8ID279joBj1gi5fbsfu0t_9qh-laU,31081 +transformers/pipelines/table_question_answering.py,sha256=V6QtaXUjxtYc7KEXMba4tFMxPYqZeJOZpXlt3fS7ifE,20923 +transformers/pipelines/text2text_generation.py,sha256=S9NhbLvTm3cjVD-Ai6AOFrimeSty447OEKEcoeMqCys,18896 +transformers/pipelines/text_classification.py,sha256=LrmS2Etpkb_QCVjXpCxTYfA1Ds72uTUxSSUZ3rQ4yHs,11272 +transformers/pipelines/text_generation.py,sha256=hYSlVy2WzHHni_h0T-s-d2QM4iij_hDvY9_BKZU_7ss,27394 +transformers/pipelines/text_to_audio.py,sha256=50AlNLsRcnMcKYEAD2u9feaA7tfzaRGSuJw6dWCHFmw,11171 +transformers/pipelines/token_classification.py,sha256=ELCsAB3pnMBiu5jB-euIjaOv8LpgHFKaC2oX9a9ZDXM,30829 +transformers/pipelines/video_classification.py,sha256=lLXCowAUy7Hsy0AcyXOLJ0g_rZ5Yek1QYOa3McS0lD0,8236 +transformers/pipelines/visual_question_answering.py,sha256=v47WPs2TqnrmMuht-_48oOrLEuMoMtvmDUmmPhDoHVM,9819 +transformers/pipelines/zero_shot_audio_classification.py,sha256=4xyLE2eScVzbAWks8g2HOuXNyNMwqUSJTyANFHWYEFQ,7028 +transformers/pipelines/zero_shot_classification.py,sha256=svbtL0nOT3COZQa8DUVSW1QCK0Hx5ZkR5p91EC73rwA,12539 +transformers/pipelines/zero_shot_image_classification.py,sha256=YCTIDSWDmmCkJUj50KpnHLbMZ51cBjpgx_s47Zcnrj0,8622 +transformers/pipelines/zero_shot_object_detection.py,sha256=tJNu8fhYCsGNHdh4jiHlWOeUnhcVC8wNs5nvdB7Mp00,10740 +transformers/processing_utils.py,sha256=bCneXD_GdM8humN3o5y6-yuj5LwtEgLUuUT4z4QObzM,87156 +transformers/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +transformers/pytorch_utils.py,sha256=4XMBrwsRqomCKDII-3tK9ROFPWQ3EbGTKD0aQp1rK4Y,14852 +transformers/quantizers/__init__.py,sha256=S_xTSTbkDOvjLgR3jgR4EAkP_sc3NE8e38T-lllAaNo,800 +transformers/quantizers/__pycache__/__init__.cpython-310.pyc,, +transformers/quantizers/__pycache__/auto.cpython-310.pyc,, +transformers/quantizers/__pycache__/base.cpython-310.pyc,, +transformers/quantizers/__pycache__/quantizer_aqlm.cpython-310.pyc,, +transformers/quantizers/__pycache__/quantizer_auto_round.cpython-310.pyc,, +transformers/quantizers/__pycache__/quantizer_awq.cpython-310.pyc,, +transformers/quantizers/__pycache__/quantizer_bitnet.cpython-310.pyc,, +transformers/quantizers/__pycache__/quantizer_bnb_4bit.cpython-310.pyc,, +transformers/quantizers/__pycache__/quantizer_bnb_8bit.cpython-310.pyc,, +transformers/quantizers/__pycache__/quantizer_compressed_tensors.cpython-310.pyc,, +transformers/quantizers/__pycache__/quantizer_eetq.cpython-310.pyc,, +transformers/quantizers/__pycache__/quantizer_fbgemm_fp8.cpython-310.pyc,, +transformers/quantizers/__pycache__/quantizer_finegrained_fp8.cpython-310.pyc,, +transformers/quantizers/__pycache__/quantizer_fp_quant.cpython-310.pyc,, +transformers/quantizers/__pycache__/quantizer_gptq.cpython-310.pyc,, +transformers/quantizers/__pycache__/quantizer_higgs.cpython-310.pyc,, +transformers/quantizers/__pycache__/quantizer_hqq.cpython-310.pyc,, +transformers/quantizers/__pycache__/quantizer_mxfp4.cpython-310.pyc,, +transformers/quantizers/__pycache__/quantizer_quanto.cpython-310.pyc,, +transformers/quantizers/__pycache__/quantizer_quark.cpython-310.pyc,, +transformers/quantizers/__pycache__/quantizer_spqr.cpython-310.pyc,, +transformers/quantizers/__pycache__/quantizer_torchao.cpython-310.pyc,, +transformers/quantizers/__pycache__/quantizer_vptq.cpython-310.pyc,, +transformers/quantizers/__pycache__/quantizers_utils.cpython-310.pyc,, +transformers/quantizers/auto.py,sha256=Nr3GYO5ruu6UnJ06V-qjktNjhbAT5ccfn6BJARIuyrg,13804 +transformers/quantizers/base.py,sha256=rHK6XP8YkGSKHtBkhCVAgT5wrNu7QX4SsM2ip3ga8Rc,16334 +transformers/quantizers/quantizer_aqlm.py,sha256=t6XKZKBpYzNukrPXkU8AZtCg2j4uX4CYrCii4k2JVRI,3599 +transformers/quantizers/quantizer_auto_round.py,sha256=F2ctpnJwlUI1pnV4TGul4km2_PinHjCNIAadlZvkuLo,3068 +transformers/quantizers/quantizer_awq.py,sha256=W69vAaXoIUWWHVd_QeZ7dUKwfFa_2_ddA02-F-CBIcs,7414 +transformers/quantizers/quantizer_bitnet.py,sha256=9cQ6Nk8qXvgtgbMzmPPwpBu9MDfmqZ1xB6pnBx4aaQU,4669 +transformers/quantizers/quantizer_bnb_4bit.py,sha256=KFJNrsbGKI42jLBfTz-bHjU9g_xfqoAqT6KV2YjLkqo,16098 +transformers/quantizers/quantizer_bnb_8bit.py,sha256=94EXjl9woh8Gllw61ToS_rfHXzAiUXZIhGs0pHwq5NA,12570 +transformers/quantizers/quantizer_compressed_tensors.py,sha256=jU7HrDPFidB9E1aAvUWL_n98Woph7cBC1uit8Ka7Mt4,5082 +transformers/quantizers/quantizer_eetq.py,sha256=5HsstHPFjFosjNc4NcJuVhchka_NIfKc8M87lmM9n5E,7034 +transformers/quantizers/quantizer_fbgemm_fp8.py,sha256=qe_pYCQ5BdrOVIyc2Q2vkQb3ZHuRx4T-pkHHmZUFRqs,13607 +transformers/quantizers/quantizer_finegrained_fp8.py,sha256=WvwaXdqujw_CPRzajUBdSRhFnPBhjPu7ceUadWVV3iU,9481 +transformers/quantizers/quantizer_fp_quant.py,sha256=8Rf2LcDtumNsqNBRYH4bs_ZIqNANd4jbv9LMPBzLQ7o,7548 +transformers/quantizers/quantizer_gptq.py,sha256=81KDChWDLG-rA0V3TkpZEB1hUPVhq2asg_8XfcKoWwU,5585 +transformers/quantizers/quantizer_higgs.py,sha256=RGhg7cLlhgFmSTmPA9xsAUvSydSpX4T8oPOuq4qEzb8,8277 +transformers/quantizers/quantizer_hqq.py,sha256=fFvZIZCmycyY06PA6RpHw5EMK6ykJlYerx20MtoFxVI,11395 +transformers/quantizers/quantizer_mxfp4.py,sha256=l6Ha75phDPeNgUO4B98MEtxxEy4MAtfLowyLnfNo-oA,19225 +transformers/quantizers/quantizer_quanto.py,sha256=VKKNzoMXBACtCb4ZpjEKDX5A0_-OxjgviwrvXBU7uWE,6793 +transformers/quantizers/quantizer_quark.py,sha256=0dkQFwD8b8uS_vy8nRTaVhhVTLqG7eDWpGxLHYLJNDM,3528 +transformers/quantizers/quantizer_spqr.py,sha256=ctTswadhjIb-MHtmmhYgjx4pwFmbC59MptzXXI6___4,3212 +transformers/quantizers/quantizer_torchao.py,sha256=V1fqs9qmCwmH8pqwRtUpD9aRZfNC2wg5Q19d0Twm1qM,20572 +transformers/quantizers/quantizer_vptq.py,sha256=3jDRNytkYDJvnyq1vE656ElJpN9olkEyQB4ur0unQ-k,3722 +transformers/quantizers/quantizers_utils.py,sha256=gVf8Up7S6h8mrYHtwmcAJgBENhwQsh3x6cMmoPso6x8,878 +transformers/safetensors_conversion.py,sha256=LjnFRVfXRsOhIHdyiw6pevDJcMdsKwc3kvQ6csPs9wA,4074 +transformers/sagemaker/__init__.py,sha256=fKtKAHamz_CLL9jPGCa2E-1n8RmuS-58qGtzZuKc3qg,730 +transformers/sagemaker/__pycache__/__init__.cpython-310.pyc,, +transformers/sagemaker/__pycache__/trainer_sm.cpython-310.pyc,, +transformers/sagemaker/__pycache__/training_args_sm.cpython-310.pyc,, +transformers/sagemaker/trainer_sm.py,sha256=7GsKLtjdMfKp98OwHD7RcBsl745OOwHAaBswkfLkfsE,1044 +transformers/sagemaker/training_args_sm.py,sha256=u4ufd92WQzfhzHC7j7vgNOx3BcwNPzzFHgImeXHl48g,5410 +transformers/testing_utils.py,sha256=m0CM3WgV0A7W5GZ62lZACbiyi-4uvmjTuoj6QFtOyyc,151169 +transformers/tf_utils.py,sha256=uiS6uSPmB_ZUaxbV-vMkGy1roDTtY3ujpIgkwuskGmc,11390 +transformers/time_series_utils.py,sha256=fhc___L7NHqLzQ2lvrojW0yGkXJUTVqHGEAt5VDRqNA,7493 +transformers/tokenization_mistral_common.py,sha256=U-f69MiL63qob6z6MjGPh0TaN3J26vqioOzvZNElZYk,91444 +transformers/tokenization_utils.py,sha256=38xCQUA32GXSJWglnuwS3RDKpzdbLXoncHt6UCoI74A,47780 +transformers/tokenization_utils_base.py,sha256=otYvfl1Y-QizotCyTOYynh5SyBUILO3eKaXAB6I-foM,217915 +transformers/tokenization_utils_fast.py,sha256=VY5FTuaFDpDovF0XguNYeN_aHam_35l64RP6f_dxoPM,41383 +transformers/trainer.py,sha256=w-rI-ii9pjMP1N7hMef-fZvcD6NdnelE_OUsuXs3m6s,279527 +transformers/trainer_callback.py,sha256=YkfU5q-2K7G2RcmdaDLnajZOdSXiaCNKSsmJAot8hN8,33631 +transformers/trainer_pt_utils.py,sha256=MfApM3Cv-9DaHDOmFCdX-BpNT7v5AZrriSlYUNLC54Q,61426 +transformers/trainer_seq2seq.py,sha256=XnhGbtAwI0F4E9ynU5L80I4DP1DJeP8rOU1C6YzXE9E,18001 +transformers/trainer_utils.py,sha256=IOMtBe8i82arnOkcbb7CKQsuRvjadJ1S7uuvakNJvY4,34254 +transformers/training_args.py,sha256=RExMVhe4ngWuSjHePE9_wfYxFJapv37zV6ppvjqir_8,162917 +transformers/training_args_seq2seq.py,sha256=J9_vJQR4VxWAHWVbRmxjXHSRLd6KSe8inisIVezlbXI,3896 +transformers/training_args_tf.py,sha256=4WYwTKApwnjndGhEDL_NNOtvQ6VIa5w_ZZEBzAAN4Qg,14604 +transformers/utils/__init__.py,sha256=RueiNTpYNmGkkt_pQNEZ3gA1JnmeVoUdi-tFN6HmUmM,10400 +transformers/utils/__pycache__/__init__.cpython-310.pyc,, +transformers/utils/__pycache__/attention_visualizer.cpython-310.pyc,, +transformers/utils/__pycache__/auto_docstring.cpython-310.pyc,, +transformers/utils/__pycache__/backbone_utils.cpython-310.pyc,, +transformers/utils/__pycache__/bitsandbytes.cpython-310.pyc,, +transformers/utils/__pycache__/chat_template_utils.cpython-310.pyc,, +transformers/utils/__pycache__/constants.cpython-310.pyc,, +transformers/utils/__pycache__/deprecation.cpython-310.pyc,, +transformers/utils/__pycache__/doc.cpython-310.pyc,, +transformers/utils/__pycache__/dummy_detectron2_objects.cpython-310.pyc,, +transformers/utils/__pycache__/dummy_essentia_and_librosa_and_pretty_midi_and_scipy_and_torch_objects.cpython-310.pyc,, +transformers/utils/__pycache__/dummy_flax_objects.cpython-310.pyc,, +transformers/utils/__pycache__/dummy_mistral_common_objects.cpython-310.pyc,, +transformers/utils/__pycache__/dummy_music_objects.cpython-310.pyc,, +transformers/utils/__pycache__/dummy_pt_objects.cpython-310.pyc,, +transformers/utils/__pycache__/dummy_sentencepiece_and_tokenizers_objects.cpython-310.pyc,, +transformers/utils/__pycache__/dummy_sentencepiece_objects.cpython-310.pyc,, +transformers/utils/__pycache__/dummy_speech_objects.cpython-310.pyc,, +transformers/utils/__pycache__/dummy_tensorflow_text_objects.cpython-310.pyc,, +transformers/utils/__pycache__/dummy_tf_objects.cpython-310.pyc,, +transformers/utils/__pycache__/dummy_timm_and_torchvision_objects.cpython-310.pyc,, +transformers/utils/__pycache__/dummy_tokenizers_objects.cpython-310.pyc,, +transformers/utils/__pycache__/dummy_torchaudio_objects.cpython-310.pyc,, +transformers/utils/__pycache__/dummy_torchvision_objects.cpython-310.pyc,, +transformers/utils/__pycache__/dummy_vision_objects.cpython-310.pyc,, +transformers/utils/__pycache__/fx.cpython-310.pyc,, +transformers/utils/__pycache__/generic.cpython-310.pyc,, +transformers/utils/__pycache__/hp_naming.cpython-310.pyc,, +transformers/utils/__pycache__/hub.cpython-310.pyc,, +transformers/utils/__pycache__/import_utils.cpython-310.pyc,, +transformers/utils/__pycache__/logging.cpython-310.pyc,, +transformers/utils/__pycache__/metrics.cpython-310.pyc,, +transformers/utils/__pycache__/model_parallel_utils.cpython-310.pyc,, +transformers/utils/__pycache__/notebook.cpython-310.pyc,, +transformers/utils/__pycache__/peft_utils.cpython-310.pyc,, +transformers/utils/__pycache__/quantization_config.cpython-310.pyc,, +transformers/utils/__pycache__/sentencepiece_model_pb2.cpython-310.pyc,, +transformers/utils/__pycache__/sentencepiece_model_pb2_new.cpython-310.pyc,, +transformers/utils/__pycache__/versions.cpython-310.pyc,, +transformers/utils/attention_visualizer.py,sha256=3cFo4QHuidz5HThcqh6e-FeShTmcZizqt7F6Vj6Wxaw,10002 +transformers/utils/auto_docstring.py,sha256=Wsc50zaeZGtzgXve7L9Mifn7wDvne0s8Cx3nawQl7FE,82036 +transformers/utils/backbone_utils.py,sha256=VBTJq-x9JZBfV1ftRcUqK3PnsVjVdzJetRBwTBouggM,17722 +transformers/utils/bitsandbytes.py,sha256=LzOKwcHWAxxZZv-7Ts9Q0vlEYvHd18affVgVbiR3Tzs,1040 +transformers/utils/chat_template_utils.py,sha256=ph0p2YRJSZmg8aKAFDQi4oRpZHJ6TMZvcuEs_x2ZLuI,22775 +transformers/utils/constants.py,sha256=sZsUwOnA3CbtN1svs9YoaNLTTsAc9RVaITsgpf8K4iI,282 +transformers/utils/deprecation.py,sha256=rsbc7bbHPmvePSmkpf_nXQ7OIX6ITFSK6nJxHvu0bY4,8065 +transformers/utils/doc.py,sha256=K5MgXYi1j1Bd5OU-ho57ojgp1UftHN4Yu2mpj3x3lQA,52480 +transformers/utils/dummy_detectron2_objects.py,sha256=n7Pt_7sbVBNfohKGcOARB-ZcPcJRbjEAcoLd2vTXndU,340 +transformers/utils/dummy_essentia_and_librosa_and_pretty_midi_and_scipy_and_torch_objects.py,sha256=n6pY4s7zCII3dzo7Ejd0RviHa_pMateuDEwbbHgsTUY,902 +transformers/utils/dummy_flax_objects.py,sha256=lqW9EJzfDmsx7Uj4cm4UHUUwcYI9SFm8-biApCP40HQ,2652 +transformers/utils/dummy_mistral_common_objects.py,sha256=a43f12WAikWuVMOnFPTA1A2rvI9gi2a4POyuBLLFVEs,311 +transformers/utils/dummy_music_objects.py,sha256=1lxIebYUOdHJWMQ_T5IQgPgcO_wp_8YM_HGc3skuGVg,458 +transformers/utils/dummy_pt_objects.py,sha256=NX6GyTm_tdvcxYUpBpa7LhgMcNfRG-SuGKHkg9FE5us,14933 +transformers/utils/dummy_sentencepiece_and_tokenizers_objects.py,sha256=BgPLr8Wz8A-17K86x04N21CKXtWNQLJEWx2c4aZRqaA,286 +transformers/utils/dummy_sentencepiece_objects.py,sha256=pBykNNg9IPDeshVOeaw4sxHvgmt3by9X4rIQtz0ONYg,6455 +transformers/utils/dummy_speech_objects.py,sha256=9eFm1cjdsYOPBoAz9JTgP35Bg8WF2C9AZ_y1hFpKZdQ,465 +transformers/utils/dummy_tensorflow_text_objects.py,sha256=43V0IA2kb9gtuL0S1OL1eRFFxzQwKg4pPjMVuXUB5qg,306 +transformers/utils/dummy_tf_objects.py,sha256=8ZPa6w8h-VzRDzwOO9xK26u9evz3T8bkxSLhgxI-lKU,4139 +transformers/utils/dummy_timm_and_torchvision_objects.py,sha256=EFuC5z6IsKOqqowoUGviJ3KgTjzvdTTN7gGQ3it-4t0,324 +transformers/utils/dummy_tokenizers_objects.py,sha256=PFIh5nBDmhWG2XDGuwIyBGldm6b_jdZdL3E8t5A8FsY,304 +transformers/utils/dummy_torchaudio_objects.py,sha256=EG0q0JkedoNb_4ntsf6EyTOE6Nr1whvHOzHPKy1t7x0,847 +transformers/utils/dummy_torchvision_objects.py,sha256=BaUQGsNL0Xfj-HP-pOVXSKYw5UFaNlWD_Iso9D8muGw,479 +transformers/utils/dummy_vision_objects.py,sha256=GDbX7-GrqykExLY91SMhSf508DinS5NSFfavbeDsCMU,630 +transformers/utils/fx.py,sha256=zCoZAdT1XNnypOj2fCQMX-ADlBYQlmJKrkJvesarxME,56930 +transformers/utils/generic.py,sha256=lHKIJRkN_0kfLguTvrWcgkatsLYEnjIDxRFAX0O7fjA,41945 +transformers/utils/hp_naming.py,sha256=vqcOXcDOyqbISWo8-ClUJUOBVbZM1h08EcymTwcRthc,4979 +transformers/utils/hub.py,sha256=vI9J6TYLkExDgsgwtYtbcNffXtZv2Qspi_sO3CPi6EY,50071 +transformers/utils/import_utils.py,sha256=ZrKsQL4sU429lAk3DB9r92mTS4sjLtrDZeFimcXsEQg,108811 +transformers/utils/logging.py,sha256=izaHM1YuNFG1dsZZ8rbbRfBB897o2BgNFscrMlOVAII,12219 +transformers/utils/metrics.py,sha256=bL6xW97M-trUf0uSSZnYnZ-1_u_RxRiIg5BJY0bnh30,15402 +transformers/utils/model_parallel_utils.py,sha256=dmPsjrVGLxwYHsGXyvFQrcl-aZRQA5hydi4I7_sBAoo,2257 +transformers/utils/notebook.py,sha256=Gkg0GxMhbrTk21Fp6aXVeTuVk49yPDWuGbLc4OCHrPo,15796 +transformers/utils/peft_utils.py,sha256=7XZBVmD_gcZl2hjwTRYztGs-WEHfRc53rqNuUdAlzl0,5193 +transformers/utils/quantization_config.py,sha256=MK8CU9pBIqA8TXWMraDfrM3YndtyW39pj0W-E13bU1g,95861 +transformers/utils/sentencepiece_model_pb2.py,sha256=WcMZRm2-571XwxSfo-6FZih9fDy_Zl5mMwqrDrC1Dlg,50663 +transformers/utils/sentencepiece_model_pb2_new.py,sha256=ahaV--amhGIL3nXFCTHqezqxuGXm8SHr_C3Zvj7KbAY,6598 +transformers/utils/versions.py,sha256=C-Tqr4qGSHH64ygIBCSo8gA6azz7Dbzh8zdc_yjMkX8,4337 +transformers/video_processing_utils.py,sha256=Bn3JWf6ADVpaWrOcVLU4F6S1lCTzFDZ2fXNhwgs7pAk,41231 +transformers/video_utils.py,sha256=O8F09M9oEV6tOZtJUh38aZsb9gVeWv6aQ3L9mO2Bnb4,33856 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers-4.57.6.dist-info/WHEEL b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers-4.57.6.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..e7fa31b6f3f78deb1022c1f7927f07d4d16da822 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers-4.57.6.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers-4.57.6.dist-info/entry_points.txt b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers-4.57.6.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..47f047547c476346d81519e9d380af1a6be26155 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers-4.57.6.dist-info/entry_points.txt @@ -0,0 +1,3 @@ +[console_scripts] +transformers = transformers.commands.transformers_cli:main +transformers-cli = transformers.commands.transformers_cli:main_cli diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers-4.57.6.dist-info/top_level.txt b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers-4.57.6.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..976a2b1f3998279c10c413279a095be86bf69167 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers-4.57.6.dist-info/top_level.txt @@ -0,0 +1 @@ +transformers diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tree_sitter/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tree_sitter/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a3fbe84727c8c6a6946b73bd2b4cb2f4130e55de --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tree_sitter/__init__.py @@ -0,0 +1,71 @@ +"""Python bindings to the Tree-sitter parsing library.""" + +from typing import Protocol as _Protocol + +from ._binding import ( + Language, + LogType, + LookaheadIterator, + Node, + Parser, + Point, + Query, + QueryCursor, + QueryError, + Range, + Tree, + TreeCursor, + LANGUAGE_VERSION, + MIN_COMPATIBLE_LANGUAGE_VERSION, +) + +LogType.__doc__ = "The type of a log message." + +Point.__doc__ = "A position in a multi-line text document, in terms of rows and columns." +Point.row.__doc__ = "The zero-based row of the document." +Point.column.__doc__ = "The zero-based column of the document." + + +class QueryPredicate(_Protocol): + """A custom query predicate that runs on a pattern.""" + def __call__(self, predicate, args, pattern_index, captures): + """ + Parameters + ---------- + + predicate : str + The name of the predicate. + args : list[tuple[str, typing.Literal['capture', 'string']]] + The arguments to the predicate. + pattern_index : int + The index of the pattern within the query. + captures : dict[str, list[Node]] + The captures contained in the pattern. + + Returns + ------- + ``True`` if the predicate matches, ``False`` otherwise. + + Tip + --- + You don't need to create an actual class, just a function with this signature. + """ + + +__all__ = [ + "Language", + "LogType", + "LookaheadIterator", + "Node", + "Parser", + "Point", + "Query", + "QueryCursor", + "QueryError", + "QueryPredicate", + "Range", + "Tree", + "TreeCursor", + "LANGUAGE_VERSION", + "MIN_COMPATIBLE_LANGUAGE_VERSION", +] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tree_sitter/__init__.pyi b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tree_sitter/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..f68eac62c77c2c1708e2922487124c8117a2f2cd --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tree_sitter/__init__.pyi @@ -0,0 +1,416 @@ +from enum import IntEnum +from collections.abc import ByteString, Callable, Iterator, Sequence +from typing import Annotated, Any, Final, Literal, NamedTuple, Protocol, Self, final, overload +from typing_extensions import deprecated + +class _SupportsFileno(Protocol): + def fileno(self) -> int: ... + +class Point(NamedTuple): + row: int + column: int + +class LogType(IntEnum): + PARSE: int + LEX: int + +@final +class Language: + @overload + @deprecated("int argument support is deprecated") + def __init__(self, ptr: Annotated[int, "TSLanguage *"], /) -> None: ... + @overload + def __init__(self, ptr: Annotated[object, "TSLanguage *"], /) -> None: ... + @property + def name(self) -> str | None: ... + @property + def abi_version(self) -> int: ... + @property + def semantic_version(self) -> tuple[int, int, int] | None: ... + @deprecated("Use abi_version instead") + @property + def version(self) -> int: ... + @property + def node_kind_count(self) -> int: ... + @property + def parse_state_count(self) -> int: ... + @property + def field_count(self) -> int: ... + @property + def supertypes(self) -> tuple[int, ...]: ... + def subtypes(self, supertype: int, /) -> tuple[int, ...]: ... + def node_kind_for_id(self, id: int, /) -> str | None: ... + def id_for_node_kind(self, kind: str, named: bool, /) -> int | None: ... + def node_kind_is_named(self, id: int, /) -> bool: ... + def node_kind_is_visible(self, id: int, /) -> bool: ... + def node_kind_is_supertype(self, id: int, /) -> bool: ... + def field_name_for_id(self, field_id: int, /) -> str | None: ... + def field_id_for_name(self, name: str, /) -> int | None: ... + def next_state(self, state: int, id: int, /) -> int: ... + def lookahead_iterator(self, state: int, /) -> LookaheadIterator | None: ... + @deprecated("Use the Query() constructor instead") + def query(self, source: str, /) -> Query: ... + def copy(self) -> Language: ... + def __repr__(self) -> str: ... + def __eq__(self, other: Any, /) -> bool: ... + def __ne__(self, other: Any, /) -> bool: ... + def __hash__(self) -> int: ... + def __copy__(self) -> Language: ... + +@final +class Node: + @property + def id(self) -> int: ... + @property + def kind_id(self) -> int: ... + @property + def grammar_id(self) -> int: ... + @property + def grammar_name(self) -> str: ... + @property + def type(self) -> str: ... + @property + def is_named(self) -> bool: ... + @property + def is_extra(self) -> bool: ... + @property + def has_changes(self) -> bool: ... + @property + def has_error(self) -> bool: ... + @property + def is_error(self) -> bool: ... + @property + def parse_state(self) -> int: ... + @property + def next_parse_state(self) -> int: ... + @property + def is_missing(self) -> bool: ... + @property + def start_byte(self) -> int: ... + @property + def end_byte(self) -> int: ... + @property + def byte_range(self) -> tuple[int, int]: ... + @property + def range(self) -> Range: ... + @property + def start_point(self) -> Point: ... + @property + def end_point(self) -> Point: ... + @property + def children(self) -> list[Node]: ... + @property + def child_count(self) -> int: ... + @property + def named_children(self) -> list[Node]: ... + @property + def named_child_count(self) -> int: ... + @property + def parent(self) -> Node | None: ... + @property + def next_sibling(self) -> Node | None: ... + @property + def prev_sibling(self) -> Node | None: ... + @property + def next_named_sibling(self) -> Node | None: ... + @property + def prev_named_sibling(self) -> Node | None: ... + @property + def descendant_count(self) -> int: ... + @property + def text(self) -> bytes | None: ... + def walk(self) -> TreeCursor: ... + def edit( + self, + start_byte: int, + old_end_byte: int, + new_end_byte: int, + start_point: Point | tuple[int, int], + old_end_point: Point | tuple[int, int], + new_end_point: Point | tuple[int, int], + ) -> None: ... + def child(self, index: int, /) -> Node | None: ... + def named_child(self, index: int, /) -> Node | None: ... + def first_child_for_byte(self, byte: int, /) -> Node | None: ... + def first_named_child_for_byte(self, byte: int, /) -> Node | None: ... + def child_by_field_id(self, id: int, /) -> Node | None: ... + def child_by_field_name(self, name: str, /) -> Node | None: ... + def child_with_descendant(self, descendant: Node, /) -> Node | None: ... + def children_by_field_id(self, id: int, /) -> list[Node]: ... + def children_by_field_name(self, name: str, /) -> list[Node]: ... + def field_name_for_child(self, child_index: int, /) -> str | None: ... + def field_name_for_named_child(self, child_index: int, /) -> str | None: ... + def descendant_for_byte_range( + self, + start_byte: int, + end_byte: int, + /, + ) -> Node | None: ... + def named_descendant_for_byte_range( + self, + start_byte: int, + end_byte: int, + /, + ) -> Node | None: ... + def descendant_for_point_range( + self, + start_point: Point | tuple[int, int], + end_point: Point | tuple[int, int], + /, + ) -> Node | None: ... + def named_descendant_for_point_range( + self, + start_point: Point | tuple[int, int], + end_point: Point | tuple[int, int], + /, + ) -> Node | None: ... + def __repr__(self) -> str: ... + def __str__(self) -> str: ... + def __eq__(self, other: Any, /) -> bool: ... + def __ne__(self, other: Any, /) -> bool: ... + def __hash__(self) -> int: ... + +@final +class Tree: + @property + def root_node(self) -> Node: ... + @property + def included_ranges(self) -> list[Range]: ... + @property + def language(self) -> Language: ... + def root_node_with_offset( + self, + offset_bytes: int, + offset_extent: Point | tuple[int, int], + /, + ) -> Node | None: ... + def copy(self) -> Tree: ... + def edit( + self, + start_byte: int, + old_end_byte: int, + new_end_byte: int, + start_point: Point | tuple[int, int], + old_end_point: Point | tuple[int, int], + new_end_point: Point | tuple[int, int], + ) -> None: ... + def walk(self) -> TreeCursor: ... + def changed_ranges(self, new_tree: Tree, /) -> list[Range]: ... + def print_dot_graph(self, file: _SupportsFileno, /) -> None: ... + def __copy__(self) -> Tree: ... + +@final +class TreeCursor: + @property + def node(self) -> Node | None: ... + @property + def field_id(self) -> int | None: ... + @property + def field_name(self) -> str | None: ... + @property + def depth(self) -> int: ... + @property + def descendant_index(self) -> int: ... + def copy(self) -> TreeCursor: ... + def reset(self, node: Node, /) -> None: ... + def reset_to(self, cursor: TreeCursor, /) -> None: ... + def goto_first_child(self) -> bool: ... + def goto_last_child(self) -> bool: ... + def goto_parent(self) -> bool: ... + def goto_next_sibling(self) -> bool: ... + def goto_previous_sibling(self) -> bool: ... + def goto_descendant(self, index: int, /) -> None: ... + def goto_first_child_for_byte(self, byte: int, /) -> int | None: ... + def goto_first_child_for_point(self, point: Point | tuple[int, int], /) -> int | None: ... + def __copy__(self) -> TreeCursor: ... + +@final +class Parser: + @overload + def __init__( + self, + language: Language | None = None, + *, + included_ranges: Sequence[Range] | None = None, + logger: Callable[[LogType, str], None] | None = None, + ) -> None: ... + @deprecated("timeout_micros is deprecated") + @overload + def __init__( + self, + language: Language | None = None, + *, + included_ranges: Sequence[Range] | None = None, + timeout_micros: int | None = None, + logger: Callable[[LogType, str], None] | None = None, + ) -> None: ... + @property + def language(self) -> Language | None: ... + @language.setter + def language(self, language: Language) -> None: ... + @language.deleter + def language(self) -> None: ... + @property + def included_ranges(self) -> list[Range]: ... + @included_ranges.setter + def included_ranges(self, ranges: Sequence[Range]) -> None: ... + @included_ranges.deleter + def included_ranges(self) -> None: ... + @deprecated("Use the progress_callback in parse()") + @property + def timeout_micros(self) -> int: ... + @deprecated("Use the progress_callback in parse()") + @timeout_micros.setter + def timeout_micros(self, timeout: int) -> None: ... + @deprecated("Use the progress_callback in parse()") + @timeout_micros.deleter + def timeout_micros(self) -> None: ... + @property + def logger(self) -> Callable[[LogType, str], None] | None: ... + @logger.setter + def logger(self, logger: Callable[[LogType, str], None]) -> None: ... + @logger.deleter + def logger(self) -> None: ... + @overload + def parse( + self, + source: ByteString, + /, + old_tree: Tree | None = None, + encoding: Literal["utf8", "utf16", "utf16le", "utf16be"] = "utf8", + ) -> Tree: ... + @overload + def parse( + self, + read_callback: Callable[[int, Point], ByteString | None], + /, + old_tree: Tree | None = None, + encoding: Literal["utf8", "utf16", "utf16le", "utf16be"] = "utf8", + progress_callback: Callable[[int, bool], bool] | None = None, + ) -> Tree: ... + def reset(self) -> None: ... + def print_dot_graphs(self, file: _SupportsFileno | None, /) -> None: ... + +class QueryError(ValueError): ... + +class QueryPredicate(Protocol): + def __call__( + self, + predicate: str, + args: list[tuple[str, Literal["capture", "string"]]], + pattern_index: int, + captures: dict[str, list[Node]], + ) -> bool: ... + +@final +class Query: + def __new__(cls, language: Language, source: str, /) -> Self: ... + def pattern_count(self) -> int: ... + def capture_count(self) -> int: ... + def string_count(self) -> int: ... + def start_byte_for_pattern(self, index: int, /) -> int: ... + def end_byte_for_pattern(self, index: int, /) -> int: ... + def is_pattern_rooted(self, index: int, /) -> bool: ... + def is_pattern_non_local(self, index: int, /) -> bool: ... + def is_pattern_guaranteed_at_step(self, index: int, /) -> bool: ... + def capture_name(self, index: int, /) -> str: ... + def capture_quantifier( + self, + pattern_index: int, + capture_index: int, + / + ) -> Literal["", "?", "*", "+"]: ... + def string_value(self, index: int, /) -> str: ... + def disable_capture(self, name: str, /) -> None: ... + def disable_pattern(self, index: int, /) -> None: ... + def pattern_settings(self, index: int, /) -> dict[str, str | None]: ... + def pattern_assertions(self, index: int, /) -> dict[str, tuple[str | None, bool]]: ... + +@final +class QueryCursor: + @overload + def __init__(self, query: Query, *, match_limit: int = 0xFFFFFFFF) -> None: ... + @deprecated("timeout_micros is deprecated") + @overload + def __init__( + self, + query: Query, + *, + match_limit: int = 0xFFFFFFFF, + timeout_micros: int = 0 + ) -> None: ... + @property + def match_limit(self) -> int: ... + @match_limit.setter + def match_limit(self, limit: int) -> None: ... + @match_limit.deleter + def match_limit(self) -> None: ... + @deprecated("Use the progress_callback in matches() or captures()") + @property + def timeout_micros(self) -> int: ... + @deprecated("Use the progress_callback in matches() or captures()") + @timeout_micros.setter + def timeout_micros(self, timeout: int) -> None: ... + @property + def did_exceed_match_limit(self) -> bool: ... + def set_max_start_depth(self, depth: int, /) -> None: ... + def set_byte_range(self, start: int, end: int, /) -> None: ... + def set_point_range( + self, + start: Point | tuple[int, int], + end: Point | tuple[int, int], + /, + ) -> None: ... + def captures( + self, + node: Node, + predicate: QueryPredicate | None = None, + progress_callback: Callable[[int], bool] | None = None, + /, + ) -> dict[str, list[Node]]: ... + def matches( + self, + node: Node, + predicate: QueryPredicate | None = None, + progress_callback: Callable[[int], bool] | None = None, + /, + ) -> list[tuple[int, dict[str, list[Node]]]]: ... + +@final +class LookaheadIterator(Iterator[tuple[int, str]]): + @property + def language(self) -> Language: ... + @property + def current_symbol(self) -> int: ... + @property + def current_symbol_name(self) -> str: ... + def reset(self, state: int, /, language: Language | None = None) -> bool: ... + def names(self) -> list[str]: ... + def symbols(self) -> list[int]: ... + def __next__(self) -> tuple[int, str]: ... + +@final +class Range: + def __init__( + self, + start_point: Point | tuple[int, int], + end_point: Point | tuple[int, int], + start_byte: int, + end_byte: int, + ) -> None: ... + @property + def start_point(self) -> Point: ... + @property + def end_point(self) -> Point: ... + @property + def start_byte(self) -> int: ... + @property + def end_byte(self) -> int: ... + def __eq__(self, other: Any, /) -> bool: ... + def __ne__(self, other: Any, /) -> bool: ... + def __repr__(self) -> str: ... + def __hash__(self) -> int: ... + +LANGUAGE_VERSION: Final[int] + +MIN_COMPATIBLE_LANGUAGE_VERSION: Final[int] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tree_sitter/py.typed b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/tree_sitter/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/typing_inspection-0.4.2.dist-info/INSTALLER b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/typing_inspection-0.4.2.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/typing_inspection-0.4.2.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/typing_inspection-0.4.2.dist-info/METADATA b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/typing_inspection-0.4.2.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..b0eba85d3eecdda5430e23dfaa6c198ec9851141 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/typing_inspection-0.4.2.dist-info/METADATA @@ -0,0 +1,49 @@ +Metadata-Version: 2.4 +Name: typing-inspection +Version: 0.4.2 +Summary: Runtime typing introspection tools +Project-URL: Homepage, https://github.com/pydantic/typing-inspection +Project-URL: Documentation, https://pydantic.github.io/typing-inspection/dev/ +Project-URL: Source, https://github.com/pydantic/typing-inspection +Project-URL: Changelog, https://github.com/pydantic/typing-inspection/blob/main/HISTORY.md +Author-email: Victorien Plot +License-Expression: MIT +License-File: LICENSE +Classifier: Development Status :: 3 - Alpha +Classifier: Intended Audience :: Developers +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +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.14 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Typing :: Typed +Requires-Python: >=3.9 +Requires-Dist: typing-extensions>=4.12.0 +Description-Content-Type: text/markdown + +# typing-inspection + +[![CI](https://img.shields.io/github/actions/workflow/status/pydantic/typing-inspection/ci.yml?branch=main&logo=github&label=CI)](https://github.com/pydantic/typing-inspection/actions?query=event%3Apush+branch%3Amain+workflow%3ACI) +[![Coverage](https://coverage-badge.samuelcolvin.workers.dev/pydantic/typing-inspection.svg)](https://coverage-badge.samuelcolvin.workers.dev/redirect/pydantic/typing-inspection) +[![PyPI](https://img.shields.io/pypi/v/typing-inspection.svg)](https://pypi.org/project/typing-inspection/) +[![Versions](https://img.shields.io/pypi/pyversions/typing-inspection.svg)](https://github.com/pydantic/typing-inspection) +[![License](https://img.shields.io/github/license/pydantic/typing-inspection.svg)](https://github.com/pydantic/typing-inspection/blob/main/LICENSE) +[![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff) + +`typing-inspection` provides tools to inspect type annotations at runtime. + +## Installation + +From [PyPI](https://pypi.org/project/typing-inspection/): + +```bash +pip install typing-inspection +``` + +The library can be imported from the `typing_inspection` module. diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/typing_inspection-0.4.2.dist-info/RECORD b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/typing_inspection-0.4.2.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..61703859990f4d5b5d27999985829ad1ac6b3a98 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/typing_inspection-0.4.2.dist-info/RECORD @@ -0,0 +1,13 @@ +typing_inspection-0.4.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +typing_inspection-0.4.2.dist-info/METADATA,sha256=YQls0L_jxwQLb5jCKwLRkP4Bk20P92FsUTT-0CiRlTo,2552 +typing_inspection-0.4.2.dist-info/RECORD,, +typing_inspection-0.4.2.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87 +typing_inspection-0.4.2.dist-info/licenses/LICENSE,sha256=gEtZsl8sMb0nj5ICoZrkmjlFqiZkOH4tChKMfKzGHsM,1090 +typing_inspection/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +typing_inspection/__pycache__/__init__.cpython-310.pyc,, +typing_inspection/__pycache__/introspection.cpython-310.pyc,, +typing_inspection/__pycache__/typing_objects.cpython-310.pyc,, +typing_inspection/introspection.py,sha256=dD5Ad4J6hAfF6UBzBO4sqSs1h2ybQVThkQofLWWVBP0,22534 +typing_inspection/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +typing_inspection/typing_objects.py,sha256=kajVgh8J7UZ7wTidVxzFMpjwSnFGBoDoTqfVAAvOHZ8,17166 +typing_inspection/typing_objects.pyi,sha256=u1NDpl_RJFnAUMAMx-WBd0SBKwVG7luLEc8ukSvRnZs,9401 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/typing_inspection-0.4.2.dist-info/WHEEL b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/typing_inspection-0.4.2.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..12228d414b6cfed7c39d3781c85c63256a1d7fb5 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/typing_inspection-0.4.2.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.27.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/uritemplate-4.2.0.dist-info/INSTALLER b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/uritemplate-4.2.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/uritemplate-4.2.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/uritemplate-4.2.0.dist-info/METADATA b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/uritemplate-4.2.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..2229593fd667c42b6a3475ce061da0397f96fc61 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/uritemplate-4.2.0.dist-info/METADATA @@ -0,0 +1,84 @@ +Metadata-Version: 2.4 +Name: uritemplate +Version: 4.2.0 +Summary: Implementation of RFC 6570 URI Templates +Home-page: https://uritemplate.readthedocs.org +Author: Ian Stapleton Cordasco +Author-email: graffatcolmingov@gmail.com +License: BSD 3-Clause OR Apache-2.0 +Project-URL: Source, https://github.com/python-hyper/uritemplate +Keywords: rfc 6570 uri template +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: Implementation :: CPython +Requires-Python: >=3.9 +Description-Content-Type: text/x-rst +License-File: LICENSE +Dynamic: license-file + +uritemplate +=========== + +Documentation_ -- GitHub_ -- Travis-CI_ + +Simple python library to deal with `URI Templates`_. The API looks like + +.. code-block:: python + + from uritemplate import URITemplate, expand + + # NOTE: URI params must be strings not integers + + gist_uri = 'https://api.github.com/users/sigmavirus24/gists{/gist_id}' + t = URITemplate(gist_uri) + print(t.expand(gist_id='123456')) + # => https://api.github.com/users/sigmavirus24/gists/123456 + + # or + print(expand(gist_uri, gist_id='123456')) + + # also + t.expand({'gist_id': '123456'}) + print(expand(gist_uri, {'gist_id': '123456'})) + +Where it might be useful to have a class + +.. code-block:: python + + import requests + + class GitHubUser(object): + url = URITemplate('https://api.github.com/user{/login}') + def __init__(self, name): + self.api_url = url.expand(login=name) + response = requests.get(self.api_url) + if response.status_code == 200: + self.__dict__.update(response.json()) + +When the module containing this class is loaded, ``GitHubUser.url`` is +evaluated and so the template is created once. It's often hard to notice in +Python, but object creation can consume a great deal of time and so can the +``re`` module which uritemplate relies on. Constructing the object once should +reduce the amount of time your code takes to run. + +Installing +---------- + +:: + + pip install uritemplate + +License +------- + +Modified BSD license_ + + +.. _Documentation: https://uritemplate.readthedocs.io/ +.. _GitHub: https://github.com/python-hyper/uritemplate +.. _Travis-CI: https://travis-ci.org/python-hyper/uritemplate +.. _URI Templates: https://tools.ietf.org/html/rfc6570 +.. _license: https://github.com/python-hyper/uritemplate/blob/master/LICENSE diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/uritemplate-4.2.0.dist-info/RECORD b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/uritemplate-4.2.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..1ff5d9dbf9e7c269306647c170642f1fe0e4a7cf --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/uritemplate-4.2.0.dist-info/RECORD @@ -0,0 +1,17 @@ +uritemplate-4.2.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +uritemplate-4.2.0.dist-info/METADATA,sha256=NSr9Q7bxq4-UyjGvKhrU8NGpTb1xLBttnkTjXUuzqWI,2579 +uritemplate-4.2.0.dist-info/RECORD,, +uritemplate-4.2.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91 +uritemplate-4.2.0.dist-info/licenses/LICENSE,sha256=PPyfAc3uySkA8ijPVnf_pX5-0wTEJjUyvK2cvZlp5Gw,196 +uritemplate-4.2.0.dist-info/top_level.txt,sha256=WJzkFEINWbgwuzuUEP8kD8Sk2fFHYQzBgrjO3viyubE,12 +uritemplate/__init__.py,sha256=4VPKNovvYqtf2-NWMfoW_L5LdkgZph0FAJdJXLktv5U,876 +uritemplate/__pycache__/__init__.cpython-310.pyc,, +uritemplate/__pycache__/api.cpython-310.pyc,, +uritemplate/__pycache__/orderedset.cpython-310.pyc,, +uritemplate/__pycache__/template.cpython-310.pyc,, +uritemplate/__pycache__/variable.cpython-310.pyc,, +uritemplate/api.py,sha256=I_tFOvrvUPfmLGfvb4CDyeZb2DhqGQ8oEeTAT-jEO5s,2306 +uritemplate/orderedset.py,sha256=4Z8u8uw339D_RWvbUslv5d6EnA2wxQC66317oTLzp0o,3367 +uritemplate/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +uritemplate/template.py,sha256=7upfALQ2yBXxE8ipKqx3g0P7TgMRQRItXRoaG5doLnk,4774 +uritemplate/variable.py,sha256=ZwmTFlqQRvp9Td9FSbP4Co9n1lUefZY17_K_jv1lTBY,18291 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/uritemplate-4.2.0.dist-info/WHEEL b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/uritemplate-4.2.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..e7fa31b6f3f78deb1022c1f7927f07d4d16da822 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/uritemplate-4.2.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/uritemplate-4.2.0.dist-info/top_level.txt b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/uritemplate-4.2.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..2d76f010c2c1a70f504859f8ddd0ac637a8622d8 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/uritemplate-4.2.0.dist-info/top_level.txt @@ -0,0 +1 @@ +uritemplate diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/uritemplate/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/uritemplate/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b22774767876685b6efc2e478c57bde886530ef5 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/uritemplate/__init__.py @@ -0,0 +1,33 @@ +""" + +uritemplate +=========== + +URI templates implemented as close to :rfc:`6570` as possible + +See http://uritemplate.rtfd.org/ for documentation + +:copyright: + (c) 2013 Ian Stapleton Cordasco +:license: + Modified BSD Apache License (Version 2.0), see LICENSE for more details + and either LICENSE.BSD or LICENSE.APACHE for the details of those specific + licenses + +""" + +__title__ = "uritemplate" +__author__ = "Ian Stapleton Cordasco" +__license__ = "Modified BSD or Apache License, Version 2.0" +__copyright__ = "Copyright 2013 Ian Stapleton Cordasco" +__version__ = "4.2.0" +__version_info__ = tuple( + int(i) for i in __version__.split(".") if i.isdigit() +) + +from uritemplate.api import URITemplate +from uritemplate.api import expand +from uritemplate.api import partial +from uritemplate.api import variables + +__all__ = ("URITemplate", "expand", "partial", "variables") diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/uritemplate/api.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/uritemplate/api.py new file mode 100644 index 0000000000000000000000000000000000000000..8da3914e759431b907396dd4832a89ba01ac3cf3 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/uritemplate/api.py @@ -0,0 +1,86 @@ +""" + +uritemplate.api +=============== + +This module contains the very simple API provided by uritemplate. + +""" + +import typing as t + +from uritemplate import variable +from uritemplate.orderedset import OrderedSet +from uritemplate.template import URITemplate + +__all__ = ("OrderedSet", "URITemplate", "expand", "partial", "variables") + + +def expand( + uri: str, + var_dict: t.Optional[variable.VariableValueDict] = None, + **kwargs: variable.VariableValue, +) -> str: + """Expand the template with the given parameters. + + :param str uri: The templated URI to expand + :param dict var_dict: Optional dictionary with variables and values + :param kwargs: Alternative way to pass arguments + :returns: str + + Example:: + + expand('https://api.github.com{/end}', {'end': 'users'}) + expand('https://api.github.com{/end}', end='gists') + + .. note:: Passing values by both parts, may override values in + ``var_dict``. For example:: + + expand('https://{var}', {'var': 'val1'}, var='val2') + + ``val2`` will be used instead of ``val1``. + + """ + return URITemplate(uri).expand(var_dict, **kwargs) + + +def partial( + uri: str, + var_dict: t.Optional[variable.VariableValueDict] = None, + **kwargs: variable.VariableValue, +) -> URITemplate: + """Partially expand the template with the given parameters. + + If all of the parameters for the template are not given, return a + partially expanded template. + + :param dict var_dict: Optional dictionary with variables and values + :param kwargs: Alternative way to pass arguments + :returns: :class:`URITemplate` + + Example:: + + t = URITemplate('https://api.github.com{/end}') + t.partial() # => URITemplate('https://api.github.com{/end}') + + """ + return URITemplate(uri).partial(var_dict, **kwargs) + + +def variables(uri: str) -> OrderedSet: + """Parse the variables of the template. + + This returns all of the variable names in the URI Template. + + :returns: Set of variable names + :rtype: set + + Example:: + + variables('https://api.github.com{/end}) + # => {'end'} + variables('https://api.github.com/repos{/username}{/repository}') + # => {'username', 'repository'} + + """ + return OrderedSet(URITemplate(uri).variable_names) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/uritemplate/orderedset.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/uritemplate/orderedset.py new file mode 100644 index 0000000000000000000000000000000000000000..dd7cd1a5867d472fdae1cd065b7586c2f17a22c2 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/uritemplate/orderedset.py @@ -0,0 +1,92 @@ +# From: https://github.com/ActiveState/code/blob/master/recipes/Python/576696_OrderedSet_with_Weakrefs/ # noqa +import typing as t +import weakref + + +class Link: + """Representation of one item in a doubly-linked list.""" + + __slots__ = ("prev", "next", "key", "__weakref__") + prev: "Link" + next: "Link" + key: str + + +class OrderedSet(t.MutableSet[str]): + """A set that remembers the order in which items were added.""" + + # Big-O running times for all methods are the same as for regular sets. + # The internal self.__map dictionary maps keys to links in a doubly linked + # list. The circular doubly linked list starts and ends with a sentinel + # element. The sentinel element never gets deleted (this simplifies the + # algorithm). The prev/next links are weakref proxies (to prevent circular + # references). Individual links are kept alive by the hard reference in + # self.__map. Those hard references disappear when a key is deleted from + # an OrderedSet. + + def __init__(self, iterable: t.Optional[t.Iterable[str]] = None): + self.__root = root = Link() # sentinel node for doubly linked list + root.prev = root.next = root + self.__map: t.MutableMapping[str, Link] = {} # key --> link + if iterable is not None: + self |= iterable # type: ignore + + def __len__(self) -> int: + return len(self.__map) + + def __contains__(self, key: object) -> bool: + return key in self.__map + + def add(self, key: str) -> None: + # Store new key in a new link at the end of the linked list + if key not in self.__map: + self.__map[key] = link = Link() + root = self.__root + last = root.prev + link.prev, link.next, link.key = last, root, key + last.next = root.prev = weakref.proxy(link) + + def discard(self, key: str) -> None: + # Remove an existing item using self.__map to find the link which is + # then removed by updating the links in the predecessor and successors. + if key in self.__map: + link = self.__map.pop(key) + link.prev.next = link.next + link.next.prev = link.prev + + def __iter__(self) -> t.Generator[str, None, None]: + # Traverse the linked list in order. + root = self.__root + curr = root.next + while curr is not root: + yield curr.key + curr = curr.next + + def __reversed__(self) -> t.Generator[str, None, None]: + # Traverse the linked list in reverse order. + root = self.__root + curr = root.prev + while curr is not root: + yield curr.key + curr = curr.prev + + def pop(self, last: bool = True) -> str: + if not self: + raise KeyError("set is empty") + key = next(reversed(self)) if last else next(iter(self)) + self.discard(key) + return key + + def __repr__(self) -> str: + if not self: + return f"{self.__class__.__name__}()" + return f"{self.__class__.__name__}({list(self)!r})" + + def __str__(self) -> str: + return self.__repr__() + + def __eq__(self, other: object) -> bool: + if isinstance(other, OrderedSet): + return len(self) == len(other) and list(self) == list(other) + other = t.cast(t.Iterable[str], other) + return not self.isdisjoint(other) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/uritemplate/py.typed b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/uritemplate/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/uritemplate/template.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/uritemplate/template.py new file mode 100644 index 0000000000000000000000000000000000000000..3205380bd049926fbdb434d2ce0012fe95c4a095 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/uritemplate/template.py @@ -0,0 +1,169 @@ +""" + +uritemplate.template +==================== + +This module contains the essential inner workings of uritemplate. + +What treasures await you: + +- URITemplate class + +You see a treasure chest of knowledge in front of you. +What do you do? +> + +""" + +import re +import typing as t + +from uritemplate import orderedset +from uritemplate import variable + +template_re = re.compile("{([^}]+)}") + + +def _merge( + var_dict: t.Optional[variable.VariableValueDict], + overrides: variable.VariableValueDict, +) -> variable.VariableValueDict: + if var_dict: + opts = var_dict.copy() + opts.update(overrides) + return opts + return overrides + + +class URITemplate: + """This parses the template and will be used to expand it. + + This is the most important object as the center of the API. + + Example:: + + from uritemplate import URITemplate + import requests + + + t = URITemplate( + 'https://api.github.com/users/sigmavirus24/gists{/gist_id}' + ) + uri = t.expand(gist_id=123456) + resp = requests.get(uri) + for gist in resp.json(): + print(gist['html_url']) + + Please note:: + + str(t) + # 'https://api.github.com/users/sigmavirus24/gists{/gistid}' + repr(t) # is equivalent to + # URITemplate(str(t)) + # Where str(t) is interpreted as the URI string. + + Also, ``URITemplates`` are hashable so they can be used as keys in + dictionaries. + + """ + + def __init__(self, uri: str): + #: The original URI to be parsed. + self.uri: str = uri + #: A list of the variables in the URI. They are stored as + #: :class:`~uritemplate.variable.URIVariable`\ s + self.variables: t.List[variable.URIVariable] = [ + variable.URIVariable(m.groups()[0]) + for m in template_re.finditer(self.uri) + ] + #: A set of variable names in the URI. + self.variable_names = orderedset.OrderedSet() + for var in self.variables: + for name in var.variable_names: + self.variable_names.add(name) + + def __repr__(self) -> str: + return 'URITemplate("%s")' % self + + def __str__(self) -> str: + return self.uri + + def __eq__(self, other: object) -> bool: + if not isinstance(other, URITemplate): + return NotImplemented + return self.uri == other.uri + + def __hash__(self) -> int: + return hash(self.uri) + + def _expand( + self, var_dict: variable.VariableValueDict, replace: bool + ) -> str: + if not self.variables: + return self.uri + + expansion = var_dict + expanded: t.Dict[str, str] = {} + for v in self.variables: + expanded.update(v.expand(expansion)) + + def replace_all(match: "re.Match[str]") -> str: + return expanded.get(match.groups()[0], "") + + def replace_partial(match: "re.Match[str]") -> str: + match_group = match.groups()[0] + var = "{%s}" % match_group + return expanded.get(match_group) or var + + replace_func = replace_partial if replace else replace_all + + return template_re.sub(replace_func, self.uri) + + def expand( + self, + var_dict: t.Optional[variable.VariableValueDict] = None, + **kwargs: variable.VariableValue, + ) -> str: + """Expand the template with the given parameters. + + :param dict var_dict: Optional dictionary with variables and values + :param kwargs: Alternative way to pass arguments + :returns: str + + Example:: + + t = URITemplate('https://api.github.com{/end}') + t.expand({'end': 'users'}) + t.expand(end='gists') + + .. note:: Passing values by both parts, may override values in + ``var_dict``. For example:: + + expand('https://{var}', {'var': 'val1'}, var='val2') + + ``val2`` will be used instead of ``val1``. + + """ + return self._expand(_merge(var_dict, kwargs), False) + + def partial( + self, + var_dict: t.Optional[variable.VariableValueDict] = None, + **kwargs: variable.VariableValue, + ) -> "URITemplate": + """Partially expand the template with the given parameters. + + If all of the parameters for the template are not given, return a + partially expanded template. + + :param dict var_dict: Optional dictionary with variables and values + :param kwargs: Alternative way to pass arguments + :returns: :class:`URITemplate` + + Example:: + + t = URITemplate('https://api.github.com{/end}') + t.partial() # => URITemplate('https://api.github.com{/end}') + + """ + return URITemplate(self._expand(_merge(var_dict, kwargs), True)) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/uritemplate/variable.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/uritemplate/variable.py new file mode 100644 index 0000000000000000000000000000000000000000..02e33e088fb4c665a088df56fc3ef2ca61e61dcc --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/uritemplate/variable.py @@ -0,0 +1,564 @@ +""" + +uritemplate.variable +==================== + +This module contains the URIVariable class which powers the URITemplate class. + +What treasures await you: + +- URIVariable class + +You see a hammer in front of you. +What do you do? +> + +""" + +import collections.abc +import enum +import string +import typing as t +import urllib.parse + +ScalarVariableValue = t.Union[int, float, complex, str, None] +VariableValue = t.Union[ + t.Sequence[ScalarVariableValue], + t.List[ScalarVariableValue], + t.Mapping[str, ScalarVariableValue], + t.Tuple[str, ScalarVariableValue], + ScalarVariableValue, +] +VariableValueDict = t.Dict[str, VariableValue] + + +_UNRESERVED_CHARACTERS: t.Final[str] = ( + f"{string.ascii_letters}{string.digits}~-_." +) +_GEN_DELIMS: t.Final[str] = ":/?#[]@" +_SUB_DELIMS: t.Final[str] = "!$&'()*+,;=" +_RESERVED_CHARACTERS: t.Final[str] = f"{_GEN_DELIMS}{_SUB_DELIMS}" + + +class Operator(enum.Enum): + # Section 2.2. Expressions + # expression = "{" [ operator ] variable-list "}" + # operator = op-level2 / op-level3 / op-reserve + # op-level2 = "+" / "#" + # op-level3 = "." / "/" / ";" / "?" / "&" + # op-reserve = "=" / "," / "!" / "@" / "|" + default = "" # 3.2.2. Simple String Expansiona: {var} + # Operator Level 2 (op-level2) + reserved = "+" # 3.2.3. Reserved Expansion: {+var} + fragment = "#" # 3.2.4. Fragment Expansion: {#var} + # Operator Level 3 (op-level3) + # 3.2.5. Label Expansion with Dot-Prefix: {.var} + label_with_dot_prefix = "." + path_segment = "/" # 3.2.6. Path Segment Expansion: {/var} + path_style_parameter = ( + ";" # 3.2.7. Path-Style Parameter Expansion: {;var} + ) + form_style_query = "?" # 3.2.8. Form-Style Query Expansion: {?var} + # 3.2.9. Form-Style Query Continuation: {&var} + form_style_query_continuation = "&" + # Reserved Operators (op-reserve) + reserved_eq = "=" + reserved_comma = "," + reserved_bang = "!" + reserved_at = "@" + reserved_pipe = "|" + + def reserved_characters(self) -> str: + # TODO: Re-enable after un-commenting 3.9 + # match self: + # case Operator.reserved: + # return _RESERVED_CHARACTERS + "%" + # # case Operator.default | Operator.reserved | Operator.fragment: + # case Operator.fragment: + # return _RESERVED_CHARACTERS + # case _: + # return "" + if self == Operator.reserved: + return _RESERVED_CHARACTERS + "%" + if self == Operator.fragment: + return _RESERVED_CHARACTERS + return "" + + def expansion_separator(self) -> str: + """Identify the separator used during expansion. + + Per `Section 3.2.1. Variable Expansion`_: + + ====== =========== ========= + Type Separator + ====== =========== ========= + ``","`` (default) + ``+`` ``","`` + ``#`` ``","`` + ``.`` ``"."`` + ``/`` ``"/"`` + ``;`` ``";"`` + ``?`` ``"&"`` + ``&`` ``"&"`` + ====== =========== ========= + + .. _`Section 3.2.1. Variable Expansion`: + https://www.rfc-editor.org/rfc/rfc6570#section-3.2.1 + """ + if self == Operator.label_with_dot_prefix: + return "." + if self == Operator.path_segment: + return "/" + if self == Operator.path_style_parameter: + return ";" + if ( + self == Operator.form_style_query + or self == Operator.form_style_query_continuation + ): + return "&" + # if self == Operator.reserved or self == Operator.fragment: + # return "," + return "," + # match self: + # case Operator.label_with_dot_prefix: + # return "." + # case Operator.path_segment: + # return "/" + # case Operator.path_style_parameter: + # return ";" + # case ( + # Operator.form_style_query | + # Operator.form_style_query_continuation + # ): + # return "&" + # case Operator.reserved | Operator.fragment: + # return "," + # case _: + # return "," + + def variable_prefix(self) -> str: + if self == Operator.reserved: + return "" + return t.cast(str, self.value) + # match self: + # case Operator.reserved: + # return "" + # case _: + # return t.cast(str, self.value) + + def _always_quote(self, value: str) -> str: + return quote(value, "") + + def _only_quote_unquoted_characters(self, value: str) -> str: + if urllib.parse.unquote(value) == value: + return quote(value, _RESERVED_CHARACTERS) + return value + + def quote(self, value: t.Any) -> str: + if not isinstance(value, (str, bytes)): + value = str(value) + if isinstance(value, bytes): + value = value.decode() + + if self == Operator.reserved or self == Operator.fragment: + return self._only_quote_unquoted_characters(value) + return self._always_quote(value) + + @staticmethod + def from_string(s: str) -> "Operator": + return _operators.get(s, Operator.default) + + +_operators: t.Final[t.Dict[str, Operator]] = { + "+": Operator.reserved, + "#": Operator.fragment, + ".": Operator.label_with_dot_prefix, + "/": Operator.path_segment, + ";": Operator.path_style_parameter, + "?": Operator.form_style_query, + "&": Operator.form_style_query_continuation, + "!": Operator.reserved_bang, + "|": Operator.reserved_pipe, + "@": Operator.reserved_at, + "=": Operator.reserved_eq, + ",": Operator.reserved_comma, +} + + +class URIVariable: + """This object validates everything inside the URITemplate object. + + It validates template expansions and will truncate length as decided by + the template. + + Please note that just like the :class:`URITemplate `, this + object's ``__str__`` and ``__repr__`` methods do not return the same + information. Calling ``str(var)`` will return the original variable. + + This object does the majority of the heavy lifting. The ``URITemplate`` + object finds the variables in the URI and then creates ``URIVariable`` + objects. Expansions of the URI are handled by each ``URIVariable`` + object. ``URIVariable.expand()`` returns a dictionary of the original + variable and the expanded value. Check that method's documentation for + more information. + + """ + + def __init__(self, var: str): + #: The original string that comes through with the variable + self.original: str = var + #: The operator for the variable + self.operator: Operator = Operator.default + #: List of variables in this variable + self.variables: t.List[t.Tuple[str, t.MutableMapping[str, t.Any]]] = ( + [] + ) + #: List of variable names + self.variable_names: t.List[str] = [] + #: List of defaults passed in + self.defaults: t.MutableMapping[str, ScalarVariableValue] = {} + # Parse the variable itself. + self.parse() + + def __repr__(self) -> str: + return "URIVariable(%s)" % self + + def __str__(self) -> str: + return self.original + + def parse(self) -> None: + """Parse the variable. + + This finds the: + - operator, + - set of safe characters, + - variables, and + - defaults. + + """ + var_list_str = self.original + if (operator_str := self.original[0]) in _operators: + self.operator = Operator.from_string(operator_str) + var_list_str = self.original[1:] + + var_list = var_list_str.split(",") + + for var in var_list: + default_val = None + name = var + # NOTE(sigmavirus24): This is from an earlier draft but is not in + # the specification + if "=" in var: + name, default_val = tuple(var.split("=", 1)) + + explode = name.endswith("*") + name = name.rstrip("*") + + prefix: t.Optional[int] = None + if ":" in name: + name, prefix_str = tuple(name.split(":", 1)) + prefix = int(prefix_str, 10) + + if default_val: + self.defaults[name] = default_val + + self.variables.append( + (name, {"explode": explode, "prefix": prefix}) + ) + + self.variable_names = [varname for (varname, _) in self.variables] + + def _query_expansion( + self, + name: str, + value: VariableValue, + explode: bool, + prefix: t.Optional[int], + ) -> t.Optional[str]: + """Expansion method for the '?' and '&' operators.""" + if value is None: + return None + + tuples, items = is_list_of_tuples(value) + + safe = self.operator.reserved_characters() + _quote = self.operator.quote + if list_test(value) and not tuples: + if not value: + return None + value = t.cast(t.Sequence[ScalarVariableValue], value) + if explode: + return self.operator.expansion_separator().join( + f"{name}={_quote(v)}" for v in value + ) + else: + value = ",".join(_quote(v) for v in value) + return f"{name}={value}" + + if dict_test(value) or tuples: + if not value: + return None + value = t.cast(t.Mapping[str, ScalarVariableValue], value) + items = items or sorted(value.items()) + if explode: + return self.operator.expansion_separator().join( + f"{quote(k, safe)}={_quote(v)}" for k, v in items + ) + else: + value = ",".join( + f"{quote(k, safe)},{_quote(v)}" for k, v in items + ) + return f"{name}={value}" + + if value: + value = t.cast(t.Text, value) + value = value[:prefix] if prefix else value + return f"{name}={_quote(value)}" + return name + "=" + + def _label_path_expansion( + self, + name: str, + value: VariableValue, + explode: bool, + prefix: t.Optional[int], + ) -> t.Optional[str]: + """Label and path expansion method. + + Expands for operators: '/', '.' + + """ + join_str = self.operator.expansion_separator() + safe = self.operator.reserved_characters() + + if value is None or ( + not isinstance(value, (str, int, float, complex)) + and len(value) == 0 + ): + return None + + tuples, items = is_list_of_tuples(value) + + if list_test(value) and not tuples: + if not explode: + join_str = "," + + value = t.cast(t.Sequence[ScalarVariableValue], value) + fragments = [ + self.operator.quote(v) for v in value if v is not None + ] + return join_str.join(fragments) if fragments else None + + if dict_test(value) or tuples: + value = t.cast(t.Mapping[str, ScalarVariableValue], value) + items = items or sorted(value.items()) + format_str = "%s=%s" + if not explode: + format_str = "%s,%s" + join_str = "," + + expanded = join_str.join( + format_str % (quote(k, safe), self.operator.quote(v)) + for k, v in items + if v is not None + ) + return expanded if expanded else None + + value = t.cast(t.Text, value) + value = value[:prefix] if prefix else value + return self.operator.quote(value) + + def _semi_path_expansion( + self, + name: str, + value: VariableValue, + explode: bool, + prefix: t.Optional[int], + ) -> t.Optional[str]: + """Expansion method for ';' operator.""" + join_str = self.operator.expansion_separator() + safe = self.operator.reserved_characters() + + if value is None: + return None + + tuples, items = is_list_of_tuples(value) + + if list_test(value) and not tuples: + value = t.cast(t.Sequence[ScalarVariableValue], value) + if explode: + expanded = join_str.join( + f"{name}={quote(v, safe)}" for v in value if v is not None + ) + return expanded if expanded else None + else: + value = ",".join(quote(v, safe) for v in value) + return f"{name}={value}" + + if dict_test(value) or tuples: + value = t.cast(t.Mapping[str, ScalarVariableValue], value) + items = items or sorted(value.items()) + + if explode: + return join_str.join( + f"{quote(k, safe)}={self.operator.quote(v)}" + for k, v in items + if v is not None + ) + else: + expanded = ",".join( + f"{quote(k, safe)},{self.operator.quote(v)}" + for k, v in items + if v is not None + ) + return f"{name}={expanded}" + + value = t.cast(t.Text, value) + value = value[:prefix] if prefix else value + if value: + return f"{name}={self.operator.quote(value)}" + + return name + + def _string_expansion( + self, + name: str, + value: VariableValue, + explode: bool, + prefix: t.Optional[int], + ) -> t.Optional[str]: + if value is None: + return None + + tuples, items = is_list_of_tuples(value) + + if list_test(value) and not tuples: + value = t.cast(t.Sequence[ScalarVariableValue], value) + return ",".join(self.operator.quote(v) for v in value) + + if dict_test(value) or tuples: + value = t.cast(t.Mapping[str, ScalarVariableValue], value) + items = items or sorted(value.items()) + format_str = "%s=%s" if explode else "%s,%s" + + return ",".join( + format_str % (self.operator.quote(k), self.operator.quote(v)) + for k, v in items + ) + + value = t.cast(t.Text, value) + value = value[:prefix] if prefix else value + return self.operator.quote(value) + + def expand( + self, var_dict: t.Optional[VariableValueDict] = None + ) -> t.Mapping[str, str]: + """Expand the variable in question. + + Using ``var_dict`` and the previously parsed defaults, expand this + variable and subvariables. + + :param dict var_dict: dictionary of key-value pairs to be used during + expansion + :returns: dict(variable=value) + + Examples:: + + # (1) + v = URIVariable('/var') + expansion = v.expand({'var': 'value'}) + print(expansion) + # => {'/var': '/value'} + + # (2) + v = URIVariable('?var,hello,x,y') + expansion = v.expand({'var': 'value', 'hello': 'Hello World!', + 'x': '1024', 'y': '768'}) + print(expansion) + # => {'?var,hello,x,y': + # '?var=value&hello=Hello%20World%21&x=1024&y=768'} + + """ + return_values = [] + if var_dict is None: + return {self.original: self.original} + + for name, opts in self.variables: + value = var_dict.get(name, None) + if not value and value != "" and name in self.defaults: + value = self.defaults[name] + + if value is None: + continue + + expanded = None + if ( + self.operator == Operator.path_segment + or self.operator == Operator.label_with_dot_prefix + ): + expansion = self._label_path_expansion + elif ( + self.operator == Operator.form_style_query + or self.operator == Operator.form_style_query_continuation + ): + expansion = self._query_expansion + elif self.operator == Operator.path_style_parameter: + expansion = self._semi_path_expansion + else: + expansion = self._string_expansion + # match self.operator: + # case Operator.path_segment | Operator.label_with_dot_prefix: + # expansion = self._label_path_expansion + # case (Operator.form_style_query | + # Operator.form_style_query_continuation): + # expansion = self._query_expansion + # case Operator.path_style_parameter: + # expansion = self._semi_path_expansion + # case _: + # expansion = self._string_expansion + + expanded = expansion(name, value, opts["explode"], opts["prefix"]) + + if expanded is not None: + return_values.append(expanded) + + value = "" + if return_values: + value = ( + self.operator.variable_prefix() + + self.operator.expansion_separator().join(return_values) + ) + return {self.original: value} + + +def is_list_of_tuples( + value: t.Any, +) -> t.Tuple[bool, t.Optional[t.Sequence[t.Tuple[str, ScalarVariableValue]]]]: + if ( + not value + or not isinstance(value, (list, tuple)) + or not all(isinstance(t, tuple) and len(t) == 2 for t in value) + ): + return False, None + + return True, value + + +def list_test(value: t.Any) -> bool: + return isinstance(value, (list, tuple)) + + +def dict_test(value: t.Any) -> bool: + return isinstance(value, (dict, collections.abc.MutableMapping)) + + +def _encode(value: t.AnyStr, encoding: str = "utf-8") -> bytes: + if isinstance(value, str): + return value.encode(encoding) + return value + + +def quote(value: t.Any, safe: str) -> str: + if not isinstance(value, (str, bytes)): + value = str(value) + return urllib.parse.quote(_encode(value), safe) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5c2f4cbede0967459b2978f7c851605dafad7299 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__init__.py @@ -0,0 +1,212 @@ +"""Use wandb to track machine learning work. + +Train and fine-tune models, manage models from experimentation to production. + +For guides and examples, see https://docs.wandb.ai. + +For scripts and interactive notebooks, see https://github.com/wandb/examples. + +For reference documentation, see https://docs.wandb.ai/models/ref/python. +""" +from __future__ import annotations + +__version__ = "0.27.0" + + +from wandb.errors import Error + +# This needs to be early as other modules call it. +from wandb.errors.term import termsetup, termlog, termerror, termwarn + +# Configure the logger as early as possible for consistent behavior. +from wandb.sdk.lib import wb_logging as _wb_logging +_wb_logging.configure_wandb_logger() + +from wandb import sdk as wandb_sdk + +import wandb + +wandb.wandb_lib = wandb_sdk.lib # type: ignore + +init = wandb_sdk.init +setup = wandb_sdk.setup +attach = _attach = wandb_sdk._attach +teardown = _teardown = wandb_sdk.teardown +finish = wandb_sdk.finish +join = finish +login = wandb_sdk.login +helper = wandb_sdk.helper +sweep = wandb_sdk.sweep +controller = wandb_sdk.controller +require = wandb_sdk.require +Artifact = wandb_sdk.Artifact +AlertLevel = wandb_sdk.AlertLevel +Settings = wandb_sdk.Settings +Config = wandb_sdk.Config + +from wandb.apis import InternalApi, PublicApi +from wandb.errors import CommError, UsageError + +from wandb.sdk.lib import preinit as _preinit +from wandb.sdk.lib import lazyloader as _lazyloader + +from wandb.integration.torch import wandb_torch + +from wandb.sdk.data_types._private import _cleanup_media_tmp_dir + +_cleanup_media_tmp_dir() + +from wandb.data_types import Graph +from wandb.data_types import Image +from wandb.data_types import Plotly +from wandb.data_types import Video +from wandb.data_types import Audio +from wandb.data_types import Table +from wandb.data_types import Html +from wandb.data_types import box3d +from wandb.data_types import Object3D +from wandb.data_types import Molecule +from wandb.data_types import Histogram +from wandb.data_types import Classes +from wandb.data_types import JoinedTable + +from wandb.wandb_agent import agent + +from wandb.plot import visualize, plot_table +from wandb.integration.sagemaker import sagemaker_auth +from wandb.sdk.internal import profiler +from wandb.sdk.wandb_run import Run + +# Artifact import types +from wandb.sdk.artifacts.artifact_ttl import ArtifactTTL + + +# globals +Api = PublicApi +api = InternalApi() +run: Run | None = None +config = _preinit.PreInitObject("wandb.config", wandb_sdk.wandb_config.Config) +summary = _preinit.PreInitObject("wandb.summary", wandb_sdk.wandb_summary.Summary) +log = _preinit.PreInitCallable("wandb.log", Run.log) # type: ignore +watch = _preinit.PreInitCallable("wandb.watch", Run.watch) # type: ignore +unwatch = _preinit.PreInitCallable("wandb.unwatch", Run.unwatch) # type: ignore +save = _preinit.PreInitCallable("wandb.save", Run.save) # type: ignore +restore = wandb_sdk.wandb_run.restore +use_artifact = _preinit.PreInitCallable( + "wandb.use_artifact", Run.use_artifact # type: ignore +) +log_artifact = _preinit.PreInitCallable( + "wandb.log_artifact", Run.log_artifact # type: ignore +) +log_model = _preinit.PreInitCallable( + "wandb.log_model", Run.log_model # type: ignore +) +use_model = _preinit.PreInitCallable( + "wandb.use_model", Run.use_model # type: ignore +) +link_model = _preinit.PreInitCallable( + "wandb.link_model", Run.link_model # type: ignore +) +define_metric = _preinit.PreInitCallable( + "wandb.define_metric", Run.define_metric # type: ignore +) + +mark_preempting = _preinit.PreInitCallable( + "wandb.mark_preempting", Run.mark_preempting # type: ignore +) + +alert = _preinit.PreInitCallable("wandb.alert", Run.alert) # type: ignore +pin_config_keys = _preinit.PreInitCallable( + "wandb.pin_config_keys", Run.pin_config_keys # type: ignore +) + +# record of patched libraries +patched = {"tensorboard": [], "keras": [], "gym": []} # type: ignore + +keras = _lazyloader.LazyLoader("wandb.keras", globals(), "wandb.integration.keras") +sklearn = _lazyloader.LazyLoader("wandb.sklearn", globals(), "wandb.sklearn") +tensorflow = _lazyloader.LazyLoader( + "wandb.tensorflow", globals(), "wandb.integration.tensorflow" +) +xgboost = _lazyloader.LazyLoader( + "wandb.xgboost", globals(), "wandb.integration.xgboost" +) +catboost = _lazyloader.LazyLoader( + "wandb.catboost", globals(), "wandb.integration.catboost" +) +tensorboard = _lazyloader.LazyLoader( + "wandb.tensorboard", globals(), "wandb.integration.tensorboard" +) +gym = _lazyloader.LazyLoader("wandb.gym", globals(), "wandb.integration.gym") +lightgbm = _lazyloader.LazyLoader( + "wandb.lightgbm", globals(), "wandb.integration.lightgbm" +) +jupyter = _lazyloader.LazyLoader("wandb.jupyter", globals(), "wandb.jupyter") +sacred = _lazyloader.LazyLoader("wandb.sacred", globals(), "wandb.integration.sacred") + + +def ensure_configured(): + global api + api = InternalApi() + + +def set_trace(): + import pdb + + pdb.set_trace() + + +if wandb_sdk.lib.ipython.in_notebook(): + from IPython import get_ipython # type: ignore[import-not-found] + + jupyter._load_ipython_extension(get_ipython()) + + +if "dev" in __version__: + import wandb.env + import os + + # Disable error reporting in dev versions. + os.environ[wandb.env.ERROR_REPORTING] = os.environ.get( + wandb.env.ERROR_REPORTING, + "false", + ) + + +__all__ = ( + "__version__", + "init", + "finish", + "setup", + "save", + "sweep", + "controller", + "agent", + "config", + "log", + "summary", + "join", + "Api", + "Graph", + "Image", + "Plotly", + "Video", + "Audio", + "Table", + "Html", + "box3d", + "Object3D", + "Molecule", + "Histogram", + "ArtifactTTL", + "log_artifact", + "use_artifact", + "log_model", + "use_model", + "link_model", + "define_metric", + "watch", + "unwatch", + "plot_table", + "Run", +) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__init__.pyi b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..fe09e6e42d4d3e3da5aa04c97ce26a7fdad37030 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__init__.pyi @@ -0,0 +1,1238 @@ +"""Use wandb to track machine learning work. + +Train and fine-tune models, manage models from experimentation to production. + +For guides and examples, see https://docs.wandb.ai. + +For scripts and interactive notebooks, see https://github.com/wandb/examples. + +For reference documentation, see https://docs.wandb.ai/models/ref/python. +""" + +from __future__ import annotations + +from wandb.sdk.lib.deprecation import UNSET, DoNotSet + +__all__ = ( + "__version__", # doc:exclude + "init", + "finish", + "setup", + "login", + "save", # doc:exclude + "sweep", + "controller", + "agent", + "config", # doc:exclude + "log", # doc:exclude + "summary", # doc:exclude + "Api", + "Graph", # doc:exclude + "Image", + "Plotly", + "Video", + "Audio", + "Table", + "Html", + "box3d", + "Object3D", + "Molecule", + "Histogram", + "ArtifactTTL", # doc:exclude + "log_artifact", # doc:exclude + "use_artifact", # doc:exclude + "log_model", # doc:exclude + "use_model", # doc:exclude + "link_model", # doc:exclude + "define_metric", # doc:exclude + "Error", # doc:exclude + "termsetup", # doc:exclude + "termlog", # doc:exclude + "termerror", # doc:exclude + "termwarn", # doc:exclude + "Artifact", + "Settings", + "teardown", + "watch", # doc:exclude + "unwatch", # doc:exclude + "plot", # doc:exclude + "plot_table", + "restore", + "Run", +) + +import os +from collections.abc import Iterable, Sequence +from typing import TYPE_CHECKING, Any, Callable, Literal, TextIO + +import wandb.plot as plot +from wandb.apis import InternalApi +from wandb.apis import PublicApi as Api +from wandb.data_types import ( + Audio, + Graph, + Histogram, + Html, + Image, + Molecule, + Object3D, + Plotly, + Table, + Video, + box3d, +) +from wandb.errors import Error +from wandb.errors.term import termerror, termlog, termsetup, termwarn +from wandb.sdk import Artifact, Settings, wandb_config, wandb_metric, wandb_summary +from wandb.sdk.artifacts.artifact_ttl import ArtifactTTL +from wandb.sdk.lib.filesystem import PolicyName +from wandb.sdk.lib.paths import FilePathStr, StrPath +from wandb.sdk.wandb_run import Run +from wandb.sdk.wandb_setup import _WandbSetup +from wandb.wandb_controller import _WandbController + +if TYPE_CHECKING: + import torch # type: ignore [import-not-found] + + import wandb + from wandb.plot import CustomChart + +__version__: str = "0.27.0" + +run: Run | None +config: wandb_config.Config +summary: wandb_summary.Summary + +# private attributes +api: InternalApi +patched: dict[str, list[Callable]] + +def require( + requirement: str | Iterable[str] | None = None, + experiment: str | Iterable[str] | None = None, +) -> None: + """Indicate which experimental features are used by the script. + + This should be called before any other `wandb` functions, ideally right + after importing `wandb`. + + Args: + requirement: The name of a feature to require or an iterable of + feature names. + experiment: An alias for `requirement`. + + Raises: + wandb.errors.UnsupportedError: If a feature name is unknown. + """ + ... + +def setup(settings: Settings | None = None) -> _WandbSetup: + """Prepares W&B for use in the current process and its children. + + You can usually ignore this as it is implicitly called by `wandb.init()`. + + When using wandb in multiple processes, calling `wandb.setup()` + in the parent process before starting child processes may improve + performance and resource utilization. + + Note that `wandb.setup()` modifies `os.environ`, and it is important + that child processes inherit the modified environment variables. + + See also `wandb.teardown()`. + + Args: + settings: Configuration settings to apply globally. These can be + overridden by subsequent `wandb.init()` calls. + + Example: + ```python + import multiprocessing + + import wandb + + def run_experiment(params): + with wandb.init(config=params): + # Run experiment + pass + + if __name__ == "__main__": + # Start backend and set global config + wandb.setup(settings={"project": "my_project"}) + + # Define experiment parameters + experiment_params = [ + {"learning_rate": 0.01, "epochs": 10}, + {"learning_rate": 0.001, "epochs": 20}, + ] + + # Start multiple processes, each running a separate experiment + processes = [] + for params in experiment_params: + p = multiprocessing.Process(target=run_experiment, args=(params,)) + p.start() + processes.append(p) + + # Wait for all processes to complete + for p in processes: + p.join() + + # Optional: Explicitly shut down the backend + wandb.teardown() + ``` + """ + ... + +def teardown(exit_code: int | None = None) -> None: + """Waits for W&B to finish and frees resources. + + Completes any runs that were not explicitly finished + using `run.finish()` and waits for all data to be uploaded. + + It is recommended to call this at the end of a session + that used `wandb.setup()`. It is invoked automatically + in an `atexit` hook, but this is not reliable in certain setups + such as when using Python's `multiprocessing` module. + """ + ... + +def init( + entity: str | None = None, + project: str | None = None, + dir: StrPath | None = None, + id: str | None = None, + name: str | None = None, + notes: str | None = None, + tags: Sequence[str] | None = None, + config: dict[str, Any] | str | None = None, + config_exclude_keys: list[str] | None = None, + config_include_keys: list[str] | None = None, + allow_val_change: bool | None = None, + group: str | None = None, + job_type: str | None = None, + mode: Literal["online", "offline", "disabled", "shared"] | None = None, + force: bool | None = None, + reinit: ( + bool + | Literal[ + None, + "default", + "return_previous", + "finish_previous", + "create_new", + ] + ) = None, + resume: bool | Literal["allow", "never", "must", "auto"] | None = None, + resume_from: str | None = None, + fork_from: str | None = None, + save_code: bool | None = None, + tensorboard: bool | None = None, + sync_tensorboard: bool | None = None, + monitor_gym: bool | None = None, + settings: Settings | dict[str, Any] | None = None, + anonymous: DoNotSet = UNSET, +) -> Run: + r"""Start a new run to track and log to W&B. + + In an ML training pipeline, you could add `wandb.init()` to the beginning of + your training script as well as your evaluation script, and each piece would + be tracked as a run in W&B. + + `wandb.init()` spawns a new background process to log data to a run, and it + also syncs data to https://wandb.ai by default, so you can see your results + in real-time. When you're done logging data, call `run.finish()` to + end the run, or use the run as a context manager to call it automatically: + + with wandb.init() as run: + ... # run.finish() executes at the end of the block + + If you don't call `run.finish()`, the run will end when your script exits. + + Run IDs must not contain any of the following special characters `/ \ # ? % :` + + Args: + entity: The username or team name the runs are logged to. + The entity must already exist, so ensure you create your account + or team in the UI before starting to log runs. If not specified, the + run will default your default entity. To change the default entity, + go to your settings and update the + "Default location to create new projects" under "Default team". + project: The name of the project under which this run will be logged. + If not specified, we use a heuristic to infer the project name based + on the system, such as checking the git root or the current program + file. If we can't infer the project name, the project will default to + `"uncategorized"`. + dir: The absolute path to the directory where experiment logs and + metadata files are stored. If not specified, this defaults + to the `./wandb` directory. Note that this does not affect the + location where artifacts are stored when calling `download()`. + id: A unique identifier for this run, used for resuming. It must be unique + within the project and cannot be reused once a run is deleted. For + a short descriptive name, use the `name` field, + or for saving hyperparameters to compare across runs, use `config`. + name: A short display name for this run, which appears in the UI to help + you identify it. By default, we generate a random two-word name + allowing easy cross-reference runs from table to charts. Keeping these + run names brief enhances readability in chart legends and tables. For + saving hyperparameters, we recommend using the `config` field. + notes: A detailed description of the run, similar to a commit message in + Git. Use this argument to capture any context or details that may + help you recall the purpose or setup of this run in the future. + tags: A list of tags to label this run in the UI. Tags are helpful for + organizing runs or adding temporary identifiers like "baseline" or + "production." You can easily add, remove tags, or filter by tags in + the UI. + If resuming a run, the tags provided here will replace any existing + tags. To add tags to a resumed run without overwriting the current + tags, use `run.tags += ("new_tag",)` after calling `run = wandb.init()`. + config: Sets `wandb.config`, a dictionary-like object for storing input + parameters to your run, such as model hyperparameters or data + preprocessing settings. + The config appears in the UI in an overview page, allowing you to + group, filter, and sort runs based on these parameters. + Keys should not contain periods (`.`), and values should be + smaller than 10 MB. + If a dictionary, `argparse.Namespace`, or `absl.flags.FLAGS` is + provided, the key-value pairs will be loaded directly into + `wandb.config`. + If a string is provided, it is interpreted as a path to a YAML file, + from which configuration values will be loaded into `wandb.config`. + config_exclude_keys: A list of specific keys to exclude from `wandb.config`. + config_include_keys: A list of specific keys to include in `wandb.config`. + allow_val_change: Controls whether config values can be modified after their + initial set. By default, an exception is raised if a config value is + overwritten. For tracking variables that change during training, such as + a learning rate, consider using `wandb.log()` instead. By default, this + is `False` in scripts and `True` in Notebook environments. + group: Specify a group name to organize individual runs as part of a larger + experiment. This is useful for cases like cross-validation or running + multiple jobs that train and evaluate a model on different test sets. + Grouping allows you to manage related runs collectively in the UI, + making it easy to toggle and review results as a unified experiment. + job_type: Specify the type of run, especially helpful when organizing runs + within a group as part of a larger experiment. For example, in a group, + you might label runs with job types such as "train" and "eval". + Defining job types enables you to easily filter and group similar runs + in the UI, facilitating direct comparisons. + mode: Specifies how run data is managed, with the following options: + - `"online"` (default): Enables live syncing with W&B when a network + connection is available, with real-time updates to visualizations. + - `"offline"`: Suitable for air-gapped or offline environments; data + is saved locally and can be synced later. Ensure the run folder + is preserved to enable future syncing. + - `"disabled"`: Disables all W&B functionality, making the run’s methods + no-ops. Typically used in testing to bypass W&B operations. + - `"shared"`: (This is an experimental feature). Allows multiple processes, + possibly on different machines, to simultaneously log to the same run. + In this approach you use a primary node and one or more worker nodes + to log data to the same run. Within the primary node you + initialize a run. For each worker node, initialize a run + using the run ID used by the primary node. + force: Determines if a W&B login is required to run the script. If `True`, + the user must be logged in to W&B; otherwise, the script will not + proceed. If `False` (default), the script can proceed without a login, + switching to offline mode if the user is not logged in. + reinit: Shorthand for the "reinit" setting. Determines the behavior of + `wandb.init()` when a run is active. + resume: Controls the behavior when resuming a run with the specified `id`. + Available options are: + - `"allow"`: If a run with the specified `id` exists, it will resume + from the last step; otherwise, a new run will be created. + - `"never"`: If a run with the specified `id` exists, an error will + be raised. If no such run is found, a new run will be created. + - `"must"`: If a run with the specified `id` exists, it will resume + from the last step. If no run is found, an error will be raised. + - `"auto"`: Automatically resumes the previous run if it crashed on + this machine; otherwise, starts a new run. + - `True`: Deprecated. Use `"auto"` instead. + - `False`: Deprecated. Use the default behavior (leaving `resume` + unset) to always start a new run. + If `resume` is set, `fork_from` and `resume_from` cannot be + used. When `resume` is unset, the system will always start a new run. + resume_from: Specifies a moment in a previous run to resume a run from, + using the format `{run_id}?_step={step}`. This allows users to truncate + the history logged to a run at an intermediate step and resume logging + from that step. The target run must be in the same project. + If an `id` argument is also provided, the `resume_from` argument will + take precedence. + `resume`, `resume_from` and `fork_from` cannot be used together, only + one of them can be used at a time. + Note that this feature is in beta and may change in the future. + fork_from: Specifies a point in a previous run from which to fork a new + run, using the format `{id}?_step={step}`. This creates a new run that + resumes logging from the specified step in the target run’s history. + The target run must be part of the current project. + If an `id` argument is also provided, it must be different from the + `fork_from` argument, an error will be raised if they are the same. + `resume`, `resume_from` and `fork_from` cannot be used together, only + one of them can be used at a time. + Note that this feature is in beta and may change in the future. + save_code: Enables saving the main script or notebook to W&B, aiding in + experiment reproducibility and allowing code comparisons across runs in + the UI. By default, this is disabled, but you can change the default to + enable on your settings page. + tensorboard: Deprecated. Use `sync_tensorboard` instead. + sync_tensorboard: Enables automatic syncing of W&B logs from TensorBoard + or TensorBoardX, saving relevant event files for viewing in + the W&B UI. + monitor_gym: Enables automatic logging of videos of the environment when + using OpenAI Gym. + settings: Specifies a dictionary or `wandb.Settings` object with advanced + settings for the run. + + Returns: + A `Run` object. + + Raises: + Error: If some unknown or internal error happened during the run + initialization. + AuthenticationError: If the user failed to provide valid credentials. + CommError: If there was a problem communicating with the WandB server. + UsageError: If the user provided invalid arguments. + KeyboardInterrupt: If user interrupts the run. + + Examples: + `wandb.init()` returns a `Run` object. Use the run object to log data, + save artifacts, and manage the run lifecycle. + + ```python + import wandb + + config = {"lr": 0.01, "batch_size": 32} + with wandb.init(config=config) as run: + # Log accuracy and loss to the run + acc = 0.95 # Example accuracy + loss = 0.05 # Example loss + run.log({"accuracy": acc, "loss": loss}) + ``` + """ + ... + +def finish( + exit_code: int | None = None, + quiet: bool | None = None, +) -> None: + """Finish a run and upload any remaining data. + + Marks the completion of a W&B run and ensures all data is synced to the server. + The run's final state is determined by its exit conditions and sync status. + + Run States: + - Running: Active run that is logging data and/or sending heartbeats. + - Crashed: Run that stopped sending heartbeats unexpectedly. + - Finished: Run completed successfully (`exit_code=0`) with all data synced. + - Failed: Run completed with errors (`exit_code!=0`). + + Args: + exit_code: Integer indicating the run's exit status. Use 0 for success, + any other value marks the run as failed. + quiet: Deprecated. Configure logging verbosity using `wandb.Settings(quiet=...)`. + """ + ... + +def login( + key: str | None = None, + relogin: bool | None = None, + host: str | None = None, + force: bool | None = None, + timeout: int | None = None, + verify: bool = False, + referrer: str | None = None, + anonymous: DoNotSet = UNSET, +) -> bool: + """Log into W&B. + + You generally don't have to use this because most W&B methods that need + authentication can log in implicitly. This is the programmatic counterpart + to the `wandb login` CLI. + + This updates global credentials for the session (affecting all wandb usage + in the current Python process after this call) and possibly the .netrc file. + + If the identity_token_file setting is set, like through the + WANDB_IDENTITY_TOKEN_FILE environment variable, then this is a no-op. + + Otherwise, if an explicit API key is provided, it is used and written to + the system .netrc file. If no key is provided, but the session is already + authenticated, then the session key is used for verification (if verify + is True) and the .netrc file is not updated. + + If none of the above is true, then this gets the API key from the first of: + + - The WANDB_API_KEY environment variable + - The api_key setting in a system or workspace settings file + - The .netrc file (either ~/.netrc, ~/_netrc or the path specified by the + NETRC environment variable) + - An interactive prompt (if available) + + Args: + key: The API key to use. + relogin: If true, get the API key from an interactive prompt, skipping + reading .netrc, environment variables, etc. + host: The W&B server URL to connect to. + force: If true, disallows selecting offline mode in the interactive + prompt. + timeout: Number of seconds to wait for user input in the interactive + prompt. This can be used as a failsafe if an interactive prompt + is incorrectly shown in a non-interactive environment. + verify: Verify the credentials with the W&B server and raise an + AuthenticationError on failure. + referrer: The referrer to use in the URL login request for analytics. + + Returns: + bool: If `key` is configured. + + Raises: + AuthenticationError: If `api_key` fails verification with the server. + UsageError: If `api_key` cannot be configured and no tty. + """ + ... + +def log( + data: dict[str, Any], + step: int | None = None, + commit: bool | None = None, +) -> None: + """Upload run data. + + Use `log` to log data from runs, such as scalars, images, video, + histograms, plots, and tables. See [Log objects and media](https://docs.wandb.ai/models/track/log) for + code snippets, best practices, and more. + + Basic usage: + + ```python + import wandb + + with wandb.init() as run: + run.log({"train-loss": 0.5, "accuracy": 0.9}) + ``` + + The previous code snippet saves the loss and accuracy to the run's + history and updates the summary values for these metrics. + + Visualize logged data in a workspace at [wandb.ai](https://wandb.ai), + or locally on a [self-hosted instance](https://docs.wandb.ai/platform/hosting) + of the W&B app, or export data to visualize and explore locally, such as in a + Jupyter notebook, with the [Public API](https://docs.wandb.ai/models/track/public-api-guide). + + Logged values don't have to be scalars. You can log any + [W&B supported Data Type](https://docs.wandb.ai/models/ref/python/data-types) + such as images, audio, video, and more. For example, you can use + `wandb.Table` to log structured data. See + [Log tables, visualize and query data](https://docs.wandb.ai/models/tables/tables-walkthrough) + tutorial for more details. + + W&B organizes metrics with a forward slash (`/`) in their name + into sections named using the text before the final slash. For example, + the following results in two sections named "train" and "validate": + + ```python + with wandb.init() as run: + # Log metrics in the "train" section. + run.log( + { + "train/accuracy": 0.9, + "train/loss": 30, + "validate/accuracy": 0.8, + "validate/loss": 20, + } + ) + ``` + + Only one level of nesting is supported; `run.log({"a/b/c": 1})` + produces a section named "a". + + `run.log()` is not intended to be called more than a few times per second. + For optimal performance, limit your logging to once every N iterations, + or collect data over multiple iterations and log it in a single step. + + By default, each call to `log` creates a new "step". + The step must always increase, and it is not possible to log + to a previous step. You can use any metric as the X axis in charts. + See [Custom log axes](https://docs.wandb.ai/models/track/log/customize-logging-axes) + for more details. + + In many cases, it is better to treat the W&B step like + you'd treat a timestamp rather than a training step. + + ```python + with wandb.init() as run: + # Example: log an "epoch" metric for use as an X axis. + run.log({"epoch": 40, "train-loss": 0.5}) + ``` + + It is possible to use multiple `wandb.Run.log()` invocations to log to + the same step with the `step` and `commit` parameters. + The following are all equivalent: + + ```python + with wandb.init() as run: + # Normal usage: + run.log({"train-loss": 0.5, "accuracy": 0.8}) + run.log({"train-loss": 0.4, "accuracy": 0.9}) + + # Implicit step without auto-incrementing: + run.log({"train-loss": 0.5}, commit=False) + run.log({"accuracy": 0.8}) + run.log({"train-loss": 0.4}, commit=False) + run.log({"accuracy": 0.9}) + + # Explicit step: + run.log({"train-loss": 0.5}, step=current_step) + run.log({"accuracy": 0.8}, step=current_step) + current_step += 1 + run.log({"train-loss": 0.4}, step=current_step) + run.log({"accuracy": 0.9}, step=current_step, commit=True) + ``` + + Args: + data: A `dict` with `str` keys and values that are serializable + Python objects including: `int`, `float` and `string`; + any of the `wandb.data_types`; lists, tuples and NumPy arrays + of serializable Python objects; other `dict`s of this + structure. + step: The step number to log. If `None`, then an implicit + auto-incrementing step is used. See the notes in + the description. + commit: If true, finalize and upload the step. If false, then + accumulate data for the step. See the notes in the description. + If `step` is `None`, then the default is `commit=True`; + otherwise, the default is `commit=False`. + + Examples: + For more and more detailed examples, see + [our guides to logging](https://docs.wandb.ai/models/track/log). + + Basic usage + + ```python + import wandb + + with wandb.init() as run: + run.log({"train-loss": 0.5, "accuracy": 0.9 + ``` + + Incremental logging + + ```python + import wandb + + with wandb.init() as run: + run.log({"loss": 0.2}, commit=False) + # Somewhere else when I'm ready to report this step: + run.log({"accuracy": 0.8}) + ``` + + Histogram + + ```python + import numpy as np + import wandb + + # sample gradients at random from normal distribution + gradients = np.random.randn(100, 100) + with wandb.init() as run: + run.log({"gradients": wandb.Histogram(gradients)}) + ``` + + Image from NumPy + + ```python + import numpy as np + import wandb + + with wandb.init() as run: + examples = [] + for i in range(3): + pixels = np.random.randint(low=0, high=256, size=(100, 100, 3)) + image = wandb.Image(pixels, caption=f"random field {i}") + examples.append(image) + run.log({"examples": examples}) + ``` + + Image from PIL + + ```python + import numpy as np + from PIL import Image as PILImage + import wandb + + with wandb.init() as run: + examples = [] + for i in range(3): + pixels = np.random.randint( + low=0, + high=256, + size=(100, 100, 3), + dtype=np.uint8, + ) + pil_image = PILImage.fromarray(pixels, mode="RGB") + image = wandb.Image(pil_image, caption=f"random field {i}") + examples.append(image) + run.log({"examples": examples}) + ``` + + Video from NumPy + + ```python + import numpy as np + import wandb + + with wandb.init() as run: + # axes are (time, channel, height, width) + frames = np.random.randint( + low=0, + high=256, + size=(10, 3, 100, 100), + dtype=np.uint8, + ) + run.log({"video": wandb.Video(frames, fps=4)}) + ``` + + Matplotlib plot + + ```python + from matplotlib import pyplot as plt + import numpy as np + import wandb + + with wandb.init() as run: + fig, ax = plt.subplots() + x = np.linspace(0, 10) + y = x * x + ax.plot(x, y) # plot y = x^2 + run.log({"chart": fig}) + ``` + + PR Curve + + ```python + import wandb + + with wandb.init() as run: + run.log({"pr": wandb.plot.pr_curve(y_test, y_probas, labels)}) + ``` + + 3D Object + + ```python + import wandb + + with wandb.init() as run: + run.log( + { + "generated_samples": [ + wandb.Object3D(open("sample.obj")), + wandb.Object3D(open("sample.gltf")), + wandb.Object3D(open("sample.glb")), + ] + } + ) + ``` + + Raises: + wandb.Error: If called before `wandb.init()`. + ValueError: If invalid data is passed. + """ + ... + +def save( + glob_str: str | os.PathLike, + base_path: str | os.PathLike | None = None, + policy: PolicyName = "live", +) -> bool | list[str]: + """Sync one or more files to W&B. + + Relative paths are relative to the current working directory. + + A Unix glob, such as "myfiles/*", is expanded at the time `save` is + called regardless of the `policy`. In particular, new files are not + picked up automatically. + + A `base_path` may be provided to control the directory structure of + uploaded files. It should be a prefix of `glob_str`, and the directory + structure beneath it is preserved. + + When given an absolute path or glob and no `base_path`, one + directory level is preserved as in the example above. + + Files are automatically deduplicated: calling `save()` multiple times + on the same file without modifications will not re-upload it. + + Args: + glob_str: A relative or absolute path or Unix glob. + base_path: A path to use to infer a directory structure; see examples. + policy: One of `live`, `now`, or `end`. + - live: upload the file as it changes, overwriting the previous version + - now: upload the file once now + - end: upload file when the run ends + + Returns: + Paths to the symlinks created for the matched files. + + For historical reasons, this may return a boolean in legacy code. + + ```python + import wandb + + run = wandb.init() + + run.save("these/are/myfiles/*") + # => Saves files in a "these/are/myfiles/" folder in the run. + + run.save("these/are/myfiles/*", base_path="these") + # => Saves files in an "are/myfiles/" folder in the run. + + run.save("/Users/username/Documents/run123/*.txt") + # => Saves files in a "run123/" folder in the run. See note below. + + run.save("/Users/username/Documents/run123/*.txt", base_path="/Users") + # => Saves files in a "username/Documents/run123/" folder in the run. + + run.save("files/*/saveme.txt") + # => Saves each "saveme.txt" file in an appropriate subdirectory + # of "files/". + + # Explicitly finish the run since a context manager is not used. + run.finish() + ``` + """ + ... + +def sweep( + sweep: dict | Callable, + entity: str | None = None, + project: str | None = None, + prior_runs: list[str] | None = None, +) -> str: + """Initialize a hyperparameter sweep. + + Search for hyperparameters that optimizes a cost function + of a machine learning model by testing various combinations. + + Make note the unique identifier, `sweep_id`, that is returned. + At a later step provide the `sweep_id` to a sweep agent. + + See [Sweep configuration structure](https://docs.wandb.ai/models/sweeps/define-sweep-configuration) + for information on how to define your sweep. + + Args: + sweep: The configuration of a hyperparameter search. + (or configuration generator). + If you provide a callable, ensure that the callable does + not take arguments and that it returns a dictionary that + conforms to the W&B sweep config spec. + entity: The username or team name where you want to send W&B + runs created by the sweep to. Ensure that the entity you + specify already exists. If you don't specify an entity, + the run will be sent to your default entity, + which is usually your username. + project: The name of the project where W&B runs created from + the sweep are sent to. If the project is not specified, the + run is sent to a project labeled 'Uncategorized'. + prior_runs: The run IDs of existing runs to add to this sweep. + + Returns: + str: A unique identifier for the sweep. + """ + ... + +def controller( + sweep_id_or_config: str | dict | None = None, + entity: str | None = None, + project: str | None = None, +) -> _WandbController: + """Public sweep controller constructor. + + Examples: + ```python + import wandb + + tuner = wandb.controller(...) + print(tuner.sweep_config) + print(tuner.sweep_id) + tuner.configure_search(...) + tuner.configure_stopping(...) + ``` + """ + ... + +def agent( + sweep_id: str, + function: Callable | None = None, + entity: str | None = None, + project: str | None = None, + count: int | None = None, + forward_signals: bool = False, +) -> None: + """Start one or more sweep agents. + + The sweep agent uses the `sweep_id` to know which sweep it + is a part of, what function to execute, and (optionally) how + many agents to run. + + Args: + sweep_id: The unique identifier for a sweep. A sweep ID + is generated by W&B CLI or Python SDK. + function: A function to call instead of the "program" + specified in the sweep config. + entity: The username or team name where you want to send W&B + runs created by the sweep to. Ensure that the entity you + specify already exists. If you don't specify an entity, + the run will be sent to your default entity, + which is usually your username. + project: The name of the project where W&B runs created from + the sweep are sent to. If the project is not specified, the + run is sent to a project labeled "Uncategorized". + count: The number of sweep config trials to try. + forward_signals: Whether to forward signals the agent receives + to the child processes. Only supported by CLI agent. + """ + ... + +def define_metric( + name: str, + step_metric: str | wandb_metric.Metric | None = None, + step_sync: bool | None = None, + hidden: bool | None = None, + summary: str | None = None, + goal: str | None = None, + overwrite: bool | None = None, +) -> wandb_metric.Metric: + """Customize metrics logged with `wandb.Run.log()`. + + Args: + name: The name of the metric to customize. + step_metric: The name of another metric to serve as the X-axis + for this metric in automatically generated charts. + step_sync: Automatically insert the last value of step_metric into + `wandb.Run.log()` if it is not provided explicitly. Defaults to True + if step_metric is specified. + hidden: Hide this metric from automatic plots. + summary: Specify aggregate metrics added to summary. + Supported aggregations include "min", "max", "mean", "last", + "first", "best", "copy" and "none". "none" prevents a summary + from being generated. "best" is used together with the goal + parameter, "best" is deprecated and should not be used, use + "min" or "max" instead. "copy" is deprecated and should not be + used. + goal: Specify how to interpret the "best" summary type. + Supported options are "minimize" and "maximize". "goal" is + deprecated and should not be used, use "min" or "max" instead. + overwrite: If false, then this call is merged with previous + `define_metric` calls for the same metric by using their + values for any unspecified parameters. If true, then + unspecified parameters overwrite values specified by + previous calls. + + Returns: + An object that represents this call but can otherwise be discarded. + """ + ... + +def log_artifact( + artifact_or_path: Artifact | StrPath, + name: str | None = None, + type: str | None = None, + aliases: list[str] | None = None, + tags: list[str] | None = None, +) -> Artifact: + """Declare an artifact as an output of a run. + + Args: + artifact_or_path: (str or Artifact) A path to the contents of this artifact, + can be in the following forms: + - `/local/directory` + - `/local/directory/file.txt` + - `s3://bucket/path` + You can also pass an Artifact object created by calling + `wandb.Artifact`. + name: (str, optional) An artifact name. Valid names can be in the following forms: + - name:version + - name:alias + - digest + This will default to the basename of the path prepended with the current + run id if not specified. + type: (str) The type of artifact to log, examples include `dataset`, `model` + aliases: (list, optional) Aliases to apply to this artifact, + defaults to `["latest"]` + tags: (list, optional) Tags to apply to this artifact, if any. + + Returns: + An `Artifact` object. + """ + ... + +def use_artifact( + artifact_or_name: str | Artifact, + type: str | None = None, + aliases: list[str] | None = None, + use_as: str | None = None, +) -> Artifact: + """Declare an artifact as an input to a run. + + Call `download` or `file` on the returned object to get the contents locally. + + Args: + artifact_or_name: The name of the artifact to use. May be prefixed + with the name of the project the artifact was logged to + ("entity" or "entity/project"). If no + entity is specified in the name, the Run or API setting's entity is used. + Valid names can be in the following forms + - name:version + - name:alias + type: The type of artifact to use. + aliases: Aliases to apply to this artifact + use_as: This argument is deprecated and does nothing. + + Returns: + An `Artifact` object. + + Examples: + ```python + import wandb + + run = wandb.init(project="") + + # Use an artifact by name and alias + artifact_a = run.use_artifact(artifact_or_name=":") + + # Use an artifact by name and version + artifact_b = run.use_artifact(artifact_or_name=":v") + + # Use an artifact by entity/project/name:alias + artifact_c = run.use_artifact(artifact_or_name="//:") + + # Use an artifact by entity/project/name:version + artifact_d = run.use_artifact( + artifact_or_name="//:v" + ) + + # Explicitly finish the run since a context manager is not used. + run.finish() + ``` + """ + ... + +def log_model( + path: StrPath, + name: str | None = None, + aliases: list[str] | None = None, +) -> None: + """Logs a model artifact containing the contents inside the 'path' to a run and marks it as an output to this run. + + The name of model artifact can only contain alphanumeric characters, + underscores, and hyphens. + + Args: + path: (str) A path to the contents of this model, + can be in the following forms: + - `/local/directory` + - `/local/directory/file.txt` + - `s3://bucket/path` + name: A name to assign to the model artifact that + the file contents will be added to. This will default to the + basename of the path prepended with the current run id if + not specified. + aliases: Aliases to apply to the created model artifact, + defaults to `["latest"]` + + Raises: + ValueError: If name has invalid special characters. + + Returns: + None + """ + ... + +def use_model(name: str) -> FilePathStr: + """Download the files logged in a model artifact 'name'. + + Args: + name: A model artifact name. 'name' must match the name of an existing logged + model artifact. May be prefixed with `entity/project/`. Valid names + can be in the following forms + - model_artifact_name:version + - model_artifact_name:alias + + Returns: + path (str): Path to downloaded model artifact file(s). + + Raises: + AssertionError: If model artifact 'name' is of a type that does + not contain the substring 'model'. + """ + ... + +def link_model( + path: StrPath, + registered_model_name: str, + name: str | None = None, + aliases: list[str] | None = None, +) -> Artifact | None: + """Log a model artifact version and link it to a registered model in the model registry. + + Linked model versions are visible in the UI for the specified registered model. + + This method will: + - Check if 'name' model artifact has been logged. If so, use the artifact version that matches the files + located at 'path' or log a new version. Otherwise log files under 'path' as a new model artifact, 'name' + of type 'model'. + - Check if registered model with name 'registered_model_name' exists in the 'model-registry' project. + If not, create a new registered model with name 'registered_model_name'. + - Link version of model artifact 'name' to registered model, 'registered_model_name'. + - Attach aliases from 'aliases' list to the newly linked model artifact version. + + Args: + path: (str) A path to the contents of this model, can be in the + following forms: + - `/local/directory` + - `/local/directory/file.txt` + - `s3://bucket/path` + registered_model_name: The name of the registered model that the + model is to be linked to. A registered model is a collection of + model versions linked to the model registry, typically + representing a team's specific ML Task. The entity that this + registered model belongs to will be derived from the run. + name: The name of the model artifact that files in 'path' will be + logged to. This will default to the basename of the path + prepended with the current run id if not specified. + aliases: Aliases that will only be applied on this linked artifact + inside the registered model. The alias "latest" will always be + applied to the latest version of an artifact that is linked. + + Raises: + AssertionError: If registered_model_name is a path or + if model artifact 'name' is of a type that does not contain + the substring 'model'. + ValueError: If name has invalid special characters. + + Returns: + The linked artifact if linking was successful, otherwise `None`. + """ + ... + +def plot_table( + vega_spec_name: str, + data_table: wandb.Table, + fields: dict[str, Any], + string_fields: dict[str, Any] | None = None, + split_table: bool = False, +) -> CustomChart: + """Creates a custom charts using a Vega-Lite specification and a `wandb.Table`. + + This function creates a custom chart based on a Vega-Lite specification and + a data table represented by a `wandb.Table` object. The specification needs + to be predefined and stored in the W&B backend. The function returns a custom + chart object that can be logged to W&B using `wandb.Run.log()`. + + Args: + vega_spec_name: The name or identifier of the Vega-Lite spec + that defines the visualization structure. + data_table: A `wandb.Table` object containing the data to be + visualized. + fields: A mapping between the fields in the Vega-Lite spec and the + corresponding columns in the data table to be visualized. + string_fields: A dictionary for providing values for any string constants + required by the custom visualization. + split_table: Whether the table should be split into a separate section + in the W&B UI. If `True`, the table will be displayed in a section named + "Custom Chart Tables". Default is `False`. + + Returns: + CustomChart: A custom chart object that can be logged to W&B. To log the + chart, pass the chart object as argument to `wandb.Run.log()`. + + Raises: + wandb.Error: If `data_table` is not a `wandb.Table` object. + + Example: + ```python + # Create a custom chart using a Vega-Lite spec and the data table. + import wandb + + data = [[1, 1], [2, 2], [3, 3], [4, 4], [5, 5]] + table = wandb.Table(data=data, columns=["x", "y"]) + fields = {"x": "x", "y": "y", "title": "MY TITLE"} + + with wandb.init() as run: + # Training code goes here + + # Create a custom title with `string_fields`. + my_custom_chart = wandb.plot_table( + vega_spec_name="wandb/line/v0", + data_table=table, + fields=fields, + string_fields={"title": "Title"}, + ) + + run.log({"custom_chart": my_custom_chart}) + ``` + """ + ... + +def watch( + models: torch.nn.Module | Sequence[torch.nn.Module], + criterion: torch.F | None = None, + log: Literal["gradients", "parameters", "all"] | None = "gradients", + log_freq: int = 1000, + idx: int | None = None, + log_graph: bool = False, +) -> None: + """Hook into given PyTorch model to monitor gradients and the model's computational graph. + + This function can track parameters, gradients, or both during training. + + Args: + models: A single model or a sequence of models to be monitored. + criterion: The loss function being optimized (optional). + log: Specifies whether to log "gradients", "parameters", or "all". + Set to None to disable logging. (default="gradients"). + log_freq: Frequency (in batches) to log gradients and parameters. (default=1000) + idx: Index used when tracking multiple models with `wandb.watch`. (default=None) + log_graph: Whether to log the model's computational graph. (default=False) + + Raises: + ValueError: + If `wandb.init()` has not been called or if any of the models are not instances + of `torch.nn.Module`. + """ + ... + +def unwatch( + models: torch.nn.Module | Sequence[torch.nn.Module] | None = None, +) -> None: + """Remove pytorch model topology, gradient and parameter hooks. + + Args: + models: Optional list of pytorch models that have had watch called on them. + """ + ... + +def restore( + name: str, + run_path: str | None = None, + replace: bool = False, + root: str | None = None, +) -> None | TextIO: + """Download the specified file from cloud storage. + + File is placed into the current directory or run directory. + By default, will only download the file if it doesn't already exist. + + Args: + name: The name of the file. + run_path: Optional path to a run to pull files from, i.e. `username/project_name/run_id` + if wandb.init has not been called, this is required. + replace: Whether to download the file even if it already exists locally + root: The directory to download the file to. Defaults to the current + directory or the run directory if wandb.init was called. + + Returns: + None if it can't find the file, otherwise a file object open for reading. + + Raises: + CommError: If W&B can't connect to the W&B backend. + ValueError: If the file is not found or can't find run_path. + """ + ... diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__main__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..e32b1ef386cb475c83b09fb527a9621a7370847a --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__main__.py @@ -0,0 +1,3 @@ +from wandb.cli import cli + +cli.cli(prog_name="python -m wandb") diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/_analytics.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/_analytics.py new file mode 100644 index 0000000000000000000000000000000000000000..33f04dffa7d7cb56831ddcaad28ebbe0c8a57476 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/_analytics.py @@ -0,0 +1,66 @@ +from __future__ import annotations + +from collections.abc import Callable +from contextvars import ContextVar +from dataclasses import dataclass, field +from functools import wraps +from typing import Final, TypeVar +from uuid import UUID, uuid4 + +from typing_extensions import ParamSpec + +from wandb._strutils import nameof + +P = ParamSpec("P") +R = TypeVar("R") + +# Header keys for tracking the calling function +X_WANDB_PYTHON_FUNC: Final[str] = "X-Wandb-Python-Func" +X_WANDB_PYTHON_CALL_ID: Final[str] = "X-Wandb-Python-Call-Id" + + +@dataclass(frozen=True) +class TrackedFuncInfo: + func: str + """The fully qualified namespace of the tracked function.""" + + call_id: UUID = field(default_factory=uuid4) + """A unique identifier assigned to each invocation.""" + + def to_headers(self) -> dict[str, str]: + return { + X_WANDB_PYTHON_FUNC: self.func, + X_WANDB_PYTHON_CALL_ID: str(self.call_id), + } + + +_current_func: ContextVar[TrackedFuncInfo] = ContextVar("_current_func") +"""An internal, threadsafe context variable to hold the current function being tracked.""" + + +def tracked(func: Callable[P, R]) -> Callable[P, R]: + """A decorator to inject the calling function name into any GraphQL request headers. + + If a tracked function calls another tracked function, only the outermost function in + the call stack will be tracked. + """ + func_namespace = f"{func.__module__}.{nameof(func)}" + + @wraps(func) + def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: + # Don't override the current tracked function if it's already set + if tracked_func(): + return func(*args, **kwargs) + + token = _current_func.set(TrackedFuncInfo(func=func_namespace)) + try: + return func(*args, **kwargs) + finally: + _current_func.reset(token) + + return wrapper + + +def tracked_func() -> TrackedFuncInfo | None: + """Returns info on the current tracked function, if any, otherwise None.""" + return _current_func.get(None) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/_iterutils.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/_iterutils.py new file mode 100644 index 0000000000000000000000000000000000000000..c55a863a46c8e80329a9ad89c96ab5f70083385a --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/_iterutils.py @@ -0,0 +1,73 @@ +from __future__ import annotations + +from collections.abc import Hashable, Iterable +from typing import TYPE_CHECKING, Any, TypeVar, overload + +if TYPE_CHECKING: + T = TypeVar("T") + HashableT = TypeVar("HashableT", bound=Hashable) + ClassInfo = type[T] | tuple[type[T], ...] + + +@overload +def always_list(obj: Iterable[T], base_type: ClassInfo = ...) -> list[T]: ... +@overload +def always_list(obj: T, base_type: ClassInfo = ...) -> list[T]: ... +def always_list(obj: Any, base_type: Any = (str, bytes)) -> list[T]: + """Return a guaranteed list of objects from one instance OR an iterable of such items. + + By default, assume the returned list should have string-like elements (`str`/`bytes`). + + Adapted from `more_itertools.always_iterable`, but simplified for internal use. See: + https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.always_iterable + """ + return [obj] if isinstance(obj, base_type) else list(obj) + + +def unique_list(iterable: Iterable[HashableT]) -> list[HashableT]: + """Return a deduplicated list of items from the given iterable, preserving order.""" + # Trick for O(1) uniqueness check that maintains order + return list(dict.fromkeys(iterable)) + + +def one( + iterable: Iterable[T], + too_short: type[Exception] | Exception | None = None, + too_long: type[Exception] | Exception | None = None, +) -> T: + """Return the only item in the iterable. + + Note: + This is intended **only** as an internal helper/convenience function, + and its implementation is directly adapted from `more_itertools.one`. + Users needing similar functionality are strongly encouraged to use + that library instead: + https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.one + + Args: + iterable: The iterable to get the only item from. + too_short: Custom exception to raise if the iterable has no items. + too_long: Custom exception to raise if the iterable has multiple items. + + Raises: + ValueError or `too_short`: If the iterable has no items. + ValueError or `too_long`: If the iterable has multiple items. + """ + # For a general iterable, avoid inadvertently iterating through all values, + # which may be costly or impossible (e.g. if infinite). Only check that: + + # ... the first item exists + it = iter(iterable) + try: + obj = next(it) + except StopIteration: + raise (too_short or ValueError("Expected 1 item in iterable, got 0")) from None + + # ...the second item doesn't + try: + _ = next(it) + except StopIteration: + return obj + raise ( + too_long or ValueError("Expected 1 item in iterable, got multiple") + ) from None diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/_strutils.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/_strutils.py new file mode 100644 index 0000000000000000000000000000000000000000..1137f9a24fddeb2b601d4ded9a55e66c017abd2c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/_strutils.py @@ -0,0 +1,39 @@ +from __future__ import annotations + +from base64 import b64decode, b64encode +from typing import Any + + +def ensureprefix(s: str, prefix: str) -> str: + """Ensures the string has the given prefix prepended.""" + return s if s.startswith(prefix) else f"{prefix}{s}" + + +def ensuresuffix(s: str, suffix: str) -> str: + """Ensures the string has the given suffix appended.""" + return s if s.endswith(suffix) else f"{s}{suffix}" + + +def nameof(obj: Any, full: bool = True) -> str: + """Internal convenience helper that returns the object's `__name__` or `__qualname__`. + + If `full` is True, attempt to return the object's `__qualname__` attribute, + falling back on the `__name__` attribute. + """ + return getattr(obj, "__qualname__", obj.__name__) if full else obj.__name__ + + +def b64decode_ascii(s: str) -> str: + """Returns the decoded base64 string interpreted as ASCII. + + Convenience function for directly converting `str -> str`. + """ + return b64decode(s).decode("ascii") + + +def b64encode_ascii(s: str) -> str: + """Returns the base64 encoding of the string's ASCII bytes. + + Convenience function for directly converting `str -> str`. + """ + return b64encode(s.encode("ascii")).decode("ascii") diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/data_types.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/data_types.py new file mode 100644 index 0000000000000000000000000000000000000000..3c89cbba5fdccd01280370224bc3ba59cb2f2f43 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/data_types.py @@ -0,0 +1,66 @@ +"""This module defines data types for logging rich, interactive visualizations to W&B. + +Data types include common media types, like images, audio, and videos, +flexible containers for information, like tables and HTML, and more. + +For more on logging media, see [our guide](https://docs.wandb.ai/models/track/log/media) + +For more on logging structured data for interactive dataset and model analysis, +see [our guide to W&B Tables](https://docs.wandb.ai/models/tables) + +All of these special data types are subclasses of WBValue. All the data types +serialize to JSON, since that is what wandb uses to save the objects locally +and upload them to the W&B server. +""" + +from .sdk.data_types.audio import Audio +from .sdk.data_types.base_types.media import BatchableMedia, Media +from .sdk.data_types.base_types.wb_value import WBValue +from .sdk.data_types.bokeh import Bokeh +from .sdk.data_types.graph import Graph, Node +from .sdk.data_types.helper_types.bounding_boxes_2d import BoundingBoxes2D +from .sdk.data_types.helper_types.classes import Classes +from .sdk.data_types.helper_types.image_mask import ImageMask +from .sdk.data_types.histogram import Histogram +from .sdk.data_types.html import Html +from .sdk.data_types.image import Image +from .sdk.data_types.molecule import Molecule +from .sdk.data_types.object_3d import Object3D, box3d +from .sdk.data_types.plotly import Plotly +from .sdk.data_types.saved_model import _SavedModel +from .sdk.data_types.table import JoinedTable, PartitionedTable, Table +from .sdk.data_types.trace_tree import WBTraceTree +from .sdk.data_types.video import Video + +# Note: we are importing everything from the sdk/data_types to maintain a namespace for now. +# Once we fully type this file and move it all into sdk, then we will need to clean up the +# other internal imports + +__all__ = [ + # Untyped Exports + "Audio", + "Table", + "JoinedTable", + "PartitionedTable", + "Bokeh", + "Node", + "Graph", + # Typed Exports + "Histogram", + "Html", + "Image", + "Molecule", + "box3d", + "Object3D", + "Plotly", + "Video", + "WBTraceTree", + "_SavedModel", + "WBValue", + "Media", + "BatchableMedia", + # Typed Legacy Exports (I'd like to remove these) + "ImageMask", + "BoundingBoxes2D", + "Classes", +] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/env.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/env.py new file mode 100644 index 0000000000000000000000000000000000000000..5be9b6f118127239f04edc08c93ea36c41e5890a --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/env.py @@ -0,0 +1,535 @@ +"""All of W&B's environment variables. + +Getters and putters for all of them should go here. That way it'll be easier to +avoid typos with names and be consistent about environment variables' semantics. + +Environment variables are not the authoritative source for these values in many +cases. +""" + +from __future__ import annotations + +import json +import os +import sys +from collections.abc import MutableMapping +from pathlib import Path + +import platformdirs + +CONFIG_PATHS = "WANDB_CONFIG_PATHS" +SWEEP_PARAM_PATH = "WANDB_SWEEP_PARAM_PATH" +SHOW_RUN = "WANDB_SHOW_RUN" +DEBUG = "WANDB_DEBUG" +SILENT = "WANDB_SILENT" +QUIET = "WANDB_QUIET" +INITED = "WANDB_INITED" +DIR = "WANDB_DIR" +# Deprecate DESCRIPTION in a future release +DESCRIPTION = "WANDB_DESCRIPTION" +NAME = "WANDB_NAME" +NOTEBOOK_NAME = "WANDB_NOTEBOOK_NAME" +NOTES = "WANDB_NOTES" +USERNAME = "WANDB_USERNAME" +USER_EMAIL = "WANDB_USER_EMAIL" +PROJECT = "WANDB_PROJECT" +ENTITY = "WANDB_ENTITY" +ORGANIZATION = "WANDB_ORGANIZATION" +BASE_URL = "WANDB_BASE_URL" +APP_URL = "WANDB_APP_URL" +PROGRAM = "WANDB_PROGRAM" +ARGS = "WANDB_ARGS" +MODE = "WANDB_MODE" +START_METHOD = "WANDB_START_METHOD" +RESUME = "WANDB_RESUME" +RUN_ID = "WANDB_RUN_ID" +RUN_STORAGE_ID = "WANDB_RUN_STORAGE_ID" +RUN_GROUP = "WANDB_RUN_GROUP" +RUN_DIR = "WANDB_RUN_DIR" +SWEEP_ID = "WANDB_SWEEP_ID" +HTTP_TIMEOUT = "WANDB_HTTP_TIMEOUT" +FILE_PUSHER_TIMEOUT = "WANDB_FILE_PUSHER_TIMEOUT" +API_KEY = "WANDB_API_KEY" +IDENTITY_TOKEN_FILE = "WANDB_IDENTITY_TOKEN_FILE" +CREDENTIALS_FILE = "WANDB_CREDENTIALS_FILE" +JOB_TYPE = "WANDB_JOB_TYPE" +DISABLE_CODE = "WANDB_DISABLE_CODE" +DISABLE_GIT = "WANDB_DISABLE_GIT" +GIT_ROOT = "WANDB_GIT_ROOT" +SAVE_CODE = "WANDB_SAVE_CODE" +TAGS = "WANDB_TAGS" +IGNORE = "WANDB_IGNORE_GLOBS" +ERROR_REPORTING = "WANDB_ERROR_REPORTING" +CORE_DEBUG = "WANDB_CORE_DEBUG" +DOCKER = "WANDB_DOCKER" +AGENT_REPORT_INTERVAL = "WANDB_AGENT_REPORT_INTERVAL" +AGENT_KILL_DELAY = "WANDB_AGENT_KILL_DELAY" +AGENT_DISABLE_FLAPPING = "WANDB_AGENT_DISABLE_FLAPPING" +AGENT_MAX_INITIAL_FAILURES = "WANDB_AGENT_MAX_INITIAL_FAILURES" +CRASH_NOSYNC_TIME = "WANDB_CRASH_NOSYNC_TIME" +MAGIC = "WANDB_MAGIC" +HOST = "WANDB_HOST" +ANONYMOUS = "WANDB_ANONYMOUS" +JUPYTER = "WANDB_JUPYTER" +CONFIG_DIR = "WANDB_CONFIG_DIR" +DATA_DIR = "WANDB_DATA_DIR" +ARTIFACT_DIR = "WANDB_ARTIFACT_DIR" +ARTIFACT_FETCH_FILE_URL_BATCH_SIZE = "WANDB_ARTIFACT_FETCH_FILE_URL_BATCH_SIZE" +CACHE_DIR = "WANDB_CACHE_DIR" +DISABLE_SSL = "WANDB_INSECURE_DISABLE_SSL" +SERVICE = "WANDB_SERVICE" +SENTRY_DSN = "WANDB_SENTRY_DSN" +INIT_TIMEOUT = "WANDB_INIT_TIMEOUT" +GIT_COMMIT = "WANDB_GIT_COMMIT" +GIT_REMOTE_URL = "WANDB_GIT_REMOTE_URL" +_EXECUTABLE = "WANDB_X_EXECUTABLE" +LAUNCH_QUEUE_NAME = "WANDB_LAUNCH_QUEUE_NAME" +LAUNCH_QUEUE_ENTITY = "WANDB_LAUNCH_QUEUE_ENTITY" +LAUNCH_TRACE_ID = "WANDB_LAUNCH_TRACE_ID" +ENABLE_DCGM_PROFILING = "WANDB_ENABLE_DCGM_PROFILING" + +# For testing, to be removed in future version +USE_V1_ARTIFACTS = "_WANDB_USE_V1_ARTIFACTS" + + +def immutable_keys() -> list[str]: + """These are env keys that shouldn't change within a single process. + + We use this to maintain certain values between multiple calls to wandb.init within a single process. + """ + return [ + DIR, + ENTITY, + PROJECT, + API_KEY, + IGNORE, + DISABLE_CODE, + DISABLE_GIT, + DOCKER, + MODE, + BASE_URL, + ERROR_REPORTING, + CRASH_NOSYNC_TIME, + MAGIC, + USERNAME, + USER_EMAIL, + DIR, + SILENT, + CONFIG_PATHS, + ANONYMOUS, + RUN_GROUP, + JOB_TYPE, + TAGS, + RESUME, + AGENT_REPORT_INTERVAL, + HTTP_TIMEOUT, + HOST, + DATA_DIR, + ARTIFACT_DIR, + ARTIFACT_FETCH_FILE_URL_BATCH_SIZE, + CACHE_DIR, + USE_V1_ARTIFACTS, + DISABLE_SSL, + IDENTITY_TOKEN_FILE, + CREDENTIALS_FILE, + ] + + +def _env_as_bool( + var: str, default: str | None = None, env: MutableMapping | None = None +) -> bool: + if env is None: + env = os.environ + val = env.get(var, default) + if not isinstance(val, str): + return False + try: + return strtobool(val) + except ValueError: + return False + + +def is_debug(default: str | None = None, env: MutableMapping | None = None) -> bool: + return _env_as_bool(DEBUG, default=default, env=env) + + +def is_offline(env: MutableMapping | None = None) -> bool: + if env is None: + env = os.environ + return env.get(MODE) == "offline" + + +def is_quiet() -> bool: + return _env_as_bool(QUIET, default="false") + + +def is_silent() -> bool: + return _env_as_bool(SILENT, default="false") + + +def error_reporting_enabled() -> bool: + return _env_as_bool(ERROR_REPORTING, default="True") + + +def core_debug(default: str | None = None) -> bool: + return _env_as_bool(CORE_DEBUG, default=default) or is_debug() + + +def ssl_disabled() -> bool: + return _env_as_bool(DISABLE_SSL, default="False") + + +def dcgm_profiling_enabled() -> bool: + """Checks whether collecting profiling metrics for Nvidia GPUs using DCGM is requested. + + Note: Enabling this feature can lead to increased resource usage + compared to standard monitoring. + Requires the `nvidia-dcgm` service to be running on the machine. + """ + return _env_as_bool(ENABLE_DCGM_PROFILING, default="False") + + +def get_error_reporting( + default: bool | str = True, + env: MutableMapping | None = None, +) -> bool | str: + if env is None: + env = os.environ + + return env.get(ERROR_REPORTING, default) + + +def get_run( + default: str | None = None, env: MutableMapping | None = None +) -> str | None: + if env is None: + env = os.environ + + return env.get(RUN_ID, default) + + +def get_args( + default: list[str] | None = None, env: MutableMapping | None = None +) -> list[str] | None: + if env is None: + env = os.environ + if env.get(ARGS): + try: + return json.loads(env.get(ARGS, "[]")) # type: ignore + except ValueError: + return None + else: + return default or sys.argv[1:] + + +def get_docker( + default: str | None = None, env: MutableMapping | None = None +) -> str | None: + if env is None: + env = os.environ + + return env.get(DOCKER, default) + + +def get_http_timeout(default: int = 20, env: MutableMapping | None = None) -> int: + if env is None: + env = os.environ + + return int(env.get(HTTP_TIMEOUT, default)) + + +def get_file_pusher_timeout( + default: int | None = None, + env: MutableMapping | None = None, +) -> int | None: + if env is None: + env = os.environ + + timeout = env.get(FILE_PUSHER_TIMEOUT, default) + return int(timeout) if timeout else None + + +def get_ignore( + default: list[str] | None = None, env: MutableMapping | None = None +) -> list[str] | None: + if env is None: + env = os.environ + ignore = env.get(IGNORE) + if ignore is not None: + return ignore.split(",") + else: + return default + + +def get_project( + default: str | None = None, env: MutableMapping | None = None +) -> str | None: + if env is None: + env = os.environ + + return env.get(PROJECT, default) + + +def get_username( + default: str | None = None, env: MutableMapping | None = None +) -> str | None: + if env is None: + env = os.environ + + return env.get(USERNAME, default) + + +def get_user_email( + default: str | None = None, env: MutableMapping | None = None +) -> str | None: + if env is None: + env = os.environ + + return env.get(USER_EMAIL, default) + + +def get_entity( + default: str | None = None, env: MutableMapping | None = None +) -> str | None: + if env is None: + env = os.environ + + return env.get(ENTITY, default) + + +def get_organization( + default: str | None = None, env: MutableMapping | None = None +) -> str | None: + if env is None: + env = os.environ + + return env.get(ORGANIZATION, default) + + +def get_base_url( + default: str | None = None, env: MutableMapping | None = None +) -> str | None: + if env is None: + env = os.environ + + return env.get(BASE_URL, default) + + +def get_app_url( + default: str | None = None, env: MutableMapping | None = None +) -> str | None: + if env is None: + env = os.environ + + return env.get(APP_URL, default) + + +def get_show_run(default: str | None = None, env: MutableMapping | None = None) -> bool: + if env is None: + env = os.environ + + return bool(env.get(SHOW_RUN, default)) + + +def get_description( + default: str | None = None, env: MutableMapping | None = None +) -> str | None: + if env is None: + env = os.environ + + return env.get(DESCRIPTION, default) + + +def get_tags(default: str = "", env: MutableMapping | None = None) -> list[str]: + if env is None: + env = os.environ + + return [tag for tag in env.get(TAGS, default).split(",") if tag] + + +def get_dir( + default: str | None = None, env: MutableMapping | None = None +) -> str | None: + if env is None: + env = os.environ + return env.get(DIR, default) + + +def get_config_paths( + default: str | None = None, env: MutableMapping | None = None +) -> str | None: + if env is None: + env = os.environ + return env.get(CONFIG_PATHS, default) + + +def get_agent_report_interval( + default: str | None = None, env: MutableMapping | None = None +) -> int | None: + if env is None: + env = os.environ + val = env.get(AGENT_REPORT_INTERVAL, default) + try: + val = int(val) # type: ignore + except ValueError: + val = None # silently ignore env format errors, caller should handle. + return val + + +def get_agent_kill_delay( + default: str | None = None, env: MutableMapping | None = None +) -> int | None: + if env is None: + env = os.environ + val = env.get(AGENT_KILL_DELAY, default) + try: + val = int(val) # type: ignore + except ValueError: + val = None # silently ignore env format errors, caller should handle. + return val + + +def get_crash_nosync_time( + default: str | None = None, env: MutableMapping | None = None +) -> int | None: + if env is None: + env = os.environ + val = env.get(CRASH_NOSYNC_TIME, default) + try: + val = int(val) # type: ignore + except ValueError: + val = None # silently ignore env format errors, caller should handle. + return val + + +def get_magic( + default: str | None = None, env: MutableMapping | None = None +) -> str | None: + if env is None: + env = os.environ + val = env.get(MAGIC, default) + return val + + +def get_data_dir(env: MutableMapping | None = None) -> str: + default_dir = platformdirs.user_data_dir("wandb") + if env is None: + env = os.environ + val = env.get(DATA_DIR, default_dir) + return val + + +def get_artifact_dir(env: MutableMapping | None = None) -> str: + default_dir = os.path.join(".", "artifacts") + if env is None: + env = os.environ + val = env.get(ARTIFACT_DIR, default_dir) + return os.path.abspath(str(val)) + + +def get_artifact_fetch_file_url_batch_size(env: MutableMapping | None = None) -> int: + default_batch_size = 5000 + if env is None: + env = os.environ + val = int(env.get(ARTIFACT_FETCH_FILE_URL_BATCH_SIZE, default_batch_size)) + return val + + +def get_cache_dir(env: MutableMapping | None = None) -> Path: + env = env or os.environ + return Path(env.get(CACHE_DIR, platformdirs.user_cache_dir("wandb"))) + + +def get_use_v1_artifacts(env: MutableMapping | None = None) -> bool: + if env is None: + env = os.environ + val = bool(env.get(USE_V1_ARTIFACTS, False)) + return val + + +def get_agent_max_initial_failures( + default: int | None = None, env: MutableMapping | None = None +) -> int | None: + if env is None: + env = os.environ + val = env.get(AGENT_MAX_INITIAL_FAILURES, default) + try: + val = int(val) # type: ignore + except ValueError: + val = default + return val + + +def set_entity(value: str, env: MutableMapping | None = None) -> None: + if env is None: + env = os.environ + env[ENTITY] = value + + +def set_project(value: str, env: MutableMapping | None = None) -> None: + if env is None: + env = os.environ + env[PROJECT] = value or "uncategorized" + + +def should_save_code() -> bool: + save_code = _env_as_bool(SAVE_CODE, default="False") + code_disabled = _env_as_bool(DISABLE_CODE, default="False") + return save_code and not code_disabled + + +def disable_git(env: MutableMapping | None = None) -> bool: + if env is None: + env = os.environ + val = env.get(DISABLE_GIT, "False") + if isinstance(val, str): + val = val.lower() != "false" + return val + + +def get_launch_queue_name(env: MutableMapping | None = None) -> str | None: + if env is None: + env = os.environ + val = env.get(LAUNCH_QUEUE_NAME, None) + return val + + +def get_launch_queue_entity(env: MutableMapping | None = None) -> str | None: + if env is None: + env = os.environ + val = env.get(LAUNCH_QUEUE_ENTITY, None) + return val + + +def get_launch_trace_id(env: MutableMapping | None = None) -> str | None: + if env is None: + env = os.environ + val = env.get(LAUNCH_TRACE_ID, None) + return val + + +def get_credentials_file(default: str, env: MutableMapping | None = None) -> Path: + """Retrieve the path for the credentials file used to save access tokens. + + The credentials file path can be set via an environment variable, otherwise + the default path is used. + """ + if env is None: + env = os.environ + credentials_file = env.get(CREDENTIALS_FILE, default) + return Path(credentials_file) + + +def strtobool(val: str) -> bool: + """Convert a string representation of truth to true or false. + + Copied from distutils. distutils was removed in Python 3.12. + """ + val = val.lower() + + if val in ("y", "yes", "t", "true", "on", "1"): + return True + elif val in ("n", "no", "f", "false", "off", "0"): + return False + else: + raise ValueError(f"invalid truth value {val!r}") diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/jupyter.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/jupyter.py new file mode 100644 index 0000000000000000000000000000000000000000..efac8556b6236d1973b428eb0daeda993c5a80c9 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/jupyter.py @@ -0,0 +1,505 @@ +from __future__ import annotations + +import json +import logging +import os +import re +import shutil +import sys +import traceback +from base64 import b64encode +from typing import Any + +import IPython +import IPython.display +import requests +from IPython.core.magic import Magics, line_cell_magic, magics_class +from IPython.core.magic_arguments import argument, magic_arguments, parse_argstring +from requests.compat import urljoin + +import wandb +import wandb.util +from wandb.sdk import wandb_setup +from wandb.sdk.lib import filesystem + +logger = logging.getLogger(__name__) + + +def display_if_magic_is_used(run: wandb.Run) -> bool: + """Display a run's page if the cell has the %%wandb cell magic. + + Args: + run: The run to display. + + Returns: + Whether the %%wandb cell magic was present. + """ + if not _current_cell_wandb_magic: + return False + + _current_cell_wandb_magic.display_if_allowed(run) + return True + + +class _WandbCellMagicState: + """State for a cell with the %%wandb cell magic.""" + + def __init__(self, *, height: int) -> None: + """Initializes the %%wandb cell magic state. + + Args: + height: The desired height for displayed iframes. + """ + self._height = height + self._already_displayed = False + + def display_if_allowed(self, run: wandb.Run) -> None: + """Display a run's iframe if one is not already displayed. + + Args: + run: The run to display. + """ + if self._already_displayed: + return + self._already_displayed = True + + _display_wandb_run(run, height=self._height) + + +_current_cell_wandb_magic: _WandbCellMagicState | None = None + + +def _display_by_wandb_path(path: str, *, height: int) -> None: + """Display a wandb object (usually in an iframe) given its URI. + + Args: + path: A path to a run, sweep, project, report, etc. + height: Height of the iframe in pixels. + """ + api = wandb.Api() + + try: + obj = api.from_path(path) + + IPython.display.display_html( + obj.to_html(height=height), + raw=True, + ) + except wandb.Error: + traceback.print_exc() + IPython.display.display_html( + f"Path {path!r} does not refer to a W&B object you can access.", + raw=True, + ) + + +def _display_wandb_run(run: wandb.Run, *, height: int) -> None: + """Display a run (usually in an iframe). + + Args: + run: The run to display. + height: Height of the iframe in pixels. + """ + IPython.display.display_html( + run.to_html(height=height), + raw=True, + ) + + +@magics_class +class WandBMagics(Magics): + def __init__(self, shell): + super().__init__(shell) + + @magic_arguments() + @argument( + "path", + default=None, + nargs="?", + help="The path to a resource you want to display.", + ) + @argument( + "-h", + "--height", + default=420, + type=int, + help="The height of the iframe in pixels.", + ) + @line_cell_magic + def wandb(self, line: str, cell: str | None = None) -> None: + """Display wandb resources in Jupyter. + + This can be used as a line magic: + + %wandb USERNAME/PROJECT/runs/RUN_ID + + Or as a cell magic: + + %%wandb -h 1024 + with wandb.init() as run: + run.log({"loss": 1}) + """ + global _current_cell_wandb_magic + + args = parse_argstring(self.wandb, line) + path: str | None = args.path + height: int = args.height + + if path: + _display_by_wandb_path(path, height=height) + displayed = True + elif run := wandb_setup.singleton().most_recent_active_run: + _display_wandb_run(run, height=height) + displayed = True + else: + displayed = False + + # If this is being used as a line magic ("%wandb"), we are done. + # When used as a cell magic ("%%wandb"), we must run the cell. + if cell is None: + return + + if not displayed: + _current_cell_wandb_magic = _WandbCellMagicState(height=height) + + try: + IPython.get_ipython().run_cell(cell) + finally: + _current_cell_wandb_magic = None + + +def notebook_metadata_from_jupyter_servers_and_kernel_id(): + # When running in VS Code's notebook extension, + # the extension creates a temporary file to start the kernel. + # This file is not actually the same as the notebook file. + # + # The real notebook path is stored in the user namespace + # under the key "__vsc_ipynb_file__" + try: + from IPython import get_ipython + + ipython = get_ipython() + if ipython is not None: + notebook_path = ipython.kernel.shell.user_ns.get("__vsc_ipynb_file__") + if notebook_path: + return { + "root": os.path.dirname(notebook_path), + "path": notebook_path, + "name": os.path.basename(notebook_path), + } + except ModuleNotFoundError: + return None + + servers, kernel_id = jupyter_servers_and_kernel_id() + for s in servers: + if s.get("password"): + raise ValueError("Can't query password protected kernel") + res = requests.get( + urljoin(s["url"], "api/sessions"), params={"token": s.get("token", "")} + ).json() + for nn in res: + if ( + isinstance(nn, dict) + and nn.get("kernel") + and "notebook" in nn + and nn["kernel"]["id"] == kernel_id + ): + return { + "root": s.get("root_dir", s.get("notebook_dir", os.getcwd())), + "path": nn["notebook"]["path"], + "name": nn["notebook"]["name"], + } + + if not kernel_id: + return None + + +def notebook_metadata(silent: bool) -> dict[str, str]: + """Attempt to query jupyter for the path and name of the notebook file. + + This can handle different jupyter environments, specifically: + + 1. Colab + 2. Kaggle + 3. JupyterLab + 4. Notebooks + 5. Other? + """ + error_message = ( + "Failed to detect the name of this notebook. You can set it manually" + " with the WANDB_NOTEBOOK_NAME environment variable to enable code" + " saving." + ) + try: + jupyter_metadata = notebook_metadata_from_jupyter_servers_and_kernel_id() + + # Colab: + # request the most recent contents + ipynb = attempt_colab_load_ipynb() + if ipynb is not None and jupyter_metadata is not None: + return { + "root": "/content", + "path": jupyter_metadata["path"], + "name": jupyter_metadata["name"], + } + + # Kaggle: + if wandb.util._is_kaggle(): + # request the most recent contents + ipynb = attempt_kaggle_load_ipynb() + if ipynb: + return { + "root": "/kaggle/working", + "path": ipynb["metadata"]["name"], + "name": ipynb["metadata"]["name"], + } + + if jupyter_metadata: + return jupyter_metadata + except Exception: + logger.exception(error_message) + + wandb.termerror(error_message) + return {} + + +def jupyter_servers_and_kernel_id(): + """Return a list of servers and the current kernel_id. + + Used to query for the name of the notebook. + """ + try: + import ipykernel # type: ignore + + kernel_id = re.search( + "kernel-(.*).json", ipykernel.connect.get_connection_file() + ).group(1) + # We're either in jupyterlab or a notebook, lets prefer the newer jupyter_server package + serverapp = wandb.util.get_module("jupyter_server.serverapp") + notebookapp = wandb.util.get_module("notebook.notebookapp") + servers = [] + if serverapp is not None: + servers.extend(list(serverapp.list_running_servers())) + if notebookapp is not None: + servers.extend(list(notebookapp.list_running_servers())) + except (AttributeError, ValueError, ImportError): + return [], None + + return servers, kernel_id + + +def attempt_colab_load_ipynb(): + colab = wandb.util.get_module("google.colab") + if colab: + # This isn't thread safe, never call in a thread + response = colab._message.blocking_request("get_ipynb", timeout_sec=5) + if response: + return response["ipynb"] + + +def attempt_kaggle_load_ipynb(): + kaggle = wandb.util.get_module("kaggle_session") + if not kaggle: + return None + + try: + client = kaggle.UserSessionClient() + parsed = json.loads(client.get_exportable_ipynb()["source"]) + # TODO: couldn't find a way to get the name of the notebook... + parsed["metadata"]["name"] = "kaggle.ipynb" + except Exception: + wandb.termerror("Unable to load kaggle notebook.") + logger.exception("Unable to load kaggle notebook.") + return None + + return parsed + + +class Notebook: + def __init__(self, settings: wandb.Settings) -> None: + self.outputs: dict[int, Any] = {} + self.settings = settings + self.shell = IPython.get_ipython() + + def save_display(self, exc_count, data_with_metadata): + self.outputs[exc_count] = self.outputs.get(exc_count, []) + + # byte values such as images need to be encoded in base64 + # otherwise nbformat.v4.new_output will throw a NotebookValidationError + data = data_with_metadata["data"] + b64_data = {} + for key in data: + val = data[key] + if isinstance(val, bytes): + b64_data[key] = b64encode(val).decode("utf-8") + else: + b64_data[key] = val + + self.outputs[exc_count].append( + {"data": b64_data, "metadata": data_with_metadata["metadata"]} + ) + + def probe_ipynb(self): + """Return notebook as dict or None.""" + relpath = self.settings.x_jupyter_path + if relpath and os.path.exists(relpath): + with open(relpath) as json_file: + data = json.load(json_file) + return data + + colab_ipynb = attempt_colab_load_ipynb() + if colab_ipynb: + return colab_ipynb + + kaggle_ipynb = attempt_kaggle_load_ipynb() + if kaggle_ipynb and len(kaggle_ipynb["cells"]) > 0: + return kaggle_ipynb + + return + + def save_ipynb(self) -> bool: + if not self.settings.save_code: + logger.info("not saving jupyter notebook") + return False + ret = False + try: + ret = self._save_ipynb() + except Exception: + wandb.termerror("Failed to save notebook.") + logger.exception("Problem saving notebook.") + return ret + + def _save_ipynb(self) -> bool: + relpath = self.settings.x_jupyter_path + logger.info("looking for notebook: %s", relpath) + if relpath and os.path.exists(relpath): + shutil.copy( + relpath, + os.path.join(self.settings._tmp_code_dir, os.path.basename(relpath)), + ) + return True + + # TODO: likely only save if the code has changed + colab_ipynb = attempt_colab_load_ipynb() + if colab_ipynb: + try: + jupyter_metadata = ( + notebook_metadata_from_jupyter_servers_and_kernel_id() + ) + nb_name = jupyter_metadata["name"] + except Exception: + nb_name = "colab.ipynb" + if not nb_name.endswith(".ipynb"): + nb_name += ".ipynb" + with open( + os.path.join( + self.settings._tmp_code_dir, + nb_name, + ), + "w", + encoding="utf-8", + ) as f: + f.write(json.dumps(colab_ipynb)) + return True + + kaggle_ipynb = attempt_kaggle_load_ipynb() + if kaggle_ipynb and len(kaggle_ipynb["cells"]) > 0: + with open( + os.path.join( + self.settings._tmp_code_dir, kaggle_ipynb["metadata"]["name"] + ), + "w", + encoding="utf-8", + ) as f: + f.write(json.dumps(kaggle_ipynb)) + return True + + return False + + def save_history(self, run: wandb.Run): + """This saves all cell executions in the current session as a new notebook.""" + try: + from nbformat import v4, validator, write # type: ignore + except ImportError: + wandb.termerror( + "The nbformat package was not found." + " It is required to save notebook history." + ) + return + # TODO: some tests didn't patch ipython properly? + if self.shell is None: + return + cells = [] + hist = list(self.shell.history_manager.get_range(output=True)) + if len(hist) <= 1 or not self.settings.save_code: + logger.info("not saving jupyter history") + return + try: + for _, execution_count, exc in hist: + if exc[1]: + # TODO: capture stderr? + outputs = [ + v4.new_output(output_type="stream", name="stdout", text=exc[1]) + ] + else: + outputs = [] + if self.outputs.get(execution_count): + for out in self.outputs[execution_count]: + outputs.append( + v4.new_output( + output_type="display_data", + data=out["data"], + metadata=out["metadata"] or {}, + ) + ) + cells.append( + v4.new_code_cell( + execution_count=execution_count, source=exc[0], outputs=outputs + ) + ) + if hasattr(self.shell, "kernel"): + language_info = self.shell.kernel.language_info + else: + language_info = {"name": "python", "version": sys.version} + logger.info("saving %i cells to _session_history.ipynb", len(cells)) + nb = v4.new_notebook( + cells=cells, + metadata={ + "kernelspec": { + "display_name": f"Python {sys.version_info[0]}", + "name": f"python{sys.version_info[0]}", + "language": "python", + }, + "language_info": language_info, + }, + ) + state_path = os.path.join("code", "_session_history.ipynb") + run._set_config_wandb("session_history", state_path) + filesystem.mkdir_exists_ok(os.path.join(self.settings.files_dir, "code")) + with open( + os.path.join(self.settings._tmp_code_dir, "_session_history.ipynb"), + "w", + encoding="utf-8", + ) as f: + write(nb, f, version=4) + with open( + os.path.join(self.settings.files_dir, state_path), + "w", + encoding="utf-8", + ) as f: + write(nb, f, version=4) + except (OSError, validator.NotebookValidationError): + wandb.termerror("Unable to save notebook session history.") + logger.exception("Unable to save notebook session history.") + + +def _load_ipython_extension(ipython): + """Best-effort auto-registration of W&B magics in notebook contexts.""" + if ipython is None: + return + + try: + ipython.register_magics(WandBMagics) + except Exception: + logger.debug("Failed to register IPython magics.", exc_info=True) + return diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/py.typed b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sklearn.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sklearn.py new file mode 100644 index 0000000000000000000000000000000000000000..5c72b8228b5cb342ba2a217104ee5ce9267a2d2f --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sklearn.py @@ -0,0 +1,35 @@ +from wandb.integration.sklearn import ( + plot_calibration_curve, + plot_class_proportions, + plot_classifier, + plot_clusterer, + plot_confusion_matrix, + plot_elbow_curve, + plot_feature_importances, + plot_learning_curve, + plot_outlier_candidates, + plot_precision_recall, + plot_regressor, + plot_residuals, + plot_roc, + plot_silhouette, + plot_summary_metrics, +) + +__all__ = ( + "plot_classifier", + "plot_clusterer", + "plot_regressor", + "plot_summary_metrics", + "plot_learning_curve", + "plot_feature_importances", + "plot_class_proportions", + "plot_calibration_curve", + "plot_roc", + "plot_precision_recall", + "plot_confusion_matrix", + "plot_elbow_curve", + "plot_silhouette", + "plot_residuals", + "plot_outlier_candidates", +) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/trigger.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/trigger.py new file mode 100644 index 0000000000000000000000000000000000000000..2e42b30d2a3aeb560287818baac98e499f620bbb --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/trigger.py @@ -0,0 +1,30 @@ +"""Module to facilitate adding hooks to wandb actions. + +Usage: + import trigger + trigger.register('on_something', func) + trigger.call('on_something', *args, **kwargs) + trigger.unregister('on_something', func) +""" + +from collections.abc import Callable +from typing import Any + +_triggers = {} + + +def reset(): + _triggers.clear() + + +def register(event: str, func: Callable): + _triggers.setdefault(event, []).append(func) + + +def call(event_str: str, *args: Any, **kwargs: Any): + for func in _triggers.get(event_str, []): + func(*args, **kwargs) + + +def unregister(event: str, func: Callable): + _triggers[event].remove(func) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/util.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/util.py new file mode 100644 index 0000000000000000000000000000000000000000..1f5ee65076f52f577d4d2e1f1510fc59bb65a87c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/util.py @@ -0,0 +1,2041 @@ +from __future__ import annotations + +import colorsys +import contextlib +import dataclasses +import enum +import importlib +import importlib.util +import itertools +import json +import logging +import math +import numbers +import os +import pathlib +import platform +import queue +import random +import re +import secrets +import shlex +import socket +import string +import sys +import tarfile +import tempfile +import threading +import time +import types +import urllib +from collections.abc import Callable, Iterable, Mapping, Sequence +from dataclasses import asdict, is_dataclass +from datetime import date, datetime, timedelta +from gzip import GzipFile +from importlib import import_module +from sys import getsizeof +from types import ModuleType +from typing import IO, TYPE_CHECKING, TextIO, TypeGuard + +from typing_extensions import Any, Generator, TypeVar, deprecated + +import wandb +import wandb.env +from wandb.errors import ( + AuthenticationError, + CommError, + UsageError, + WandbCoreNotAvailableError, +) +from wandb.errors.term import terminput +from wandb.sdk.lib import filesystem, runid +from wandb.sdk.lib.json_util import dump, dumps +from wandb.sdk.lib.paths import FilePathStr, StrPath + +if TYPE_CHECKING: + from requests import Response + + from wandb.sdk.artifacts.artifact import Artifact + +CheckRetryFnType = Callable[[Exception], bool | timedelta] +T = TypeVar("T") + + +logger = logging.getLogger(__name__) +_not_importable: set[str] = set() + +LAUNCH_JOB_ARTIFACT_SLOT_NAME = "_wandb_job" + +MAX_LINE_BYTES = (10 << 20) - (100 << 10) # imposed by back end +IS_GIT = os.path.exists(os.path.join(os.path.dirname(__file__), "..", ".git")) + +# From https://docs.docker.com/engine/reference/commandline/tag/ +# "Name components may contain lowercase letters, digits and separators. +# A separator is defined as a period, one or two underscores, or one or more dashes. +# A name component may not start or end with a separator." +DOCKER_IMAGE_NAME_SEPARATOR = "(?:__|[._]|[-]+)" +RE_DOCKER_IMAGE_NAME_SEPARATOR_START = re.compile("^" + DOCKER_IMAGE_NAME_SEPARATOR) +RE_DOCKER_IMAGE_NAME_SEPARATOR_END = re.compile(DOCKER_IMAGE_NAME_SEPARATOR + "$") +RE_DOCKER_IMAGE_NAME_SEPARATOR_REPEAT = re.compile(DOCKER_IMAGE_NAME_SEPARATOR + "{2,}") +RE_DOCKER_IMAGE_NAME_CHARS = re.compile(r"[^a-z0-9._\-]") + + +POW_10_BYTES = [ + ("B", 10**0), + ("KB", 10**3), + ("MB", 10**6), + ("GB", 10**9), + ("TB", 10**12), + ("PB", 10**15), + ("EB", 10**18), +] + +POW_2_BYTES = [ + ("B", 2**0), + ("KiB", 2**10), + ("MiB", 2**20), + ("GiB", 2**30), + ("TiB", 2**40), + ("PiB", 2**50), + ("EiB", 2**60), +] + + +def vendor_setup() -> Callable: + """Create a function that restores user paths after vendor imports. + + This enables us to use the vendor directory for packages we don't depend on. Call + the returned function after imports are complete. If you don't you may modify the + user's path which is never good. + + Usage: + + ```python + reset_path = vendor_setup() + # do any vendor imports... + reset_path() + ``` + """ + original_path = [directory for directory in sys.path] + + def reset_import_path() -> None: + sys.path = original_path + + parent_dir = os.path.abspath(os.path.dirname(__file__)) + vendor_dir = os.path.join(parent_dir, "vendor") + vendor_packages = ( + "gql-0.2.0", + "graphql-core-1.1", + "watchdog_0_9_0", + "promise-2.3.0", + ) + package_dirs = [os.path.join(vendor_dir, p) for p in vendor_packages] + for p in [vendor_dir] + package_dirs: + if p not in sys.path: + sys.path.insert(1, p) + + return reset_import_path + + +def vendor_import(name: str) -> Any: + reset_path = vendor_setup() + module = import_module(name) + reset_path() + return module + + +class LazyModuleState: + def __init__(self, module: types.ModuleType) -> None: + self.module = module + self.load_started = False + self.lock = threading.RLock() + + def load(self) -> None: + with self.lock: + if self.load_started: + return + self.load_started = True + assert self.module.__spec__ is not None + assert self.module.__spec__.loader is not None + self.module.__spec__.loader.exec_module(self.module) + self.module.__class__ = types.ModuleType + + # Set the submodule as an attribute on the parent module + # This enables access to the submodule via normal attribute access. + parent, _, child = self.module.__name__.rpartition(".") + if parent: + parent_module = sys.modules[parent] + setattr(parent_module, child, self.module) + + +class LazyModule(types.ModuleType): + def __getattribute__(self, name: str) -> Any: + state = object.__getattribute__(self, "__lazy_module_state__") + state.load() + return object.__getattribute__(self, name) + + def __setattr__(self, name: str, value: Any) -> None: + state = object.__getattribute__(self, "__lazy_module_state__") + state.load() + object.__setattr__(self, name, value) + + def __delattr__(self, name: str) -> None: + state = object.__getattribute__(self, "__lazy_module_state__") + state.load() + object.__delattr__(self, name) + + +def import_module_lazy(name: str) -> types.ModuleType: + """Import a module lazily, only when it is used. + + Inspired by importlib.util.LazyLoader, but improved so that the module loading is + thread-safe. Circular dependency between modules can lead to a deadlock if the two + modules are loaded from different threads. + + :param (str) name: Dot-separated module path. E.g., 'scipy.stats'. + """ + try: + return sys.modules[name] + except KeyError: + spec = importlib.util.find_spec(name) + if spec is None: + raise ModuleNotFoundError + module = importlib.util.module_from_spec(spec) + module.__lazy_module_state__ = LazyModuleState(module) # type: ignore + module.__class__ = LazyModule + sys.modules[name] = module + return module + + +def get_module( + name: str, + required: str | None = None, + lazy: bool = True, +) -> Any: + """Return module or None. Absolute import is required. + + :param (str) name: Dot-separated module path. E.g., 'scipy.stats'. + :param (str) required: A string to raise a ValueError if missing + :param (bool) lazy: If True, return a lazy loader for the module. + :return: (module|None) If import succeeds, the module will be returned. + """ + if name not in _not_importable: + try: + if not lazy: + return import_module(name) + else: + return import_module_lazy(name) + except Exception: + _not_importable.add(name) + msg = f"Error importing optional module {name}" + if required: + logger.exception(msg) + if required and name in _not_importable: + raise wandb.Error(required) + + +def get_optional_module(name) -> importlib.ModuleInterface | None: # type: ignore + return get_module(name) + + +np = get_module("numpy") + +pd_available = False +pandas_spec = importlib.util.find_spec("pandas") +if pandas_spec is not None: + pd_available = True + +# TODO: Revisit these limits +VALUE_BYTES_LIMIT = 100000 + + +@deprecated("Read the `app_url` setting from the appropriate Settings object.") +def app_url(api_url: str) -> str: + """Returns the URL for the W&B UI without a trailing slash.""" + if app_url := wandb.env.get_app_url(): + return str(app_url.strip("/")) + + return api_to_app_url(api_url) + + +def api_to_app_url(api_url: str) -> str: + """Convert the API URL to an app (UI) URL. + + Unlike the deprecated `app_url()`, this is a pure function: it does + not consult environment variables. + """ + if "://api.wandb.test" in api_url: + # dev mode + return api_url.replace("://api.", "://app.").strip("/") + elif "://api.wandb." in api_url: + # cloud + return api_url.replace("://api.", "://").strip("/") + elif "://api." in api_url: + # onprem cloud + return api_url.replace("://api.", "://app.").strip("/") + # wandb/local + return api_url + + +def get_full_typename(o: Any) -> Any: + """Determine types based on type names. + + Avoids needing to to import (and therefore depend on) PyTorch, TensorFlow, etc. + """ + instance_name = o.__class__.__module__ + "." + o.__class__.__name__ + if instance_name in ["builtins.module", "__builtin__.module"]: + return o.__name__ + else: + return instance_name + + +def get_h5_typename(o: Any) -> Any: + typename = get_full_typename(o) + if is_tf_tensor_typename(typename): + return "tensorflow.Tensor" + elif is_pytorch_tensor_typename(typename): + return "torch.Tensor" + else: + return o.__class__.__module__.split(".")[0] + "." + o.__class__.__name__ + + +def is_uri(string: str) -> bool: + parsed_uri = urllib.parse.urlparse(string) + return len(parsed_uri.scheme) > 0 + + +def local_file_uri_to_path(uri: str) -> str: + """Convert URI to local filesystem path. + + No-op if the uri does not have the expected scheme. + """ + path = urllib.parse.urlparse(uri).path if uri.startswith("file:") else uri + return urllib.request.url2pathname(path) + + +def get_local_path_or_none(path_or_uri: str) -> str | None: + """Return path if local, None otherwise. + + Return None if the argument is a local path (not a scheme or file:///). Otherwise + return `path_or_uri`. + """ + parsed_uri = urllib.parse.urlparse(path_or_uri) + if ( + len(parsed_uri.scheme) == 0 + or parsed_uri.scheme == "file" + and len(parsed_uri.netloc) == 0 + ): + return local_file_uri_to_path(path_or_uri) + else: + return None + + +def check_windows_valid_filename(path: int | str) -> bool: + r"""Verify that the given path does not contain any invalid characters for a Windows filename. + + Windows filenames cannot contain the following characters: + < > : " \ / | ? * + + For more details, refer to the official documentation: + https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions + + Args: + path: The file path to check, which can be either an integer or a string. + + Returns: + bool: True if the path does not contain any invalid characters, False otherwise. + """ + return not bool(re.search(r'[<>:"\\?*]', path)) # type: ignore + + +def make_file_path_upload_safe(path: str) -> str: + r"""Makes the provide path safe for file upload. + + The filename is made safe by: + 1. Removing any leading slashes to prevent writing to absolute paths + 2. Replacing '.' and '..' with underscores to prevent directory traversal attacks + + Raises: + ValueError: If running on Windows and the key contains invalid filename characters + (\, :, *, ?, ", <, >, |) + """ + sys_platform = platform.system() + if sys_platform == "Windows" and not check_windows_valid_filename(path): + raise ValueError( + f"Path {path} is invalid. Please remove invalid filename characters" + r' (\, :, *, ?, ", <, >, |)' + ) + + # On Windows, convert forward slashes to backslashes. + # This ensures that the key is a valid filename on Windows. + if sys_platform == "Windows": + path = str(path).replace("/", os.sep) + + # Avoid writing to absolute paths by striping any leading slashes. + # The key has already been validated for windows operating systems in util.check_windows_valid_filename + # This ensures the key does not contain invalid characters for windows, such as '\' or ':'. + # So we can check only for '/' in the key. + path = path.lstrip(os.sep) + + # Avoid directory traversal by replacing dots with underscores. + paths = path.split(os.sep) + safe_paths = [ + p.replace(".", "_") if p in (os.curdir, os.pardir) else p for p in paths + ] + + # Recombine the key into a relative path. + return os.sep.join(safe_paths) + + +def make_tarfile( + output_filename: str, + source_dir: str, + archive_name: str, + custom_filter: Callable | None = None, +) -> None: + # Helper for filtering out modification timestamps + def _filter_timestamps(tar_info: tarfile.TarInfo) -> tarfile.TarInfo | None: + tar_info.mtime = 0 + return tar_info if custom_filter is None else custom_filter(tar_info) + + descriptor, unzipped_filename = tempfile.mkstemp() + try: + with tarfile.open(unzipped_filename, "w") as tar: + tar.add(source_dir, arcname=archive_name, filter=_filter_timestamps) + # When gzipping the tar, don't include the tar's filename or modification time in the + # zipped archive (see https://docs.python.org/3/library/gzip.html#gzip.GzipFile) + with ( + open(output_filename, "wb") as out_file, + GzipFile(filename="", fileobj=out_file, mode="wb", mtime=0) as gzipped_tar, + open(unzipped_filename, "rb") as tar_file, + ): + gzipped_tar.write(tar_file.read()) + finally: + os.close(descriptor) + os.remove(unzipped_filename) + + +def is_tf_tensor(obj: Any) -> bool: + import tensorflow # type: ignore + + return isinstance(obj, tensorflow.Tensor) + + +def is_tf_tensor_typename(typename: str) -> bool: + return typename.startswith("tensorflow.") and ( + "Tensor" in typename or "Variable" in typename + ) + + +def is_tf_eager_tensor_typename(typename: str) -> bool: + return typename.startswith("tensorflow.") and ("EagerTensor" in typename) + + +def is_pytorch_tensor(obj: Any) -> bool: + import torch # type: ignore + + return isinstance(obj, torch.Tensor) + + +def is_pytorch_tensor_typename(typename: str) -> bool: + return typename.startswith("torch.") and ( + "Tensor" in typename or "Variable" in typename + ) + + +def is_jax_tensor_typename(typename: str) -> bool: + return typename.startswith("jaxlib.") and "Array" in typename + + +def get_jax_tensor(obj: Any) -> Any: + import jax # type: ignore + + return jax.device_get(obj) + + +def is_fastai_tensor_typename(typename: str) -> bool: + return typename.startswith("fastai.") and ("Tensor" in typename) + + +def is_pandas_data_frame_typename(typename: str) -> bool: + return typename.startswith("pandas.") and "DataFrame" in typename + + +def is_matplotlib_typename(typename: str) -> bool: + return typename.startswith("matplotlib.") + + +def is_plotly_typename(typename: str) -> bool: + return typename.startswith("plotly.") + + +def is_plotly_figure_typename(typename: str) -> bool: + return typename.startswith("plotly.") and typename.endswith(".Figure") + + +def is_numpy_array(obj: Any) -> bool: + return np and isinstance(obj, np.ndarray) + + +def is_pandas_data_frame(obj: Any) -> bool: + if pd_available: + import pandas as pd + + return isinstance(obj, pd.DataFrame) + else: + return is_pandas_data_frame_typename(get_full_typename(obj)) + + +def ensure_matplotlib_figure(obj: Any) -> Any: + """Extract the current figure from a matplotlib object. + + Return the object itself if it's a figure. + Raises ValueError if the object can't be converted. + """ + import matplotlib # type: ignore + from matplotlib.figure import Figure # type: ignore + + # there are combinations of plotly and matplotlib versions that don't work well together, + # this patches matplotlib to add a removed method that plotly assumes exists + from matplotlib.spines import Spine # type: ignore + + def is_frame_like(self: Any) -> bool: + """Return True if directly on axes frame. + + This is useful for determining if a spine is the edge of an + old style MPL plot. If so, this function will return True. + """ + position = self._position or ("outward", 0.0) + if isinstance(position, str): + if position == "center": + position = ("axes", 0.5) + elif position == "zero": + position = ("data", 0) + if len(position) != 2: + raise ValueError("position should be 2-tuple") + position_type, amount = position # type: ignore + return bool(position_type == "outward" and amount == 0) + + Spine.is_frame_like = is_frame_like + + if obj == matplotlib.pyplot: + obj = obj.gcf() + elif (not isinstance(obj, Figure)) and hasattr(obj, "figure"): + obj = obj.figure + # Some matplotlib objects have a figure function + if not isinstance(obj, Figure): + raise ValueError( + "Only matplotlib.pyplot or matplotlib.pyplot.Figure objects are accepted." + ) + return obj + + +def matplotlib_to_plotly(obj: Any) -> Any: + obj = ensure_matplotlib_figure(obj) + tools = get_module( + "plotly.tools", + required=( + "plotly is required to log interactive plots, install with: " + "`pip install plotly` or convert the plot to an image with `wandb.Image(plt)`" + ), + ) + return tools.mpl_to_plotly(obj) + + +def matplotlib_contains_images(obj: Any) -> bool: + obj = ensure_matplotlib_figure(obj) + return any(len(ax.images) > 0 for ax in obj.axes) + + +def _numpy_generic_convert(obj: Any) -> Any: + obj = obj.item() + if isinstance(obj, float) and math.isnan(obj): + obj = None + elif isinstance(obj, np.generic) and ( + obj.dtype.kind == "f" or obj.dtype == "bfloat16" + ): + # obj is a numpy float with precision greater than that of native python float + # (i.e., float96 or float128) or it is of custom type such as bfloat16. + # in these cases, obj.item() does not return a native + # python float (in the first case - to avoid loss of precision, + # so we need to explicitly cast this down to a 64bit float) + obj = float(obj) + return obj + + +def _sanitize_numpy_keys( + d: dict, + visited: dict[int, dict] | None = None, +) -> tuple[dict, bool]: + """Returns a dictionary where all NumPy keys are converted. + + Args: + d: The dictionary to sanitize. + + Returns: + A sanitized dictionary, and a boolean indicating whether anything was + changed. + """ + out: dict[Any, Any] = dict() + converted = False + + # Work with recursive dictionaries: if a dictionary has already been + # converted, reuse its converted value to retain the recursive structure + # of the input. + if visited is None: + visited = {id(d): out} + elif id(d) in visited: + return visited[id(d)], False + visited[id(d)] = out + + for key, value in d.items(): + if isinstance(value, dict): + value, converted_value = _sanitize_numpy_keys(value, visited) + converted |= converted_value + if isinstance(key, np.generic): + key = _numpy_generic_convert(key) + converted = True + out[key] = value + + return out, converted + + +def json_friendly( # noqa: C901 + obj: Any, +) -> tuple[Any, bool] | tuple[None | str | float, bool]: + """Convert an object into something that's more becoming of JSON.""" + converted = True + typename = get_full_typename(obj) + + if is_tf_eager_tensor_typename(typename): + obj = obj.numpy() + elif is_tf_tensor_typename(typename): + try: + obj = obj.eval() + except RuntimeError: + obj = obj.numpy() + elif is_pytorch_tensor_typename(typename) or is_fastai_tensor_typename(typename): + try: + if obj.requires_grad: + obj = obj.detach() + except AttributeError: + pass # before 0.4 is only present on variables + + try: + obj = obj.data + except RuntimeError: + pass # happens for Tensors before 0.4 + + if obj.size(): + obj = obj.cpu().detach().numpy() + else: + return obj.item(), True + elif is_jax_tensor_typename(typename): + obj = get_jax_tensor(obj) + + if is_numpy_array(obj): + if obj.size == 1: + obj = obj.flatten()[0] + elif obj.size <= 32: + obj = obj.tolist() + elif np and isinstance(obj, np.generic): + obj = _numpy_generic_convert(obj) + elif isinstance(obj, bytes): + obj = obj.decode("utf-8") + elif isinstance(obj, (datetime, date)): + obj = obj.isoformat() + elif callable(obj): + obj = ( + f"{obj.__module__}.{obj.__qualname__}" + if hasattr(obj, "__qualname__") and hasattr(obj, "__module__") + else str(obj) + ) + elif isinstance(obj, float) and math.isnan(obj): + obj = None + elif isinstance(obj, dict) and np: + obj, converted = _sanitize_numpy_keys(obj) + elif isinstance(obj, set): + # set is not json serializable, so we convert it to tuple + obj = tuple(obj) + elif isinstance(obj, enum.Enum): + obj = obj.name + else: + converted = False + if getsizeof(obj) > VALUE_BYTES_LIMIT: + wandb.termwarn( + f"Serializing object of type {type(obj).__name__} that is {getsizeof(obj)} bytes" + ) + return obj, converted + + +def json_friendly_val(val: Any) -> Any: + """Make any value (including dict, slice, sequence, dataclass) JSON friendly.""" + converted: dict | list + if isinstance(val, dict): + converted = {} + for key, value in val.items(): + converted[key] = json_friendly_val(value) + return converted + if isinstance(val, slice): + converted = dict( + slice_start=val.start, slice_step=val.step, slice_stop=val.stop + ) + return converted + val, _ = json_friendly(val) + if isinstance(val, Sequence) and not isinstance(val, str): + converted = [] + for value in val: + converted.append(json_friendly_val(value)) + return converted + if is_dataclass(val) and not isinstance(val, type): + converted = asdict(val) + return json_friendly_val(converted) + else: + if val.__class__.__module__ not in ("builtins", "__builtin__"): + val = str(val) + return val + + +def alias_is_version_index(alias: str) -> bool: + return len(alias) >= 2 and alias[0] == "v" and alias[1:].isnumeric() + + +def convert_plots(obj: Any) -> Any: + if is_matplotlib_typename(get_full_typename(obj)): + tools = get_module( + "plotly.tools", + required=( + "plotly is required to log interactive plots, install with: " + "`pip install plotly` or convert the plot to an image with `wandb.Image(plt)`" + ), + ) + obj = tools.mpl_to_plotly(obj) + + if is_plotly_typename(get_full_typename(obj)): + return {"_type": "plotly", "plot": obj.to_plotly_json()} + else: + return obj + + +def maybe_compress_history(obj: Any) -> tuple[Any, bool]: + if np and isinstance(obj, np.ndarray) and obj.size > 32: + return wandb.Histogram(obj, num_bins=32).to_json(), True + else: + return obj, False + + +def maybe_compress_summary(obj: Any, h5_typename: str) -> tuple[Any, bool]: + if np and isinstance(obj, np.ndarray) and obj.size > 32: + return ( + { + "_type": h5_typename, # may not be ndarray + "var": np.var(obj).item(), + "mean": np.mean(obj).item(), + "min": np.amin(obj).item(), + "max": np.amax(obj).item(), + "10%": np.percentile(obj, 10), + "25%": np.percentile(obj, 25), + "75%": np.percentile(obj, 75), + "90%": np.percentile(obj, 90), + "size": obj.size, + }, + True, + ) + else: + return obj, False + + +def launch_browser(attempt_launch_browser: bool = True) -> bool: + """Decide if we should launch a browser.""" + _display_variables = ["DISPLAY", "WAYLAND_DISPLAY", "MIR_SOCKET"] + _webbrowser_names_blocklist = ["www-browser", "lynx", "links", "elinks", "w3m"] + + import webbrowser + + launch_browser = attempt_launch_browser + if launch_browser: + if "linux" in sys.platform and not any( + os.getenv(var) for var in _display_variables + ): + launch_browser = False + try: + browser = webbrowser.get() + if hasattr(browser, "name") and browser.name in _webbrowser_names_blocklist: + launch_browser = False + except webbrowser.Error: + launch_browser = False + + return launch_browser + + +def generate_id(length: int = 8) -> str: + # Do not use this; use wandb.sdk.lib.runid.generate_id instead. + # This is kept only for legacy code. + return runid.generate_id(length) + + +def parse_tfjob_config() -> Any: + """Attempt to parse TFJob config, returning False if it can't find it.""" + if os.getenv("TF_CONFIG"): + try: + return json.loads(os.environ["TF_CONFIG"]) + except ValueError: + return False + else: + return False + + +class WandBJSONEncoder(json.JSONEncoder): + """A JSON Encoder that handles some extra types.""" + + def default(self, obj: Any) -> Any: + if hasattr(obj, "json_encode"): + return obj.json_encode() + # if hasattr(obj, 'to_json'): + # return obj.to_json() + tmp_obj, converted = json_friendly(obj) + if converted: + return tmp_obj + return json.JSONEncoder.default(self, obj) + + +class WandBJSONEncoderOld(json.JSONEncoder): + """A JSON Encoder that handles some extra types.""" + + def default(self, obj: Any) -> Any: + tmp_obj, converted = json_friendly(obj) + tmp_obj, compressed = maybe_compress_summary(tmp_obj, get_h5_typename(obj)) + if converted: + return tmp_obj + return json.JSONEncoder.default(self, tmp_obj) + + +class WandBHistoryJSONEncoder(json.JSONEncoder): + """A JSON Encoder that handles some extra types. + + This encoder turns numpy like objects with a size > 32 into histograms. + """ + + def default(self, obj: Any) -> Any: + obj, converted = json_friendly(obj) + obj, compressed = maybe_compress_history(obj) + if converted: + return obj + return json.JSONEncoder.default(self, obj) + + +class JSONEncoderUncompressed(json.JSONEncoder): + """A JSON Encoder that handles some extra types. + + This encoder turns numpy like objects with a size > 32 into histograms. + """ + + def default(self, obj: Any) -> Any: + if is_numpy_array(obj): + return obj.tolist() + elif np and isinstance(obj, np.number): + return obj.item() + elif np and isinstance(obj, np.generic): + obj = obj.item() + return json.JSONEncoder.default(self, obj) + + +def json_dump_safer(obj: Any, fp: IO[str], **kwargs: Any) -> None: + """Convert obj to json, with some extra encodable types.""" + return dump(obj, fp, cls=WandBJSONEncoder, **kwargs) + + +def json_dumps_safer(obj: Any, **kwargs: Any) -> str: + """Convert obj to json, with some extra encodable types.""" + return dumps(obj, cls=WandBJSONEncoder, **kwargs) + + +# This is used for dumping raw json into files +def json_dump_uncompressed(obj: Any, fp: IO[str], **kwargs: Any) -> None: + """Convert obj to json, with some extra encodable types.""" + return dump(obj, fp, cls=JSONEncoderUncompressed, **kwargs) + + +def json_dumps_safer_history(obj: Any, **kwargs: Any) -> str: + """Convert obj to json, with some extra encodable types, including histograms.""" + return dumps(obj, cls=WandBHistoryJSONEncoder, **kwargs) + + +def make_json_if_not_number( + v: int | float | str | Mapping | Sequence, +) -> int | float | str: + """If v is not a basic type convert it to json.""" + if isinstance(v, (float, int)): + return v + return json_dumps_safer(v) + + +def make_safe_for_json(obj: Any) -> Any: + """Replace invalid json floats with strings. Also converts to lists and dicts.""" + if isinstance(obj, Mapping): + return {k: make_safe_for_json(v) for k, v in obj.items()} + elif isinstance(obj, str): + # str's are Sequence, so we need to short-circuit + return obj + elif isinstance(obj, Sequence): + return [make_safe_for_json(v) for v in obj] + elif isinstance(obj, float): + # W&B backend and UI handle these strings + if obj != obj: # standard way to check for NaN + return "NaN" + elif obj == float("+inf"): + return "Infinity" + elif obj == float("-inf"): + return "-Infinity" + return obj + + +def no_retry_4xx(e: Exception) -> bool: + from requests import HTTPError + + if not isinstance(e, HTTPError): + return True + assert e.response is not None + if not (400 <= e.response.status_code < 500) or e.response.status_code == 429: + return True + body = json.loads(e.response.content) + raise UsageError(body["errors"][0]["message"]) + + +def parse_backend_error_messages(response: Response) -> list[str]: + """Returns error messages stored in a backend response. + + If the response is not in an expected format, an empty list is returned. + + Args: + response: A response to an HTTP request to the W&B server. + """ + from requests import JSONDecodeError + + try: + data = response.json() + except JSONDecodeError: + return [] + + if not isinstance(data, dict): + return [] + + # Backend error values are returned in one of two ways: + # - A string containing the error message + # - A JSON object with a "message" field that is a string + def get_message(error: Any) -> str | None: + if isinstance(error, str): + return error + elif ( + isinstance(error, dict) + and (message := error.get("message")) + and isinstance(message, str) + ): + return message + else: + return None + + # The response can contain an "error" field with a single error + # or an "errors" field with a list of errors. + if error := data.get("error"): + message = get_message(error) + return [message] if message else [] + + elif (errors := data.get("errors")) and isinstance(errors, list): + messages: list[str] = [] + for error in errors: + message = get_message(error) + if message: + messages.append(message) + return messages + + else: + return [] + + +def no_retry_auth(e: Any) -> bool: + from requests import HTTPError + + if hasattr(e, "exception"): + e = e.exception + if not isinstance(e, HTTPError): + return True + if e.response is None: + return True + # Don't retry bad request errors; raise immediately + if e.response.status_code in (400, 409): + return False + # Retry all non-forbidden/unauthorized/not-found errors. + if e.response.status_code not in (401, 403, 404): + return True + + # Crash with more informational message on forbidden/unauthorized errors. + # UnauthorizedError + if e.response.status_code == 401: + raise AuthenticationError( + "The API key you provided is either invalid or missing. " + f"If the `{wandb.env.API_KEY}` environment variable is set, make sure it is correct. " + "Otherwise, to resolve this issue, you may try running the 'wandb login --relogin' command. " + "If you are using a local server, make sure that you're using the correct hostname. " + "If you're not sure, you can try logging in again using the 'wandb login --relogin --host [hostname]' command." + f"(Error {e.response.status_code}: {e.response.reason})" + ) + # ForbiddenError + if e.response.status_code == 403: + if wandb.run: + raise CommError(f"Permission denied to access {wandb.run.path}") + else: + raise CommError( + "It appears that you do not have permission to access the requested resource. " + "Please reach out to the project owner to grant you access. " + "If you have the correct permissions, verify that there are no issues with your networking setup." + f"(Error {e.response.status_code}: {e.response.reason})" + ) + + # NotFoundError + if e.response.status_code == 404: + # If error message is empty, raise a more generic NotFoundError message. + if parse_backend_error_messages(e.response): + return False + else: + raise LookupError( + f"Failed to find resource. Please make sure you have the correct resource path. " + f"(Error {e.response.status_code}: {e.response.reason})" + ) + return False + + +def check_retry_conflict(e: Any) -> bool | None: + """Check if the exception is a conflict type so it can be retried. + + Returns: + True - Should retry this operation + False - Should not retry this operation + None - No decision, let someone else decide + """ + from requests import HTTPError + + if hasattr(e, "exception"): + e = e.exception + if ( + isinstance(e, HTTPError) + and e.response is not None + and e.response.status_code == 409 + ): + return True + return None + + +def check_retry_conflict_or_gone(e: Any) -> bool | None: + """Check if the exception is a conflict or gone type, so it can be retried or not. + + Returns: + True - Should retry this operation + False - Should not retry this operation + None - No decision, let someone else decide + """ + from requests import HTTPError + + if hasattr(e, "exception"): + e = e.exception + if isinstance(e, HTTPError) and e.response is not None: + if e.response.status_code == 409: + return True + if e.response.status_code == 410: + return False + return None + + +def make_check_retry_fn( + fallback_retry_fn: CheckRetryFnType, + check_fn: Callable[[Exception], bool | None], + check_timedelta: timedelta | None = None, +) -> CheckRetryFnType: + """Return a check_retry_fn which can be used by lib.Retry(). + + Args: + fallback_fn: Use this function if check_fn didn't decide if a retry should happen. + check_fn: Function which returns bool if retry should happen or None if unsure. + check_timedelta: Optional retry timeout if we check_fn matches the exception + """ + + def check_retry_fn(e: Exception) -> bool | timedelta: + check = check_fn(e) + if check is None: + return fallback_retry_fn(e) + if check is False: + return False + if check_timedelta: + return check_timedelta + return True + + return check_retry_fn + + +def find_runner(program: str) -> None | list | list[str]: + """Return a command that will run program. + + Args: + program: The string name of the program to try to run. + + Returns: + commandline list of strings to run the program (eg. with subprocess.call()) or None + """ + if os.path.isfile(program) and not os.access(program, os.X_OK): + # program is a path to a non-executable file + try: + opened = open(program) + except OSError: # PermissionError doesn't exist in 2.7 + return None + first_line = opened.readline().strip() + if first_line.startswith("#!"): + return shlex.split(first_line[2:]) + if program.endswith(".py"): + return [sys.executable] + return None + + +def downsample(values: Sequence, target_length: int) -> list: + """Downsample 1d values to target_length, including start and end. + + Algorithm just rounds index down. + + Values can be any sequence, including a generator. + """ + if not target_length > 1: + raise UsageError("target_length must be > 1") + values = list(values) + if len(values) < target_length: + return values + ratio = float(len(values) - 1) / (target_length - 1) + result = [] + for i in range(target_length): + result.append(values[int(i * ratio)]) + return result + + +def has_num(dictionary: Mapping, key: Any) -> bool: + return key in dictionary and isinstance(dictionary[key], numbers.Number) + + +def docker_image_regex(image: str) -> Any: + """Regex match for valid docker image names.""" + if image: + return re.match( + r"^(?:(?=[^:\/]{1,253})(?!-)[a-zA-Z0-9-]{1,63}(? str | None: + """Scan docker run args and attempt to find the most likely docker image argument. + + It excludes any arguments that start with a dash, and the argument after it if it + isn't a boolean switch. This can be improved, we currently fallback gracefully when + this fails. + """ + bool_args = [ + "-t", + "--tty", + "--rm", + "--privileged", + "--oom-kill-disable", + "--no-healthcheck", + "-i", + "--interactive", + "--init", + "--help", + "--detach", + "-d", + "--sig-proxy", + "-it", + "-itd", + ] + last_flag = -2 + last_arg = "" + possible_images = [] + if len(args) > 0 and args[0] == "run": + args.pop(0) + for i, arg in enumerate(args): + if arg.startswith("-"): + last_flag = i + last_arg = arg + elif "@sha256:" in arg: + # Because our regex doesn't match digests + possible_images.append(arg) + elif docker_image_regex(arg): + if last_flag == i - 2: + possible_images.append(arg) + elif "=" in last_arg: + possible_images.append(arg) + elif last_arg in bool_args and last_flag == i - 1: + possible_images.append(arg) + most_likely = None + for img in possible_images: + if ":" in img or "@" in img or "/" in img: + most_likely = img + break + if most_likely is None and len(possible_images) > 0: + most_likely = possible_images[0] + return most_likely + + +def load_yaml(file: Any) -> Any: + import yaml + + return yaml.safe_load(file) + + +def image_id_from_k8s() -> str | None: + """Ping the k8s metadata service for the image id. + + Specify the KUBERNETES_NAMESPACE environment variable if your pods are not in the + default namespace: + + - name: KUBERNETES_NAMESPACE valueFrom: + fieldRef: + fieldPath: metadata.namespace + """ + token_path = "/var/run/secrets/kubernetes.io/serviceaccount/token" + + if not os.path.exists(token_path): + return None + + try: + with open(token_path) as token_file: + token = token_file.read() + except FileNotFoundError: + logger.warning(f"Token file not found at {token_path}.") + return None + except PermissionError as e: + current_uid = os.getuid() + warning = ( + f"Unable to read the token file at {token_path} due to permission error ({e})." + f"The current user id is {current_uid}. " + "Consider changing the securityContext to run the container as the current user." + ) + logger.warning(warning) + wandb.termwarn(warning) + return None + + if not token: + return None + + import requests + + k8s_server = "https://{}:{}/api/v1/namespaces/{}/pods/{}".format( + os.getenv("KUBERNETES_SERVICE_HOST"), + os.getenv("KUBERNETES_PORT_443_TCP_PORT"), + os.getenv("KUBERNETES_NAMESPACE", "default"), + os.getenv("HOSTNAME"), + ) + try: + res = requests.get( + k8s_server, + verify="/var/run/secrets/kubernetes.io/serviceaccount/ca.crt", + timeout=3, + headers={"Authorization": f"Bearer {token}"}, + ) + res.raise_for_status() + except requests.RequestException: + return None + try: + return str( # noqa: B005 + res.json()["status"]["containerStatuses"][0]["imageID"] + ).strip("docker-pullable://") + except (ValueError, KeyError, IndexError): + logger.exception("Error checking kubernetes for image id") + return None + + +def async_call(target: Callable, timeout: int | float | None = None) -> Callable: + """Wrap a method to run in the background with an optional timeout. + + Returns a new method that will call the original with any args, waiting for upto + timeout seconds. This new method blocks on the original and returns the result or + None if timeout was reached, along with the thread. You can check thread.is_alive() + to determine if a timeout was reached. If an exception is thrown in the thread, we + reraise it. + """ + q: queue.Queue = queue.Queue() + + def wrapped_target(q: queue.Queue, *args: Any, **kwargs: Any) -> Any: + try: + q.put(target(*args, **kwargs)) + except Exception as e: + q.put(e) + + def wrapper( + *args: Any, **kwargs: Any + ) -> tuple[Exception, threading.Thread] | tuple[None, threading.Thread]: + thread = threading.Thread( + target=wrapped_target, args=(q,) + args, kwargs=kwargs + ) + thread.daemon = True + thread.start() + + try: + result = q.get(True, timeout) + except queue.Empty: + return None, thread + + if isinstance(result, Exception): + raise result.with_traceback(sys.exc_info()[2]) + return result, thread + + return wrapper + + +def read_many_from_queue( + q: queue.Queue, max_items: int, queue_timeout: int | float +) -> list: + try: + item = q.get(True, queue_timeout) + except queue.Empty: + return [] + items = [item] + for _ in range(max_items): + try: + item = q.get_nowait() + except queue.Empty: + return items + items.append(item) + return items + + +def stopwatch_now() -> float: + """Get a time value for interval comparisons. + + When possible it is a monotonic clock to prevent backwards time issues. + """ + return time.monotonic() + + +def class_colors(class_count: int) -> list[list[int]]: + # make class 0 black, and the rest equally spaced fully saturated hues + return [[0, 0, 0]] + [ + colorsys.hsv_to_rgb(i / (class_count - 1.0), 1.0, 1.0) # type: ignore + for i in range(class_count - 1) + ] + + +def prompt_choices( + choices: Sequence[str], + input_timeout: float | None = None, +) -> str: + """Prompt the user to choose from a list of options. + + If exactly one choice is given, it is returned immediately. + + Raises: + TimeoutError: if input_timeout is specified and expires. + NotATerminalError: if the output device is not capable. + KeyboardInterrupt: if the user aborts by pressing Ctrl+C. + """ + if len(choices) == 1: + return choices[0] + + for i, choice_str in enumerate(choices): + wandb.termlog(f"({i + 1}) {choice_str}") + + while True: + choice = terminput("Enter your choice: ", timeout=input_timeout) + + # If the user presses enter without typing anything, try again. + if not choice: + continue + + idx = -1 + with contextlib.suppress(ValueError): + idx = int(choice) - 1 + + if idx < 0 or idx > len(choices) - 1: + wandb.termwarn("Invalid choice") + continue + + result = choices[idx] + wandb.termlog(f"You chose {result!r}") + return result + + +def guess_data_type(shape: Sequence[int], risky: bool = False) -> str | None: + """Infer the type of data based on the shape of the tensors. + + Args: + shape (Sequence[int]): The shape of the data + risky(bool): some guesses are more likely to be wrong. + """ + # (samples,) or (samples,logits) + if len(shape) in (1, 2): + return "label" + # Assume image mask like fashion mnist: (no color channel) + # This is risky because RNNs often have 3 dim tensors: batch, time, channels + if risky and len(shape) == 3: + return "image" + if len(shape) == 4: + if shape[-1] in (1, 3, 4): + # (samples, height, width, Y \ RGB \ RGBA) + return "image" + else: + # (samples, height, width, logits) + return "segmentation_mask" + return None + + +def download_file_from_url( + dest_path: str, source_url: str, api_key: str | None = None +) -> None: + import requests + + auth = ("api", api_key or "") + response = requests.get( + source_url, + auth=auth, + stream=True, + timeout=5, + ) + response.raise_for_status() + + if os.sep in dest_path: + filesystem.mkdir_exists_ok(os.path.dirname(dest_path)) + with fsync_open(dest_path, "wb") as file: + for data in response.iter_content(chunk_size=1024): + file.write(data) + + +def download_file_into_memory(source_url: str, api_key: str | None = None) -> bytes: + import requests + + auth = ("api", api_key or "") + response = requests.get( + source_url, + auth=auth, + stream=True, + timeout=5, + ) + response.raise_for_status() + return response.content + + +def isatty(ob: IO) -> bool: + return hasattr(ob, "isatty") and ob.isatty() + + +def to_human_size(size: int, units: list[tuple[str, Any]] | None = None) -> str: + units = units or POW_10_BYTES + unit, value = units[0] + factor = round(float(size) / value, 1) + return ( + f"{factor}{unit}" + if factor < 1024 or len(units) == 1 + else to_human_size(size, units[1:]) + ) + + +def from_human_size(size: str, units: list[tuple[str, Any]] | None = None) -> int: + units = units or POW_10_BYTES + units_dict = {unit.upper(): value for (unit, value) in units} + regex = re.compile( + r"(\d+\.?\d*)\s*({})?".format("|".join(units_dict.keys())), re.IGNORECASE + ) + match = re.match(regex, size) + if not match: + raise ValueError("size must be of the form `10`, `10B` or `10 B`.") + factor, unit = ( + float(match.group(1)), + units_dict[match.group(2).upper()] if match.group(2) else 1, + ) + return int(factor * unit) + + +def auto_project_name(program: str | None) -> str: + # if we're in git, set project name to git repo name + relative path within repo + from wandb.sdk.lib.gitlib import GitRepo + + root_dir = GitRepo().root_dir + if root_dir is None: + return "uncategorized" + # On windows, GitRepo returns paths in unix style, but os.path is windows + # style. Coerce here. + root_dir = to_native_slash_path(root_dir) + repo_name = os.path.basename(root_dir) + if program is None: + return str(repo_name) + if not os.path.isabs(program): + program = os.path.join(os.curdir, program) + prog_dir = os.path.dirname(os.path.abspath(program)) + if not prog_dir.startswith(root_dir): + return str(repo_name) + project = repo_name + sub_path = os.path.relpath(prog_dir, root_dir) + if sub_path != ".": + project += "-" + sub_path + return str(project.replace(os.sep, "_")) + + +# TODO(hugh): Deprecate version here and use wandb/sdk/lib/paths.py +def to_forward_slash_path(path: str) -> str: + if platform.system() == "Windows": + path = path.replace("\\", "/") + return path + + +# TODO(hugh): Deprecate version here and use wandb/sdk/lib/paths.py +def to_native_slash_path(path: str) -> FilePathStr: + return FilePathStr(path.replace("/", os.sep)) + + +def check_and_warn_old(files: list[str]) -> bool: + if "wandb-metadata.json" in files: + wandb.termwarn("These runs were logged with a previous version of wandb.") + wandb.termwarn( + "Run pip install wandb<0.10.0 to get the old library and sync your runs." + ) + return True + return False + + +class ImportMetaHook: + def __init__(self) -> None: + self.modules: dict[str, ModuleType] = dict() + self.on_import: dict[str, list] = dict() + + def add(self, fullname: str, on_import: Callable) -> None: + self.on_import.setdefault(fullname, []).append(on_import) + + def install(self) -> None: + sys.meta_path.insert(0, self) # type: ignore + + def uninstall(self) -> None: + sys.meta_path.remove(self) # type: ignore + + def find_module( + self, fullname: str, path: str | None = None + ) -> ImportMetaHook | None: + if fullname in self.on_import: + return self + return None + + def load_module(self, fullname: str) -> ModuleType: + self.uninstall() + mod = importlib.import_module(fullname) + self.install() + self.modules[fullname] = mod + on_imports = self.on_import.get(fullname) + if on_imports: + for f in on_imports: + f() + return mod + + def get_modules(self) -> tuple[str, ...]: + return tuple(self.modules) + + def get_module(self, module: str) -> ModuleType: + return self.modules[module] + + +_import_hook: ImportMetaHook | None = None + + +def add_import_hook(fullname: str, on_import: Callable) -> None: + global _import_hook + if _import_hook is None: + _import_hook = ImportMetaHook() + _import_hook.install() + _import_hook.add(fullname, on_import) + + +def host_from_path(path: str | None) -> str: + """Return the host of the path.""" + url = urllib.parse.urlparse(path) + return str(url.netloc) + + +def uri_from_path(path: str | None) -> str: + """Return the URI of the path.""" + url = urllib.parse.urlparse(path) + uri = url.path if url.path[0] != "/" else url.path[1:] + return str(uri) + + +def is_unicode_safe(stream: TextIO) -> bool: + """Return True if the stream supports UTF-8.""" + encoding = getattr(stream, "encoding", None) + return encoding.lower() in {"utf-8", "utf_8"} if encoding else False + + +def rand_alphanumeric( + length: int = 8, rand: ModuleType | random.Random | None = None +) -> str: + wandb.termerror("rand_alphanumeric is deprecated, use 'secrets.token_hex'") + rand = rand or random + return "".join(rand.choice("0123456789ABCDEF") for _ in range(length)) + + +@contextlib.contextmanager +def fsync_open( + path: StrPath, mode: str = "w", encoding: str | None = None +) -> Generator[IO[Any], None, None]: + """Open a path for I/O and guarantee that the file is flushed and synced.""" + with open(path, mode, encoding=encoding) as f: + yield f + + f.flush() + os.fsync(f.fileno()) + + +def _is_kaggle() -> bool: + return ( + os.getenv("KAGGLE_KERNEL_RUN_TYPE") is not None + or "kaggle_environments" in sys.modules + ) + + +def _has_internet() -> bool: + """Returns whether we have internet access. + + Checks for internet access by attempting to open a DNS connection to + Google's root servers. + """ + try: + s = socket.create_connection(("8.8.8.8", 53), 0.5) + s.close() + except OSError: + return False + + return True + + +def _is_likely_kaggle() -> bool: + # Telemetry to mark first runs from Kagglers. + return ( + _is_kaggle() + or os.path.exists( + os.path.expanduser(os.path.join("~", ".kaggle", "kaggle.json")) + ) + or "kaggle" in sys.modules + ) + + +def _is_databricks() -> bool: + # check if we are running inside a databricks notebook by + # inspecting sys.modules, searching for dbutils and verifying that + # it has the appropriate structure + + if "dbutils" in sys.modules: + dbutils = sys.modules["dbutils"] + if hasattr(dbutils, "shell"): + shell = dbutils.shell + if hasattr(shell, "sc"): + sc = shell.sc + if hasattr(sc, "appName"): + return bool(sc.appName == "Databricks Shell") + return False + + +def _is_py_requirements_or_dockerfile(path: str) -> bool: + file = os.path.basename(path) + return ( + file.endswith(".py") + or file.startswith("Dockerfile") + or file == "requirements.txt" + ) + + +def artifact_to_json(artifact: Artifact) -> dict[str, Any]: + return { + "_type": "artifactVersion", + "_version": "v0", + "id": artifact.id, + "version": artifact.source_version, + "sequenceName": artifact.source_name.split(":")[0], + "usedAs": artifact.use_as, + } + + +def check_dict_contains_nested_artifact(d: dict, nested: bool = False) -> bool: + for item in d.values(): + if isinstance(item, dict): + contains_artifacts = check_dict_contains_nested_artifact(item, True) + if contains_artifacts: + return True + elif (isinstance(item, wandb.Artifact) or _is_artifact_string(item)) and nested: + return True + return False + + +def load_json_yaml_dict(config: str) -> Any: + import yaml + + ext = os.path.splitext(config)[-1] + if ext == ".json": + with open(config) as f: + return json.load(f) + elif ext == ".yaml": + with open(config) as f: + return yaml.safe_load(f) + else: + try: + return json.loads(config) + except ValueError: + return None + + +def _parse_entity_project_item(path: str) -> tuple: + """Parse paths with the following formats: {item}, {project}/{item}, & {entity}/{project}/{item}. + + Args: + path: `str`, input path; must be between 0 and 3 in length. + + Returns: + tuple of length 3 - (item, project, entity) + + Example: + alias, project, entity = _parse_entity_project_item("myproj/mymodel:best") + + assert entity == "" + assert project == "myproj" + assert alias == "mymodel:best" + + """ + words = path.split("/") + if len(words) > 3: + raise ValueError( + "Invalid path: must be str the form {item}, {project}/{item}, or {entity}/{project}/{item}" + ) + padded_words = [""] * (3 - len(words)) + words + return tuple(reversed(padded_words)) + + +def _resolve_aliases(aliases: str | Iterable[str] | None) -> list[str]: + """Add the 'latest' alias and ensure that all aliases are unique. + + Takes in `aliases` which can be None, str, or List[str] and returns list[str]. + Ensures that "latest" is always present in the returned list. + + Args: + aliases: `aliases: str | Iterable[str] | None` + + Returns: + list[str], with "latest" always present. + + Usage: + + ```python + aliases = _resolve_aliases(["best", "dev"]) + assert aliases == ["best", "dev", "latest"] + + aliases = _resolve_aliases("boom") + assert aliases == ["boom", "latest"] + ``` + """ + aliases = aliases or ["latest"] + + if isinstance(aliases, str): + aliases = [aliases] + + try: + return list(set(aliases) | {"latest"}) + except TypeError as exc: + raise ValueError("`aliases` must be Iterable or None") from exc + + +def _is_artifact_object(v: Any) -> TypeGuard[wandb.Artifact]: + return isinstance(v, wandb.Artifact) + + +def _is_artifact_string(v: Any) -> TypeGuard[str]: + return isinstance(v, str) and v.startswith("wandb-artifact://") + + +def _is_artifact_version_weave_dict(v: Any) -> TypeGuard[dict]: + return isinstance(v, dict) and v.get("_type") == "artifactVersion" + + +def _is_artifact_representation(v: Any) -> bool: + return ( + _is_artifact_object(v) + or _is_artifact_string(v) + or _is_artifact_version_weave_dict(v) + ) + + +def parse_artifact_string(v: str) -> tuple[str, str | None, bool]: + if not v.startswith("wandb-artifact://"): + raise ValueError(f"Invalid artifact string: {v}") + parsed_v = v[len("wandb-artifact://") :] + base_uri = None + url_info = urllib.parse.urlparse(parsed_v) + if url_info.scheme != "": + base_uri = f"{url_info.scheme}://{url_info.netloc}" + parts = url_info.path.split("/")[1:] + else: + parts = parsed_v.split("/") + if parts[0] == "_id": + # for now can't fetch paths but this will be supported in the future + # when we allow passing typed media objects, this can be extended + # to include paths + return parts[1], base_uri, True + + if len(parts) < 3: + raise ValueError(f"Invalid artifact string: {v}") + + # for now can't fetch paths but this will be supported in the future + # when we allow passing typed media objects, this can be extended + # to include paths + entity, project, name_and_alias_or_version = parts[:3] + return f"{entity}/{project}/{name_and_alias_or_version}", base_uri, False + + +def _get_max_cli_version() -> str | None: + max_cli_version = wandb.api.max_cli_version() + return str(max_cli_version) if max_cli_version is not None else None + + +def ensure_text( + string: str | bytes, encoding: str = "utf-8", errors: str = "strict" +) -> str: + """Coerce s to str.""" + if isinstance(string, bytes): + return string.decode(encoding, errors) + elif isinstance(string, str): + return string + else: + raise TypeError(f"not expecting type {type(string)!r}") + + +def make_artifact_name_safe(name: str) -> str: + """Make an artifact name safe for use in artifacts.""" + # artifact names may only contain alphanumeric characters, dashes, underscores, and dots. + cleaned = re.sub(r"[^a-zA-Z0-9_\-.]", "_", name) + if len(cleaned) <= 128: + return cleaned + # truncate with dots in the middle using regex + return re.sub(r"(^.{63}).*(.{63}$)", r"\g<1>..\g<2>", cleaned) + + +def make_docker_image_name_safe(name: str) -> str: + """Make a docker image name safe for use in artifacts.""" + safe_chars = RE_DOCKER_IMAGE_NAME_CHARS.sub("__", name.lower()) + deduped = RE_DOCKER_IMAGE_NAME_SEPARATOR_REPEAT.sub("__", safe_chars) + trimmed_start = RE_DOCKER_IMAGE_NAME_SEPARATOR_START.sub("", deduped) + trimmed = RE_DOCKER_IMAGE_NAME_SEPARATOR_END.sub("", trimmed_start) + return trimmed if trimmed else "image" + + +def merge_dicts( + source: dict[str, Any], + destination: dict[str, Any], +) -> dict[str, Any]: + """Recursively merge two dictionaries. + + This mutates the destination and its nested dictionaries and lists. + + Instances of `dict` are recursively merged and instances of `list` + are appended to the destination. If the destination type is not + `dict` or `list`, respectively, the key is overwritten with the + source value. + + For all other types, the source value overwrites the destination value. + """ + for key, value in source.items(): + if isinstance(value, dict): + node = destination.get(key) + if isinstance(node, dict): + merge_dicts(value, node) + else: + destination[key] = value + + elif isinstance(value, list): + dest_value = destination.get(key) + if isinstance(dest_value, list): + dest_value.extend(value) + else: + destination[key] = value + + else: + destination[key] = value + + return destination + + +def coalesce(*arg: Any) -> Any: + """Return the first non-none value in the list of arguments. + + Similar to ?? in C#. + """ + return next((a for a in arg if a is not None), None) + + +def recursive_cast_dictlike_to_dict(d: dict[str, Any]) -> dict[str, Any]: + for k, v in d.items(): + if isinstance(v, dict): + recursive_cast_dictlike_to_dict(v) + elif hasattr(v, "keys"): + d[k] = dict(v) + recursive_cast_dictlike_to_dict(d[k]) + return d + + +def remove_keys_with_none_values(d: dict[str, Any] | Any) -> dict[str, Any] | Any: + # otherwise iterrows will create a bunch of ugly charts + if not isinstance(d, dict): + return d + + if isinstance(d, dict): + new_dict = {} + for k, v in d.items(): + new_v = remove_keys_with_none_values(v) + if new_v is not None and not (isinstance(new_v, dict) and len(new_v) == 0): + new_dict[k] = new_v + return new_dict if new_dict else None + + +def batched(n: int, iterable: Iterable[T]) -> Generator[list[T], None, None]: + i = iter(iterable) + batch = list(itertools.islice(i, n)) + while batch: + yield batch + batch = list(itertools.islice(i, n)) + + +def random_string(length: int = 12) -> str: + """Generate a random string of a given length. + + :param length: Length of the string to generate. + :return: Random string. + """ + return "".join( + secrets.choice(string.ascii_lowercase + string.digits) for _ in range(length) + ) + + +def sample_with_exponential_decay_weights( + xs: Iterable | Iterable[Iterable], + ys: Iterable[Iterable], + keys: Iterable | None = None, + sample_size: int = 1500, +) -> tuple[list, list, list | None]: + """Sample from a list of lists with weights that decay exponentially. + + May be used with the wandb.plot.line_series function. + """ + xs_array = np.array(xs) + ys_array = np.array(ys) + keys_array = np.array(keys) if keys else None + weights = np.exp(-np.arange(len(xs_array)) / len(xs_array)) + weights /= np.sum(weights) + sampled_indices = np.random.choice(len(xs_array), size=sample_size, p=weights) + sampled_xs = xs_array[sampled_indices].tolist() + sampled_ys = ys_array[sampled_indices].tolist() + sampled_keys = keys_array[sampled_indices].tolist() if keys_array else None + + return sampled_xs, sampled_ys, sampled_keys + + +@dataclasses.dataclass(frozen=True) +class InstalledDistribution: + """An installed distribution. + + Attributes: + key: The distribution name as it would be imported. + version: The distribution's version string. + """ + + key: str + version: str + + +def working_set() -> Iterable[InstalledDistribution]: + """Return the working set of installed distributions.""" + from importlib.metadata import distributions + + for d in distributions(): + with contextlib.suppress(KeyError, UnicodeDecodeError, TypeError): + # In some distributions, the "Name" attribute may not be present, + # or the metadata itself may be None or malformed, which can raise + # KeyError, UnicodeDecodeError, or TypeError. + # For additional context, see: https://github.com/python/importlib_metadata/issues/371. + yield InstalledDistribution(key=d.metadata["Name"], version=d.version) + + +def get_core_path() -> str: + """Returns the path to the wandb-core binary. + + Returns: + str: The path to the wandb-core package. + + Raises: + WandbCoreNotAvailableError: If wandb-core was not built for the current system. + """ + bin_path = pathlib.Path(__file__).parent / "bin" / "wandb-core" + if not bin_path.exists(): + raise WandbCoreNotAvailableError( + f"File not found: {bin_path}." + " Please contact support at support@wandb.com." + f" Your platform is: {platform.platform()}." + ) + + return str(bin_path) + + +def time_string_to_seconds(time_str: str) -> int: + """Parse a time period string and return seconds. + + Args: + time_str: Time period string like "10s", "5m", "8h", "8d", "6M", "1y" + Accepted values are: + - s (seconds) + - m (minutes) + - h (hours) + - d (days) + - M (months) + - y (years) + + Returns: + Number of seconds in the time period + + Raises: + ValueError: If the format is invalid + + Examples: + >>> parse_time_period("10s") + 10 + >>> parse_time_period("5m") + 300 + >>> parse_time_period("8d") + 691200 + >>> parse_time_period("6M") + 15552000 + >>> parse_time_period("1y") + 31536000 + """ + import re + + if not time_str: + return 0 + + # Extract number and unit + match = re.match(r"^(\d+)([smhdMy])$", time_str) + if not match: + raise ValueError( + f"Invalid time period format: {time_str}. " + "Expected format: where unit is s (seconds), " + "m (minutes), h (hours), d (days), M (months), or y (years)" + ) + + amount = int(match.group(1)) + unit = match.group(2) + + # Convert to seconds + conversions = { + "s": 1, # seconds + "m": 60, # minutes + "h": 3600, # hours + "d": 86400, # days + "M": 2592000, # months (30 days) + "y": 31536000, # years (365 days) + } + + return amount * conversions[unit] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/wandb_agent.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/wandb_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..6501472ef65dddb767a2bb71e19476051650680b --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/wandb_agent.py @@ -0,0 +1,695 @@ +from __future__ import annotations + +import contextlib +import logging +import multiprocessing +import os +import platform +import queue +import re +import signal +import socket +import subprocess +import sys +import time +import traceback +from collections.abc import Callable +from typing import Any + +import wandb +from wandb import util +from wandb.sdk import wandb_login, wandb_setup +from wandb.sdk.lib import config_util, ipython + +logger = logging.getLogger(__name__) + + +class AgentError(Exception): + pass + + +class AgentProcess: + """Launch and manage a process.""" + + def __init__( + self, + env=None, + command=None, + function=None, + run_id=None, + in_jupyter=None, + forward_signals=False, + ): + self._popen = None + self._proc = None + self._finished_q = multiprocessing.Queue() + self._proc_killed = False + + # Store original handlers + self._original_handlers = {} + + # Set up handlers for all possible signals + if forward_signals: + skip_signals = { + getattr(signal, "SIGKILL", None), + getattr(signal, "SIGSTOP", None), + } + skip_signals.discard(None) + for signum in signal.valid_signals(): + # Skip signals that can't be caught + if signum in skip_signals: + continue + with contextlib.suppress(OSError, ValueError): + # Some signals might not be supported on all platforms + self._original_handlers[signum] = signal.getsignal(signum) + signal.signal(signum, self._forward_signal) + + if command: + if platform.system() == "Windows": + kwargs = dict(creationflags=subprocess.CREATE_NEW_PROCESS_GROUP) + env.pop(wandb.env.SERVICE, None) + # TODO: Determine if we need the same stdin workaround as POSIX case below. + self._popen = subprocess.Popen(command, env=env, **kwargs) + else: + if sys.version_info >= (3, 11): + # preexec_fn=os.setpgrp is not thread-safe; process_group was introduced in + # python 3.11 to replace it, so use that when possible + kwargs = dict(process_group=0) + else: + kwargs = dict(preexec_fn=os.setpgrp) + env.pop(wandb.env.SERVICE, None) + # Upon spawning the subprocess in a new process group, the child's process group is + # not connected to the controlling terminal's stdin. If it tries to access stdin, + # it gets a SIGTTIN and blocks until we give it the terminal, which we don't want + # to do. + # + # By using subprocess.PIPE, we give it an independent stdin. However, it will still + # block if it tries to read from stdin, because we're not writing anything to it. + # We immediately close the subprocess's stdin here so it can fail fast and get an + # EOF. + # + # (One situation that makes this relevant is that importing `readline` even + # indirectly can cause the child to attempt to access stdin, which can trigger the + # deadlock. In Python 3.13, `import torch` indirectly imports `readline` via `pdb`, + # meaning `import torch` in a run script can deadlock unless we override stdin. + # See https://github.com/wandb/wandb/pull/10489 description for more details.) + # + # Also, we avoid spawning a new session because that breaks preempted child process + # handling. + self._popen = subprocess.Popen( + command, + env=env, + stdin=subprocess.PIPE, + **kwargs, + ) + self._popen.stdin.close() + elif function: + self._proc = multiprocessing.Process( + target=self._start, + args=(self._finished_q, env, function, run_id, in_jupyter), + ) + self._proc.start() + else: + raise AgentError("Agent Process requires command or function") + + def _forward_signal(self, signum, frame): + """Forward a received signal to any child process, mirroring the agent's behavior.""" + if self._popen: + if platform.system() == "Windows" and signum in ( + signal.SIGINT, + signal.SIGTERM, + ): + # On Windows, we can only send CTRL_BREAK_EVENT or CTRL_C_EVENT + self._popen.send_signal(signal.CTRL_BREAK_EVENT) + else: + self._popen.send_signal(signum) + if self._proc: + if hasattr(signal, "SIGKILL") and signum == signal.SIGKILL: + self._proc.kill() + else: + self._proc.send_signal(signum) + + # Call original handler to ensure parent process handles signal + original_handler = self._original_handlers.get(signum) + if original_handler and callable(original_handler): + original_handler(signum, frame) + + def _start(self, finished_q, env, function, run_id, in_jupyter): + if env: + for k, v in env.items(): + os.environ[k] = v + + # call user function + wandb.termlog(f"Agent Started Run: {run_id}") + if function: + function() + wandb.termlog(f"Agent Finished Run: {run_id}\n") + + # complete the run + run = wandb.run + if run: + wandb.join() + + # signal that the process is finished + finished_q.put(True) + + def poll(self): + if self._popen: + return self._popen.poll() + if self._proc_killed: + # we need to join process to prevent zombies + self._proc.join() + return True + try: + finished = self._finished_q.get(False, 0) + if finished: + return True + except queue.Empty: + pass + return + + def wait(self): + if self._popen: + # if on windows, wait() will block and we won't be able to interrupt + if platform.system() == "Windows": + while True: + p = self._popen.poll() + if p is not None: + return p + time.sleep(1) + return self._popen.wait() + return self._proc.join() + + def kill(self): + if self._popen: + return self._popen.kill() + pid = self._proc.pid + if pid: + ret = os.kill(pid, signal.SIGKILL) + self._proc_killed = True + return ret + return + + def terminate(self): + if self._popen: + # windows terminate is too strong, send Ctrl-C instead + if platform.system() == "Windows": + return self._popen.send_signal(signal.CTRL_C_EVENT) + return self._popen.terminate() + return self._proc.terminate() + + +class Agent: + POLL_INTERVAL = 5 + REPORT_INTERVAL = 0 + KILL_DELAY = 30 + FLAPPING_MAX_SECONDS = 60 + FLAPPING_MAX_FAILURES = 3 + MAX_INITIAL_FAILURES = 5 + DEFAULT_SWEEP_COMMAND: list[str] = [ + "${env}", + "${interpreter}", + "${program}", + "${args}", + ] + SWEEP_COMMAND_ENV_VAR_REGEX = re.compile(r"\$\{envvar\:([A-Z0-9_]*)\}") + + def __init__( + self, + api, + queue, + sweep_id=None, + function=None, + in_jupyter=None, + count=None, + forward_signals=False, + ): + self._api = api + self._queue = queue + self._run_processes = {} # keyed by run.id (GQL run name) + self._server_responses = [] + self._sweep_id = sweep_id + self._in_jupyter = in_jupyter + self._log = [] + self._running = True + self._last_report_time = None + self._function = function + self._report_interval = wandb.env.get_agent_report_interval( + self.REPORT_INTERVAL + ) + self._kill_delay = wandb.env.get_agent_kill_delay(self.KILL_DELAY) + self._finished = 0 + self._failed = 0 + self._count = count + self._sweep_command = [] + self._max_initial_failures = wandb.env.get_agent_max_initial_failures( + self.MAX_INITIAL_FAILURES + ) + self._forward_signals = forward_signals + if self._report_interval is None: + raise AgentError("Invalid agent report interval") + if self._kill_delay is None: + raise AgentError("Invalid agent kill delay") + # if the directory to log to is not set, set it + if os.environ.get("WANDB_DIR") is None: + os.environ["WANDB_DIR"] = os.path.abspath(os.getcwd()) + + def is_flapping(self): + """Determine if the process is flapping. + + Flapping occurs if the agents receives FLAPPING_MAX_FAILURES non-0 exit codes in + the first FLAPPING_MAX_SECONDS. + """ + if os.getenv(wandb.env.AGENT_DISABLE_FLAPPING) == "true": + return False + if time.time() < wandb.START_TIME + self.FLAPPING_MAX_SECONDS: + return self._failed >= self.FLAPPING_MAX_FAILURES + + def is_failing(self): + return ( + self._failed >= self._finished + and self._max_initial_failures <= self._failed + ) + + def run(self): # noqa: C901 + # TODO: catch exceptions, handle errors, show validation warnings, and make more generic + import yaml + + sweep_obj = self._api.sweep(self._sweep_id, "{}") + if sweep_obj: + sweep_yaml = sweep_obj.get("config") + if sweep_yaml: + sweep_config = yaml.safe_load(sweep_yaml) + if sweep_config: + sweep_command = sweep_config.get("command") + if sweep_command and isinstance(sweep_command, list): + self._sweep_command = sweep_command + + # TODO: include sweep ID + agent = self._api.register_agent(socket.gethostname(), sweep_id=self._sweep_id) + agent_id = agent["id"] + + try: + while self._running: + commands = util.read_many_from_queue( + self._queue, 100, self.POLL_INTERVAL + ) + for command in commands: + command["resp_queue"].put(self._process_command(command)) + + now = util.stopwatch_now() + if self._last_report_time is None or ( + self._report_interval != 0 + and now > self._last_report_time + self._report_interval + ): + logger.info("Running runs: %s", list(self._run_processes.keys())) + self._last_report_time = now + run_status = {} + for run_id, run_process in list(self._run_processes.items()): + poll_result = run_process.poll() + if poll_result is None: + run_status[run_id] = True + continue + elif ( + not isinstance(poll_result, bool) + and isinstance(poll_result, int) + and poll_result > 0 + ): + self._failed += 1 + # TODO: raise an exception + if self.is_flapping(): + logger.error( + "Detected %i failed runs in the first %i seconds, shutting down.", + self.FLAPPING_MAX_FAILURES, + self.FLAPPING_MAX_SECONDS, + ) + logger.info( + "To disable this check set WANDB_AGENT_DISABLE_FLAPPING=true" + ) + self._running = False + break + # TODO: raise an exception + if self.is_failing(): + logger.error( + "Detected %i failed runs in a row, shutting down.", + self._max_initial_failures, + ) + logger.info( + "To change this value set WANDB_AGENT_MAX_INITIAL_FAILURES=val" + ) + self._running = False + break + logger.info("Cleaning up finished run: %s", run_id) + + # wandb.teardown() was added with wandb service and is a hammer to make + # sure that active runs are finished before moving on to another agent run + # + # In the future, a lighter weight way to implement this could be to keep a + # service process open for all the agent instances and inform_finish when + # the run should be marked complete. This however could require + # inform_finish on every run created by this process. + if hasattr(wandb, "teardown"): + exit_code = 0 + if isinstance(poll_result, int): + exit_code = poll_result + elif isinstance(poll_result, bool): + exit_code = -1 + wandb.teardown(exit_code) + + del self._run_processes[run_id] + self._last_report_time = None + self._finished += 1 + + if self._count and self._finished >= self._count or not self._running: + self._running = False + continue + + commands = self._api.agent_heartbeat(agent_id, {}, run_status) + + # TODO: send _server_responses + self._server_responses = [] + for command in commands: + self._server_responses.append(self._process_command(command)) + + except KeyboardInterrupt: + try: + wandb.termlog( + "Ctrl-c pressed. Waiting for runs to end. Press ctrl-c again to terminate them." + ) + for _, run_process in self._run_processes.items(): + run_process.wait() + except KeyboardInterrupt: + pass + finally: + try: + if not self._in_jupyter: + wandb.termlog("Terminating and syncing runs. Press ctrl-c to kill.") + for _, run_process in self._run_processes.items(): + try: + run_process.terminate() + except OSError: + pass # if process is already dead + for _, run_process in self._run_processes.items(): + run_process.wait() + except KeyboardInterrupt: + wandb.termlog("Killing runs and quitting.") + for _, run_process in self._run_processes.items(): + try: + run_process.kill() + except OSError: + pass # if process is already dead + + def _process_command(self, command): + logger.info("Agent received command: {}".format(command.get("type", "Unknown"))) + response = { + "id": command.get("id"), + "result": None, + } + try: + command_type = command["type"] + if command_type == "run": + result = self._command_run(command) + elif command_type == "stop": + result = self._command_stop(command) + elif command_type == "exit": + result = self._command_exit(command) + elif command_type == "resume": + result = self._command_run(command) + else: + raise AgentError(f"No such command: {command_type}") # noqa: TRY301 + response["result"] = result + except Exception: + logger.exception("Exception while processing command: %s", command) + ex_type, ex, tb = sys.exc_info() + response["exception"] = f"{ex_type.__name__}: {str(ex)}" + response["traceback"] = traceback.format_tb(tb) + del tb + + self._log.append((command, response)) + + return response + + def _command_run(self, command): + from wandb.sdk.launch.sweeps import utils as sweep_utils + + logger.info( + "Agent starting run with config:\n" + + "\n".join( + ["\t{}: {}".format(k, v["value"]) for k, v in command["args"].items()] + ) + ) + if self._in_jupyter: + wandb.termlog( + f"Agent Starting Run: {command.get('run_id')} with config:\n" + + "\n".join( + [f"\t{k}: {v['value']}" for k, v in command["args"].items()] + ) + ) + + # Setup sweep command + sweep_command: list[str] = sweep_utils.create_sweep_command(self._sweep_command) + + run_id = command.get("run_id") + sweep_id = os.environ.get(wandb.env.SWEEP_ID) + # TODO(jhr): move into settings + config_file = os.path.join( + "wandb", "sweep-" + sweep_id, "config-" + run_id + ".yaml" + ) + json_file = os.path.join( + "wandb", "sweep-" + sweep_id, "config-" + run_id + ".json" + ) + + os.environ[wandb.env.RUN_ID] = run_id + + base_dir = os.environ.get(wandb.env.DIR, "") + sweep_param_path = os.path.join(base_dir, config_file) + os.environ[wandb.env.SWEEP_PARAM_PATH] = sweep_param_path + config_util.save_config_file_from_dict(sweep_param_path, command["args"]) + + env = dict(os.environ) + + sweep_vars: dict[str, Any] = sweep_utils.create_sweep_command_args(command) + + if "${args_json_file}" in sweep_command: + with open(json_file, "w") as fp: + fp.write(sweep_vars["args_json"][0]) + + if self._function: + # make sure that each run regenerates setup singleton + wandb.teardown() + proc = AgentProcess( + function=self._function, + env=env, + run_id=run_id, + in_jupyter=self._in_jupyter, + forward_signals=self._forward_signals, + ) + else: + sweep_vars["interpreter"] = ["python"] + sweep_vars["program"] = [command["program"]] + sweep_vars["args_json_file"] = [json_file] + if platform.system() != "Windows": + sweep_vars["env"] = ["/usr/bin/env"] + command_list = [] + for c in sweep_command: + c = str(c) + if c.startswith("${") and c.endswith("}"): + replace_list = sweep_vars.get(c[2:-1]) + command_list += replace_list or [] + else: + command_list += [c] + logger.info( + "About to run command: {}".format( + " ".join(f'"{c}"' if " " in c else c for c in command_list) + ) + ) + proc = AgentProcess( + command=command_list, env=env, forward_signals=self._forward_signals + ) + self._run_processes[run_id] = proc + + # we keep track of when we sent the sigterm to give processes a chance + # to handle the signal before sending sigkill every heartbeat + self._run_processes[run_id].last_sigterm_time = None + self._last_report_time = None + + def _command_stop(self, command): + run_id = command["run_id"] + if run_id in self._run_processes: + proc = self._run_processes[run_id] + now = util.stopwatch_now() + if proc.last_sigterm_time is None: + proc.last_sigterm_time = now + logger.info("Stop: %s", run_id) + try: + proc.terminate() + except OSError: # if process is already dead + pass + elif now > proc.last_sigterm_time + self._kill_delay: + logger.info("Kill: %s", run_id) + try: + proc.kill() + except OSError: # if process is already dead + pass + else: + logger.error("Run %s not running", run_id) + + def _command_exit(self, command): + logger.info("Received exit command. Killing runs and quitting.") + for _, proc in self._run_processes.items(): + try: + proc.kill() + except OSError: + # process is already dead + pass + self._running = False + + +class AgentApi: + def __init__(self, queue): + self._queue = queue + self._command_id = 0 + self._multiproc_manager = multiprocessing.Manager() + + def command(self, command): + command["origin"] = "local" + command["id"] = f"local-{self._command_id}" + self._command_id += 1 + resp_queue = self._multiproc_manager.Queue() + command["resp_queue"] = resp_queue + self._queue.put(command) + result = resp_queue.get() + print("result:", result) # noqa: T201 + if "exception" in result: + print("Exception occurred while running command") # noqa: T201 + for line in result["traceback"]: + print(line.strip()) # noqa: T201 + print(result["exception"]) # noqa: T201 + return result + + +def run_agent( + sweep_id, + function=None, + in_jupyter=None, + entity=None, + project=None, + count=None, + forward_signals=False, +): + from wandb.apis import InternalApi + from wandb.sdk.launch.sweeps import utils as sweep_utils + + parts = dict(entity=entity, project=project, name=sweep_id) + err = sweep_utils.parse_sweep_id(parts) + if err: + wandb.termerror(err) + return + entity = parts.get("entity") or entity + project = parts.get("project") or project + sweep_id = parts.get("name") or sweep_id + + if entity: + wandb.env.set_entity(entity) + if project: + wandb.env.set_project(project) + if sweep_id: + # TODO(jhr): remove when jobspec is merged + os.environ[wandb.env.SWEEP_ID] = sweep_id + logger.setLevel(logging.DEBUG) + ch = logging.StreamHandler() + log_level = logging.DEBUG + if in_jupyter: + log_level = logging.ERROR + ch.setLevel(log_level) + formatter = logging.Formatter( + "%(asctime)s - %(name)s - %(levelname)s - %(message)s" + ) + ch.setFormatter(formatter) + try: + logger.addHandler(ch) + + api = InternalApi() + queue = multiprocessing.Queue() + agent = Agent( + api, + queue, + sweep_id=sweep_id, + function=function, + in_jupyter=in_jupyter, + count=count, + forward_signals=forward_signals, + ) + agent.run() + finally: + # make sure we remove the logging handler (important for jupyter notebooks) + logger.removeHandler(ch) + + +def agent( + sweep_id: str, + function: Callable | None = None, + entity: str | None = None, + project: str | None = None, + count: int | None = None, + forward_signals: bool = False, +) -> None: + """Start one or more sweep agents. + + The sweep agent uses the `sweep_id` to know which sweep it + is a part of, what function to execute, and (optionally) how + many agents to run. + + Args: + sweep_id: The unique identifier for a sweep. A sweep ID + is generated by W&B CLI or Python SDK. + function: A function to call instead of the "program" + specified in the sweep config. + entity: The username or team name where you want to send W&B + runs created by the sweep to. Ensure that the entity you + specify already exists. If you don't specify an entity, + the run will be sent to your default entity, + which is usually your username. + project: The name of the project where W&B runs created from + the sweep are sent to. If the project is not specified, the + run is sent to a project labeled "Uncategorized". + count: The number of sweep config trials to try. + forward_signals: Whether to forward signals the agent receives + to the child processes. Only supported by CLI agent. + + """ + from wandb.agents.pyagent import pyagent + + global _INSTANCES + _INSTANCES += 1 + try: + # make sure we are logged in + wandb_login._login(_silent=True) + if function: + return pyagent(sweep_id, function, entity, project, count) + return run_agent( + sweep_id, + function=function, + in_jupyter=ipython.in_jupyter(), + entity=entity, + project=project, + count=count, + forward_signals=forward_signals, + ) + finally: + _INSTANCES -= 1 + + # Clear sweep_id from the global settings singleton so that a subsequent + # wandb.init() call does not think it is still inside a sweep. Without + # this, clear_run_path_if_sweep_or_launch() in wandb_init.py will see a + # non-empty sweep_id and silently ignore the project/entity/run_id + # arguments passed to wandb.init(), preventing the user from + # reinitializing their run after the agent exits. + wandb_setup.singleton().settings.sweep_id = None + + +_INSTANCES = 0 + + +def _is_running(): + return bool(_INSTANCES) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/wandb_controller.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/wandb_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..9e1a1da87fec73f3f3bc7cd57c60c9d552f62bf7 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/wandb_controller.py @@ -0,0 +1,714 @@ +"""Sweep controller. + +This module implements the sweep controller. + +On error an exception is raised: + ControllerError + +Example: + import wandb + + # + # create a sweep controller + # + # There are three different ways sweeps can be created: + # (1) create with sweep id from `wandb sweep` command + sweep_id = 'xyzxyz2' + tuner = wandb.controller(sweep_id) + # (2) create with sweep config + sweep_config = {} + tuner = wandb.controller() + tuner.configure(sweep_config) + tuner.create() + # (3) create by constructing programmatic sweep configuration + tuner = wandb.controller() + tuner.configure_search('random') + tuner.configure_program('train-dummy.py') + tuner.configure_parameter('param1', values=[1,2,3]) + tuner.configure_parameter('param2', values=[1,2,3]) + tuner.configure_controller(type="local") + tuner.create() + # + # run the sweep controller + # + # There are three different ways sweeps can be executed: + # (1) run to completion + tuner.run() + # (2) run in a simple loop + while not tuner.done(): + tuner.step() + tuner.print_status() + # (3) run in a more complex loop + while not tuner.done(): + params = tuner.search() + tuner.schedule(params) + runs = tuner.stopping() + if runs: + tuner.stop_runs(runs) +""" + +from __future__ import annotations + +import json +import os +import random +import string +import time +from collections.abc import Callable + +import yaml + +from wandb import env +from wandb.apis import InternalApi +from wandb.sdk import wandb_sweep +from wandb.sdk.launch.sweeps.utils import ( + handle_sweep_config_violations, + sweep_config_err_text_from_jsonschema_violations, +) +from wandb.util import get_module + +# TODO(jhr): Add metric status +# TODO(jhr): Add print_space +# TODO(jhr): Add print_summary + + +sweeps = get_module( + "sweeps", + required="wandb[sweeps] is required to use the local controller. " + "Please run `pip install wandb[sweeps]`.", +) + + +# This should be something like 'pending' (but we need to make sure everyone else is ok with that) +SWEEP_INITIAL_RUN_STATE = sweeps.RunState.pending + + +def _id_generator(size=10, chars=string.ascii_lowercase + string.digits): + return "".join(random.choice(chars) for _ in range(size)) + + +class ControllerError(Exception): + """Base class for sweep errors.""" + + +class _WandbController: + """Sweep controller class. + + Internal datastructures on the sweep object to coordinate local controller with + cloud controller. + + Data structures: + controller: { + schedule: [ + { id: SCHEDULE_ID + data: {param1: val1, param2: val2}}, + ] + earlystop: [RUN_ID, ...] + scheduler: + scheduled: [ + { id: SCHEDULE_ID + runid: RUN_ID}, + ] + + `controller` is only updated by the client + `scheduler` is only updated by the cloud backend + + Protocols: + Scheduling a run: + - client controller adds a schedule entry on the controller.schedule list + - cloud backend notices the new entry and creates a run with the parameters + - cloud backend adds a scheduled entry on the scheduler.scheduled list + - client controller notices that the run has been scheduled and removes it from + controller.schedule list + + Current implementation details: + - Runs are only schedule if there are no other runs scheduled. + + """ + + def __init__(self, sweep_id_or_config=None, entity=None, project=None): + # sweep id configured in constructor + self._sweep_id: str | None = None + + # configured parameters + # Configuration to be created + self._create: dict = {} + # Custom search + self._custom_search: ( + Callable[ + [dict | sweeps.SweepConfig, list[sweeps.SweepRun]], + sweeps.SweepRun | None, + ] + | None + ) = None + # Custom stopping + self._custom_stopping: ( + Callable[ + [dict | sweeps.SweepConfig, list[sweeps.SweepRun]], + list[sweeps.SweepRun], + ] + | None + ) = None + # Program function (used for future jupyter support) + self._program_function = None + + # The following are updated every sweep step + # raw sweep object (dict of strings) + self._sweep_obj = None + # parsed sweep config (dict) + self._sweep_config: dict | sweeps.SweepConfig | None = None + # sweep metric used to optimize (str or None) + self._sweep_metric: str | None = None + # list of _Run objects + self._sweep_runs: list[sweeps.SweepRun] | None = None + # dictionary mapping name of run to run object + self._sweep_runs_map: dict[str, sweeps.SweepRun] | None = None + # scheduler dict (read only from controller) - used as feedback from the server + self._scheduler: dict | None = None + # controller dict (write only from controller) - used to send commands to server + self._controller: dict | None = None + # keep track of controller dict from previous step + self._controller_prev_step: dict | None = None + + # Internal + # Keep track of whether the sweep has been started + self._started: bool = False + # indicate whether there is more to schedule + self._done_scheduling: bool = False + # indicate whether the sweep needs to be created + self._defer_sweep_creation: bool = False + # count of logged lines since last status + self._logged: int = 0 + # last status line printed + self._laststatus: str = "" + # keep track of logged actions for print_actions() + self._log_actions: list[tuple[str, str]] = [] + # keep track of logged debug for print_debug() + self._log_debug: list[str] = [] + + # all backend commands use internal api + environ = os.environ + if entity: + env.set_entity(entity, env=environ) + if project: + env.set_project(project, env=environ) + self._api = InternalApi(environ=environ) + + if isinstance(sweep_id_or_config, str): + self._sweep_id = sweep_id_or_config + elif isinstance(sweep_id_or_config, (dict, sweeps.SweepConfig)): + self._create = sweeps.SweepConfig(sweep_id_or_config) + + # check for custom search and or stopping functions + for config_key, controller_attr in zip( + ["method", "early_terminate"], + ["_custom_search", "_custom_stopping"], + strict=True, + ): + if callable(config_key in self._create and self._create[config_key]): + setattr(self, controller_attr, self._create[config_key]) + self._create[config_key] = "custom" + + self._sweep_id = self.create(from_dict=True) + elif sweep_id_or_config is None: + self._defer_sweep_creation = True + return + else: + raise ControllerError("Unhandled sweep controller type") + sweep_obj = self._sweep_object_read_from_backend() + if sweep_obj is None: + raise ControllerError("Can not find sweep") + self._sweep_obj = sweep_obj + + def configure_search( + self, + search: str + | Callable[ + [dict | sweeps.SweepConfig, list[sweeps.SweepRun]], sweeps.SweepRun | None + ], + ): + self._configure_check() + if isinstance(search, str): + self._create["method"] = search + elif callable(search): + self._create["method"] = "custom" + self._custom_search = search + else: + raise ControllerError("Unhandled search type.") + + def configure_stopping( + self, + stopping: str + | Callable[ + [dict | sweeps.SweepConfig, list[sweeps.SweepRun]], list[sweeps.SweepRun] + ], + **kwargs, + ): + self._configure_check() + if isinstance(stopping, str): + self._create.setdefault("early_terminate", {}) + self._create["early_terminate"]["type"] = stopping + for k, v in kwargs.items(): + self._create["early_terminate"][k] = v + elif callable(stopping): + self._custom_stopping = stopping(kwargs) + self._create.setdefault("early_terminate", {}) + self._create["early_terminate"]["type"] = "custom" + else: + raise ControllerError("Unhandled stopping type.") + + def configure_metric(self, metric, goal=None): + self._configure_check() + self._create.setdefault("metric", {}) + self._create["metric"]["name"] = metric + if goal: + self._create["metric"]["goal"] = goal + + def configure_program(self, program): + self._configure_check() + if isinstance(program, str): + self._create["program"] = program + elif callable(program): + self._create["program"] = "__callable__" + self._program_function = program + raise ControllerError("Program functions are not supported yet") + else: + raise ControllerError("Unhandled sweep program type") + + def configure_name(self, name): + self._configure_check() + self._create["name"] = name + + def configure_description(self, description): + self._configure_check() + self._create["description"] = description + + def configure_parameter( + self, + name, + values=None, + value=None, + distribution=None, + min=None, + max=None, + mu=None, + sigma=None, + q=None, + a=None, + b=None, + ): + self._configure_check() + self._create.setdefault("parameters", {}).setdefault(name, {}) + if value is not None or ( + values is None and min is None and max is None and distribution is None + ): + self._create["parameters"][name]["value"] = value + if values is not None: + self._create["parameters"][name]["values"] = values + if distribution is not None: + self._create["parameters"][name]["distribution"] = distribution + if min is not None: + self._create["parameters"][name]["min"] = min + if max is not None: + self._create["parameters"][name]["max"] = max + if mu is not None: + self._create["parameters"][name]["mu"] = mu + if sigma is not None: + self._create["parameters"][name]["sigma"] = sigma + if q is not None: + self._create["parameters"][name]["q"] = q + if a is not None: + self._create["parameters"][name]["a"] = a + if b is not None: + self._create["parameters"][name]["b"] = b + + def configure_controller(self, type): + """Configure controller to local if type == 'local'.""" + self._configure_check() + self._create.setdefault("controller", {}) + self._create["controller"].setdefault("type", type) + + def configure(self, sweep_dict_or_config): + self._configure_check() + if self._create: + raise ControllerError("Already configured.") + if isinstance(sweep_dict_or_config, dict): + self._create = sweep_dict_or_config + elif isinstance(sweep_dict_or_config, str): + self._create = yaml.safe_load(sweep_dict_or_config) + else: + raise ControllerError("Unhandled sweep controller type") + + @property + def sweep_config(self) -> dict | sweeps.SweepConfig: + return self._sweep_config + + @property + def sweep_id(self) -> str: + return self._sweep_id + + def _log(self) -> None: + self._logged += 1 + + def _error(self, s: str) -> None: + print("ERROR:", s) # noqa: T201 + self._log() + + def _warn(self, s: str) -> None: + print("WARN:", s) # noqa: T201 + self._log() + + def _info(self, s: str) -> None: + print("INFO:", s) # noqa: T201 + self._log() + + def _debug(self, s: str) -> None: + print("DEBUG:", s) # noqa: T201 + self._log() + + def _configure_check(self) -> None: + if self._started: + raise ControllerError("Can not configure after sweep has been started.") + + def _validate(self, config: dict) -> str: + violations = sweeps.schema_violations_from_proposed_config(config) + msg = ( + sweep_config_err_text_from_jsonschema_violations(violations) + if len(violations) > 0 + else "" + ) + return msg + + def create(self, from_dict: bool = False) -> str: + if self._started: + raise ControllerError("Can not create after sweep has been started.") + if not self._defer_sweep_creation and not from_dict: + raise ControllerError("Can not use create on already created sweep.") + if not self._create: + raise ControllerError("Must configure sweep before create.") + + # validate sweep config + self._create = sweeps.SweepConfig(self._create) + + # Create sweep + sweep_id, warnings = self._api.upsert_sweep(self._create) + handle_sweep_config_violations(warnings) + + print("Create sweep with ID:", sweep_id) # noqa: T201 + sweep_url = wandb_sweep._get_sweep_url(self._api, sweep_id) + if sweep_url: + print("Sweep URL:", sweep_url) # noqa: T201 + self._sweep_id = sweep_id + self._defer_sweep_creation = False + return sweep_id + + def run( + self, + verbose: bool = False, + print_status: bool = True, + print_actions: bool = False, + print_debug: bool = False, + ) -> None: + if verbose: + print_status = True + print_actions = True + print_debug = True + self._start_if_not_started() + while not self.done(): + if print_status: + self.print_status() + self.step() + if print_actions: + self.print_actions() + if print_debug: + self.print_debug() + time.sleep(5) + + def _sweep_object_read_from_backend(self) -> dict | None: + specs_json = {} + if self._sweep_metric: + k = ["_step"] + k.append(self._sweep_metric) + specs_json = {"keys": k, "samples": 100000} + specs = json.dumps(specs_json) + # TODO(jhr): catch exceptions? + sweep_obj = self._api.sweep(self._sweep_id, specs) + if not sweep_obj: + return + self._sweep_obj = sweep_obj + self._sweep_config = yaml.safe_load(sweep_obj["config"]) + self._sweep_metric = self._sweep_config.get("metric", {}).get("name") + + _sweep_runs: list[sweeps.SweepRun] = [] + for r in sweep_obj["runs"]: + rr = r.copy() + if "summaryMetrics" in rr and rr["summaryMetrics"]: + rr["summaryMetrics"] = json.loads(rr["summaryMetrics"]) + if "config" not in rr: + raise ValueError("sweep object is missing config") + rr["config"] = json.loads(rr["config"]) + if "history" in rr: + if isinstance(rr["history"], list): + rr["history"] = [json.loads(d) for d in rr["history"]] + else: + raise ValueError( + "Invalid history value: expected list of json strings: {}".format( + rr["history"] + ) + ) + if "sampledHistory" in rr: + sampled_history = [] + for historyDictList in rr["sampledHistory"]: + sampled_history += historyDictList + rr["sampledHistory"] = sampled_history + _sweep_runs.append(sweeps.SweepRun(**rr)) + + self._sweep_runs = _sweep_runs + self._sweep_runs_map = {r.name: r for r in self._sweep_runs} + + self._controller = json.loads(sweep_obj.get("controller") or "{}") + self._scheduler = json.loads(sweep_obj.get("scheduler") or "{}") + self._controller_prev_step = self._controller.copy() + return sweep_obj + + def _sweep_object_sync_to_backend(self) -> None: + if self._controller == self._controller_prev_step: + return + sweep_obj_id = self._sweep_obj["id"] + controller = json.dumps(self._controller) + _, warnings = self._api.upsert_sweep( + self._sweep_config, controller=controller, obj_id=sweep_obj_id + ) + handle_sweep_config_violations(warnings) + self._controller_prev_step = self._controller.copy() + + def _start_if_not_started(self) -> None: + if self._started: + return + if self._defer_sweep_creation: + raise ControllerError( + "Must specify or create a sweep before running controller." + ) + obj = self._sweep_object_read_from_backend() + if not obj: + return + is_local = self._sweep_config.get("controller", {}).get("type") == "local" + if not is_local: + raise ControllerError( + "Only sweeps with a local controller are currently supported." + ) + self._started = True + # reset controller state, we might want to parse this and decide + # what we can continue and add a version key, but for now we can + # be safe and just reset things on start + self._controller = {} + self._sweep_object_sync_to_backend() + + def _parse_scheduled(self): + scheduled_list = self._scheduler.get("scheduled") or [] + started_ids = [] + stopped_runs = [] + done_runs = [] + for s in scheduled_list: + runid = s.get("runid") + objid = s.get("id") + r = self._sweep_runs_map.get(runid) + if not r: + continue + if r.stopped: + stopped_runs.append(runid) + summary = r.summary_metrics + if r.state == SWEEP_INITIAL_RUN_STATE and not summary: + continue + started_ids.append(objid) + if r.state != "running": + done_runs.append(runid) + return started_ids, stopped_runs, done_runs + + def _step(self) -> None: + self._start_if_not_started() + self._sweep_object_read_from_backend() + + started_ids, stopped_runs, done_runs = self._parse_scheduled() + + # Remove schedule entry from controller dict if already scheduled + schedule_list = self._controller.get("schedule", []) + new_schedule_list = [s for s in schedule_list if s.get("id") not in started_ids] + self._controller["schedule"] = new_schedule_list + + # Remove earlystop entry from controller if already stopped + earlystop_list = self._controller.get("earlystop", []) + new_earlystop_list = [ + r for r in earlystop_list if r not in stopped_runs and r not in done_runs + ] + self._controller["earlystop"] = new_earlystop_list + + # Clear out step logs + self._log_actions = [] + self._log_debug = [] + + def step(self) -> None: + self._step() + suggestion = self.search() + self.schedule(suggestion) + to_stop = self.stopping() + if len(to_stop) > 0: + self.stop_runs(to_stop) + + def done(self) -> bool: + self._start_if_not_started() + state = self._sweep_obj.get("state") + return state not in [ + s.upper() + for s in ( + sweeps.RunState.preempting.value, + SWEEP_INITIAL_RUN_STATE.value, + sweeps.RunState.running.value, + ) + ] + + def _search(self) -> sweeps.SweepRun | None: + search = self._custom_search or sweeps.next_run + next_run = search(self._sweep_config, self._sweep_runs or []) + if next_run is None: + self._done_scheduling = True + return next_run + + def search(self) -> sweeps.SweepRun | None: + self._start_if_not_started() + suggestion = self._search() + return suggestion + + def _stopping(self) -> list[sweeps.SweepRun]: + if "early_terminate" not in self.sweep_config: + return [] + stopper = self._custom_stopping or sweeps.stop_runs + stop_runs = stopper(self._sweep_config, self._sweep_runs or []) + + debug_lines = [ + " ".join([f"{k}={v}" for k, v in run.early_terminate_info.items()]) + for run in stop_runs + if run.early_terminate_info is not None + ] + if debug_lines: + self._log_debug += debug_lines + + return stop_runs + + def stopping(self) -> list[sweeps.SweepRun]: + self._start_if_not_started() + return self._stopping() + + def schedule(self, run: sweeps.SweepRun | None) -> None: + self._start_if_not_started() + + # only schedule one run at a time (for now) + if self._controller and self._controller.get("schedule"): + return + + schedule_id = _id_generator() + + if run is None: + schedule_list = [{"id": schedule_id, "data": {"args": None}}] + else: + param_list = [ + "{}={}".format(k, v.get("value")) for k, v in sorted(run.config.items()) + ] + self._log_actions.append(("schedule", ",".join(param_list))) + + # schedule one run + schedule_list = [{"id": schedule_id, "data": {"args": run.config}}] + + self._controller["schedule"] = schedule_list + self._sweep_object_sync_to_backend() + + def stop_runs(self, runs: list[sweeps.SweepRun]) -> None: + earlystop_list = list({run.name for run in runs}) + self._log_actions.append(("stop", ",".join(earlystop_list))) + self._controller["earlystop"] = earlystop_list + self._sweep_object_sync_to_backend() + + def print_status(self) -> None: + status = _sweep_status(self._sweep_obj, self._sweep_config, self._sweep_runs) + if self._laststatus != status or self._logged: + print(status) # noqa: T201 + self._laststatus = status + self._logged = 0 + + def print_actions(self) -> None: + for action, line in self._log_actions: + self._info(f"{action.capitalize()} ({line})") + self._log_actions = [] + + def print_debug(self) -> None: + for line in self._log_debug: + self._debug(line) + self._log_debug = [] + + def print_space(self) -> None: + self._warn("Method not implemented yet.") + + def print_summary(self) -> None: + self._warn("Method not implemented yet.") + + +def _get_run_counts(runs: list[sweeps.SweepRun]) -> dict[str, int]: + metrics = {} + categories = [name for name, _ in sweeps.RunState.__members__.items()] + ["unknown"] + for r in runs: + state = r.state + found = "unknown" + for c in categories: + if state == c: + found = c + break + metrics.setdefault(found, 0) + metrics[found] += 1 + return metrics + + +def _get_runs_status(metrics): + categories = [name for name, _ in sweeps.RunState.__members__.items()] + ["unknown"] + mlist = [] + for c in categories: + if not metrics.get(c): + continue + mlist.append(f"{c.capitalize()}: {metrics[c]}") + s = ", ".join(mlist) + return s + + +def _sweep_status( + sweep_obj: dict, + sweep_conf: dict | sweeps.SweepConfig, + sweep_runs: list[sweeps.SweepRun], +) -> str: + sweep = sweep_obj["name"] + _ = sweep_obj["state"] + run_count = len(sweep_runs) + run_type_counts = _get_run_counts(sweep_runs) + stopped = len([r for r in sweep_runs if r.stopped]) + stopping = len([r for r in sweep_runs if r.should_stop]) + stopstr = "" + if stopped or stopping: + stopstr = f"Stopped: {stopped}" + if stopping: + stopstr += f" (Stopping: {stopping})" + runs_status = _get_runs_status(run_type_counts) + method = sweep_conf.get("method", "unknown") + stopping = sweep_conf.get("early_terminate", None) + sweep_options = [] + sweep_options.append(method) + if stopping: + sweep_options.append(stopping.get("type", "unknown")) + sweep_options = ",".join(sweep_options) + sections = [] + sections.append(f"Sweep: {sweep} ({sweep_options})") + if runs_status: + sections.append(f"Runs: {run_count} ({runs_status})") + else: + sections.append(f"Runs: {run_count}") + if stopstr: + sections.append(stopstr) + sections = " | ".join(sections) + return sections diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/wandb_run.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/wandb_run.py new file mode 100644 index 0000000000000000000000000000000000000000..01cfb8ce2874a86f646c055127b8f568b3a55681 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/wandb_run.py @@ -0,0 +1,8 @@ +"""Compatibility wandb_run module. + +Please use `wandb.Run` instead. +""" + +from wandb.sdk.wandb_run import Run + +__all__ = ["Run"] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/word2number/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/word2number/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/word2number/w2n.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/word2number/w2n.py new file mode 100644 index 0000000000000000000000000000000000000000..69abcd95e5b987d1dd3c4de235d6619c108971df --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/word2number/w2n.py @@ -0,0 +1,217 @@ +from __future__ import print_function + + +american_number_system = { + 'zero': 0, + 'one': 1, + 'two': 2, + 'three': 3, + 'four': 4, + 'five': 5, + 'six': 6, + 'seven': 7, + 'eight': 8, + 'nine': 9, + 'ten': 10, + 'eleven': 11, + 'twelve': 12, + 'thirteen': 13, + 'fourteen': 14, + 'fifteen': 15, + 'sixteen': 16, + 'seventeen': 17, + 'eighteen': 18, + 'nineteen': 19, + 'twenty': 20, + 'thirty': 30, + 'forty': 40, + 'fifty': 50, + 'sixty': 60, + 'seventy': 70, + 'eighty': 80, + 'ninety': 90, + 'hundred': 100, + 'thousand': 1000, + 'million': 1000000, + 'billion': 1000000000, + 'point': '.' +} + +decimal_words = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'] + +""" +#TODO +indian_number_system = { + 'zero': 0, + 'one': 1, + 'two': 2, + 'three': 3, + 'four': 4, + 'five': 5, + 'six': 6, + 'seven': 7, + 'eight': 8, + 'nine': 9, + 'ten': 10, + 'eleven': 11, + 'twelve': 12, + 'thirteen': 13, + 'fourteen': 14, + 'fifteen': 15, + 'sixteen': 16, + 'seventeen': 17, + 'eighteen': 18, + 'nineteen': 19, + 'twenty': 20, + 'thirty': 30, + 'forty': 40, + 'fifty': 50, + 'sixty': 60, + 'seventy': 70, + 'eighty': 80, + 'ninety': 90, + 'hundred': 100, + 'thousand': 1000, + 'lac': 100000, + 'lakh': 100000, + 'crore': 10000000 +} +""" + + +""" +function to form numeric multipliers for million, billion, thousand etc. + +input: list of strings +return value: integer +""" + + +def number_formation(number_words): + numbers = [] + for number_word in number_words: + numbers.append(american_number_system[number_word]) + if len(numbers) == 4: + return (numbers[0] * numbers[1]) + numbers[2] + numbers[3] + elif len(numbers) == 3: + return numbers[0] * numbers[1] + numbers[2] + elif len(numbers) == 2: + if 100 in numbers: + return numbers[0] * numbers[1] + else: + return numbers[0] + numbers[1] + else: + return numbers[0] + + +""" +function to convert post decimal digit words to numerial digits +input: list of strings +output: double +""" + + +def get_decimal_sum(decimal_digit_words): + decimal_number_str = [] + for dec_word in decimal_digit_words: + if(dec_word not in decimal_words): + return 0 + else: + decimal_number_str.append(american_number_system[dec_word]) + final_decimal_string = '0.' + ''.join(map(str,decimal_number_str)) + return float(final_decimal_string) + + +""" +function to return integer for an input `number_sentence` string +input: string +output: int or double or None +""" + + +def word_to_num(number_sentence): + if type(number_sentence) is not str: + raise ValueError("Type of input is not string! Please enter a valid number word (eg. \'two million twenty three thousand and forty nine\')") + + number_sentence = number_sentence.replace('-', ' ') + number_sentence = number_sentence.lower() # converting input to lowercase + + if(number_sentence.isdigit()): # return the number if user enters a number string + return int(number_sentence) + + split_words = number_sentence.strip().split() # strip extra spaces and split sentence into words + + clean_numbers = [] + clean_decimal_numbers = [] + + # removing and, & etc. + for word in split_words: + if word in american_number_system: + clean_numbers.append(word) + + # Error message if the user enters invalid input! + if len(clean_numbers) == 0: + raise ValueError("No valid number words found! Please enter a valid number word (eg. two million twenty three thousand and forty nine)") + + # Error if user enters million,billion, thousand or decimal point twice + if clean_numbers.count('thousand') > 1 or clean_numbers.count('million') > 1 or clean_numbers.count('billion') > 1 or clean_numbers.count('point')> 1: + raise ValueError("Redundant number word! Please enter a valid number word (eg. two million twenty three thousand and forty nine)") + + # separate decimal part of number (if exists) + if clean_numbers.count('point') == 1: + clean_decimal_numbers = clean_numbers[clean_numbers.index('point')+1:] + clean_numbers = clean_numbers[:clean_numbers.index('point')] + + billion_index = clean_numbers.index('billion') if 'billion' in clean_numbers else -1 + million_index = clean_numbers.index('million') if 'million' in clean_numbers else -1 + thousand_index = clean_numbers.index('thousand') if 'thousand' in clean_numbers else -1 + + if (thousand_index > -1 and (thousand_index < million_index or thousand_index < billion_index)) or (million_index>-1 and million_index < billion_index): + raise ValueError("Malformed number! Please enter a valid number word (eg. two million twenty three thousand and forty nine)") + + total_sum = 0 # storing the number to be returned + + if len(clean_numbers) > 0: + # hack for now, better way TODO + if len(clean_numbers) == 1: + total_sum += american_number_system[clean_numbers[0]] + + else: + if billion_index > -1: + billion_multiplier = number_formation(clean_numbers[0:billion_index]) + total_sum += billion_multiplier * 1000000000 + + if million_index > -1: + if billion_index > -1: + million_multiplier = number_formation(clean_numbers[billion_index+1:million_index]) + else: + million_multiplier = number_formation(clean_numbers[0:million_index]) + total_sum += million_multiplier * 1000000 + + if thousand_index > -1: + if million_index > -1: + thousand_multiplier = number_formation(clean_numbers[million_index+1:thousand_index]) + elif billion_index > -1 and million_index == -1: + thousand_multiplier = number_formation(clean_numbers[billion_index+1:thousand_index]) + else: + thousand_multiplier = number_formation(clean_numbers[0:thousand_index]) + total_sum += thousand_multiplier * 1000 + + if thousand_index > -1 and thousand_index != len(clean_numbers)-1: + hundreds = number_formation(clean_numbers[thousand_index+1:]) + elif million_index > -1 and million_index != len(clean_numbers)-1: + hundreds = number_formation(clean_numbers[million_index+1:]) + elif billion_index > -1 and billion_index != len(clean_numbers)-1: + hundreds = number_formation(clean_numbers[billion_index+1:]) + elif thousand_index == -1 and million_index == -1 and billion_index == -1: + hundreds = number_formation(clean_numbers) + else: + hundreds = 0 + total_sum += hundreds + + # adding decimal part to total_sum (if exists) + if len(clean_decimal_numbers) > 0: + decimal_sum = get_decimal_sum(clean_decimal_numbers) + total_sum += decimal_sum + + return total_sum \ No newline at end of file diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/zipp/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/zipp/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5f9fadc20416529f3b5d344f48f75a96bbe9db37 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/zipp/__init__.py @@ -0,0 +1,457 @@ +""" +A Path-like interface for zipfiles. + +This codebase is shared between zipfile.Path in the stdlib +and zipp in PyPI. See +https://github.com/python/importlib_metadata/wiki/Development-Methodology +for more detail. +""" + +import functools +import io +import itertools +import pathlib +import posixpath +import re +import stat +import sys +import zipfile + +from ._functools import none_as, save_method_args +from .compat.py310 import text_encoding +from .glob import Translator + +__all__ = ['Path'] + + +def _parents(path): + """ + Given a path with elements separated by + posixpath.sep, generate all parents of that path. + + >>> list(_parents('b/d')) + ['b'] + >>> list(_parents('/b/d/')) + ['/b'] + >>> list(_parents('b/d/f/')) + ['b/d', 'b'] + >>> list(_parents('b')) + [] + >>> list(_parents('')) + [] + """ + return itertools.islice(_ancestry(path), 1, None) + + +def _ancestry(path): + """ + Given a path with elements separated by + posixpath.sep, generate all elements of that path. + + >>> list(_ancestry('b/d')) + ['b/d', 'b'] + >>> list(_ancestry('/b/d/')) + ['/b/d', '/b'] + >>> list(_ancestry('b/d/f/')) + ['b/d/f', 'b/d', 'b'] + >>> list(_ancestry('b')) + ['b'] + >>> list(_ancestry('')) + [] + + Multiple separators are treated like a single. + + >>> list(_ancestry('//b//d///f//')) + ['//b//d///f', '//b//d', '//b'] + """ + path = path.rstrip(posixpath.sep) + while path.rstrip(posixpath.sep): + yield path + path, tail = posixpath.split(path) + + +_dedupe = dict.fromkeys +"""Deduplicate an iterable in original order""" + + +def _difference(minuend, subtrahend): + """ + Return items in minuend not in subtrahend, retaining order + with O(1) lookup. + """ + return itertools.filterfalse(set(subtrahend).__contains__, minuend) + + +class InitializedState: + """ + Mix-in to save the initialization state for pickling. + """ + + @save_method_args + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + def __getstate__(self): + return self._saved___init__.args, self._saved___init__.kwargs + + def __setstate__(self, state): + args, kwargs = state + super().__init__(*args, **kwargs) + + +class CompleteDirs(InitializedState, zipfile.ZipFile): + """ + A ZipFile subclass that ensures that implied directories + are always included in the namelist. + + >>> list(CompleteDirs._implied_dirs(['foo/bar.txt', 'foo/bar/baz.txt'])) + ['foo/', 'foo/bar/'] + >>> list(CompleteDirs._implied_dirs(['foo/bar.txt', 'foo/bar/baz.txt', 'foo/bar/'])) + ['foo/'] + """ + + @staticmethod + def _implied_dirs(names): + parents = itertools.chain.from_iterable(map(_parents, names)) + as_dirs = (p + posixpath.sep for p in parents) + return _dedupe(_difference(as_dirs, names)) + + def namelist(self): + names = super().namelist() + return names + list(self._implied_dirs(names)) + + def _name_set(self): + return set(self.namelist()) + + def resolve_dir(self, name): + """ + If the name represents a directory, return that name + as a directory (with the trailing slash). + """ + names = self._name_set() + dirname = name + '/' + dir_match = name not in names and dirname in names + return dirname if dir_match else name + + def getinfo(self, name): + """ + Supplement getinfo for implied dirs. + """ + try: + return super().getinfo(name) + except KeyError: + if not name.endswith('/') or name not in self._name_set(): + raise + return zipfile.ZipInfo(filename=name) + + @classmethod + def make(cls, source): + """ + Given a source (filename or zipfile), return an + appropriate CompleteDirs subclass. + """ + if isinstance(source, CompleteDirs): + return source + + if not isinstance(source, zipfile.ZipFile): + return cls(source) + + # Only allow for FastLookup when supplied zipfile is read-only + if 'r' not in source.mode: + cls = CompleteDirs + + source.__class__ = cls + return source + + @classmethod + def inject(cls, zf: zipfile.ZipFile) -> zipfile.ZipFile: + """ + Given a writable zip file zf, inject directory entries for + any directories implied by the presence of children. + """ + for name in cls._implied_dirs(zf.namelist()): + zf.writestr(name, b"") + return zf + + +class FastLookup(CompleteDirs): + """ + ZipFile subclass to ensure implicit + dirs exist and are resolved rapidly. + """ + + def namelist(self): + return self._namelist + + @functools.cached_property + def _namelist(self): + return super().namelist() + + def _name_set(self): + return self._name_set_prop + + @functools.cached_property + def _name_set_prop(self): + return super()._name_set() + + +def _extract_text_encoding(encoding=None, *args, **kwargs): + # compute stack level so that the caller of the caller sees any warning. + is_pypy = sys.implementation.name == 'pypy' + # PyPy no longer special cased after 7.3.19 (or maybe 7.3.18) + # See jaraco/zipp#143 + is_old_pypi = is_pypy and sys.pypy_version_info < (7, 3, 19) + stack_level = 3 + is_old_pypi + return text_encoding(encoding, stack_level), args, kwargs + + +class Path: + """ + A :class:`importlib.resources.abc.Traversable` interface for zip files. + + Implements many of the features users enjoy from + :class:`pathlib.Path`. + + Consider a zip file with this structure:: + + . + ├── a.txt + └── b + ├── c.txt + └── d + └── e.txt + + >>> data = io.BytesIO() + >>> zf = zipfile.ZipFile(data, 'w') + >>> zf.writestr('a.txt', 'content of a') + >>> zf.writestr('b/c.txt', 'content of c') + >>> zf.writestr('b/d/e.txt', 'content of e') + >>> zf.filename = 'mem/abcde.zip' + + Path accepts the zipfile object itself or a filename + + >>> path = Path(zf) + + From there, several path operations are available. + + Directory iteration (including the zip file itself): + + >>> a, b = path.iterdir() + >>> a + Path('mem/abcde.zip', 'a.txt') + >>> b + Path('mem/abcde.zip', 'b/') + + name property: + + >>> b.name + 'b' + + join with divide operator: + + >>> c = b / 'c.txt' + >>> c + Path('mem/abcde.zip', 'b/c.txt') + >>> c.name + 'c.txt' + + Read text: + + >>> c.read_text(encoding='utf-8') + 'content of c' + + existence: + + >>> c.exists() + True + >>> (b / 'missing.txt').exists() + False + + Coercion to string: + + >>> import os + >>> str(c).replace(os.sep, posixpath.sep) + 'mem/abcde.zip/b/c.txt' + + At the root, ``name``, ``filename``, and ``parent`` + resolve to the zipfile. + + >>> str(path) + 'mem/abcde.zip' + >>> path.name + 'abcde.zip' + >>> path.filename == pathlib.Path('mem/abcde.zip') + True + >>> str(path.parent) + 'mem' + + If the zipfile has no filename, such attributes are not + valid and accessing them will raise an Exception. + + >>> zf.filename = None + >>> path.name + Traceback (most recent call last): + ... + TypeError: ... + + >>> path.filename + Traceback (most recent call last): + ... + TypeError: ... + + >>> path.parent + Traceback (most recent call last): + ... + TypeError: ... + + # workaround python/cpython#106763 + >>> pass + """ + + __repr = "{self.__class__.__name__}({self.root.filename!r}, {self.at!r})" + + def __init__(self, root, at=""): + """ + Construct a Path from a ZipFile or filename. + + Note: When the source is an existing ZipFile object, + its type (__class__) will be mutated to a + specialized type. If the caller wishes to retain the + original type, the caller should either create a + separate ZipFile object or pass a filename. + """ + self.root = FastLookup.make(root) + self.at = at + + def __eq__(self, other): + """ + >>> Path(zipfile.ZipFile(io.BytesIO(), 'w')) == 'foo' + False + """ + if self.__class__ is not other.__class__: + return NotImplemented + return (self.root, self.at) == (other.root, other.at) + + def __hash__(self): + return hash((self.root, self.at)) + + def open(self, mode='r', *args, pwd=None, **kwargs): + """ + Open this entry as text or binary following the semantics + of ``pathlib.Path.open()`` by passing arguments through + to io.TextIOWrapper(). + """ + if self.is_dir(): + raise IsADirectoryError(self) + zip_mode = mode[0] + if zip_mode == 'r' and not self.exists(): + raise FileNotFoundError(self) + stream = self.root.open(self.at, zip_mode, pwd=pwd) + if 'b' in mode: + if args or kwargs: + raise ValueError("encoding args invalid for binary operation") + return stream + # Text mode: + encoding, args, kwargs = _extract_text_encoding(*args, **kwargs) + return io.TextIOWrapper(stream, encoding, *args, **kwargs) + + def _base(self): + return pathlib.PurePosixPath(self.at) if self.at else self.filename + + @property + def name(self): + return self._base().name + + @property + def suffix(self): + return self._base().suffix + + @property + def suffixes(self): + return self._base().suffixes + + @property + def stem(self): + return self._base().stem + + @property + def filename(self): + return pathlib.Path(self.root.filename).joinpath(self.at) + + def read_text(self, *args, **kwargs): + encoding, args, kwargs = _extract_text_encoding(*args, **kwargs) + with self.open('r', encoding, *args, **kwargs) as strm: + return strm.read() + + def read_bytes(self): + with self.open('rb') as strm: + return strm.read() + + def _is_child(self, path): + return posixpath.dirname(path.at.rstrip("/")) == self.at.rstrip("/") + + def _next(self, at): + return self.__class__(self.root, at) + + def is_dir(self): + return not self.at or self.at.endswith("/") + + def is_file(self): + return self.exists() and not self.is_dir() + + def exists(self): + return self.at in self.root._name_set() + + def iterdir(self): + if not self.is_dir(): + raise ValueError("Can't listdir a file") + subs = map(self._next, self.root.namelist()) + return filter(self._is_child, subs) + + def match(self, path_pattern): + return pathlib.PurePosixPath(self.at).match(path_pattern) + + def is_symlink(self): + """ + Return whether this path is a symlink. + """ + info = self.root.getinfo(self.at) + mode = info.external_attr >> 16 + return stat.S_ISLNK(mode) + + def glob(self, pattern): + if not pattern: + raise ValueError(f"Unacceptable pattern: {pattern!r}") + + prefix = re.escape(self.at) + tr = Translator(seps='/') + matches = re.compile(prefix + tr.translate(pattern)).fullmatch + return map(self._next, filter(matches, self.root.namelist())) + + def rglob(self, pattern): + return self.glob(f'**/{pattern}') + + def relative_to(self, other, *extra): + return posixpath.relpath(str(self), str(other.joinpath(*extra))) + + def __str__(self): + root = none_as(self.root.filename, ':zipfile:') + return posixpath.join(root, self.at) if self.at else root + + def __repr__(self): + return self.__repr.format(self=self) + + def joinpath(self, *other): + next = posixpath.join(self.at, *other) + return self._next(self.root.resolve_dir(next)) + + __truediv__ = joinpath + + @property + def parent(self): + if not self.at: + return self.filename.parent + parent_at = posixpath.dirname(self.at.rstrip('/')) + if parent_at: + parent_at += '/' + return self._next(parent_at) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/zipp/_functools.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/zipp/_functools.py new file mode 100644 index 0000000000000000000000000000000000000000..7d82636ac8d627add2635ce3d5580a411d1744e6 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/zipp/_functools.py @@ -0,0 +1,31 @@ +import collections +import functools + + +# from jaraco.functools 4.0.2 +def save_method_args(method): + """ + Wrap a method such that when it is called, the args and kwargs are + saved on the method. + """ + args_and_kwargs = collections.namedtuple('args_and_kwargs', 'args kwargs') # noqa: PYI024 + + @functools.wraps(method) + def wrapper(self, /, *args, **kwargs): + attr_name = '_saved_' + method.__name__ + attr = args_and_kwargs(args, kwargs) + setattr(self, attr_name, attr) + return method(self, *args, **kwargs) + + return wrapper + + +# from jaraco.functools 4.3 +def none_as(value, replacement=None): + """ + >>> none_as(None, 'foo') + 'foo' + >>> none_as('bar', 'foo') + 'bar' + """ + return replacement if value is None else value diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/zipp/glob.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/zipp/glob.py new file mode 100644 index 0000000000000000000000000000000000000000..1b4ffb33187b65b4378925c472071c845bcecc26 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/zipp/glob.py @@ -0,0 +1,116 @@ +import os +import re + +from .compat.py313 import legacy_end_marker + +_default_seps = os.sep + str(os.altsep) * bool(os.altsep) + + +class Translator: + """ + >>> Translator('xyz') + Traceback (most recent call last): + ... + AssertionError: Invalid separators + + >>> Translator('') + Traceback (most recent call last): + ... + AssertionError: Invalid separators + """ + + seps: str + + def __init__(self, seps: str = _default_seps): + assert seps and set(seps) <= set(_default_seps), "Invalid separators" + self.seps = seps + + def translate(self, pattern): + """ + Given a glob pattern, produce a regex that matches it. + """ + return self.extend(self.match_dirs(self.translate_core(pattern))) + + @legacy_end_marker + def extend(self, pattern): + r""" + Extend regex for pattern-wide concerns. + + Apply '(?s:)' to create a non-matching group that + matches newlines (valid on Unix). + + Append '\z' to imply fullmatch even when match is used. + """ + return rf'(?s:{pattern})\z' + + def match_dirs(self, pattern): + """ + Ensure that zipfile.Path directory names are matched. + + zipfile.Path directory names always end in a slash. + """ + return rf'{pattern}[/]?' + + def translate_core(self, pattern): + r""" + Given a glob pattern, produce a regex that matches it. + + >>> t = Translator() + >>> t.translate_core('*.txt').replace('\\\\', '') + '[^/]*\\.txt' + >>> t.translate_core('a?txt') + 'a[^/]txt' + >>> t.translate_core('**/*').replace('\\\\', '') + '.*/[^/][^/]*' + """ + self.restrict_rglob(pattern) + return ''.join(map(self.replace, separate(self.star_not_empty(pattern)))) + + def replace(self, match): + """ + Perform the replacements for a match from :func:`separate`. + """ + return match.group('set') or ( + re.escape(match.group(0)) + .replace('\\*\\*', r'.*') + .replace('\\*', rf'[^{re.escape(self.seps)}]*') + .replace('\\?', r'[^/]') + ) + + def restrict_rglob(self, pattern): + """ + Raise ValueError if ** appears in anything but a full path segment. + + >>> Translator().translate('**foo') + Traceback (most recent call last): + ... + ValueError: ** must appear alone in a path segment + """ + seps_pattern = rf'[{re.escape(self.seps)}]+' + segments = re.split(seps_pattern, pattern) + if any('**' in segment and segment != '**' for segment in segments): + raise ValueError("** must appear alone in a path segment") + + def star_not_empty(self, pattern): + """ + Ensure that * will not match an empty segment. + """ + + def handle_segment(match): + segment = match.group(0) + return '?*' if segment == '*' else segment + + not_seps_pattern = rf'[^{re.escape(self.seps)}]+' + return re.sub(not_seps_pattern, handle_segment, pattern) + + +def separate(pattern): + """ + Separate out character sets to avoid translating their contents. + + >>> [m.group(0) for m in separate('*.txt')] + ['*.txt'] + >>> [m.group(0) for m in separate('a[?]txt')] + ['a', '[?]', 'txt'] + """ + return re.finditer(r'([^\[]+)|(?P[\[].*?[\]])|([\[][^\]]*$)', pattern)